first commit
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
"""Zhenyang doctor workstation."""
|
||||
|
||||
__all__ = ["__version__"]
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,19 @@
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from doctor_workstation.app import main
|
||||
|
||||
|
||||
def _run() -> int:
|
||||
try:
|
||||
return main()
|
||||
except Exception:
|
||||
if "--smoke-test" not in sys.argv and os.getenv("DOCTOR_SMOKE_TEST") != "1":
|
||||
raise
|
||||
traceback.print_exc()
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(_run())
|
||||
@@ -0,0 +1,830 @@
|
||||
"""Application composition root for the doctor workstation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QLibraryInfo, QLocale, QObject, Qt, QTimer, QTranslator
|
||||
from PySide6.QtGui import QGuiApplication, QIcon
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QDialog,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from doctor_workstation.config import AppConfig
|
||||
from doctor_workstation.core import Session
|
||||
from doctor_workstation.core.errors import AuthenticationExpiredError
|
||||
from doctor_workstation.logging_setup import configure_logging
|
||||
from doctor_workstation.resources import resource_path, video_dist_path
|
||||
from doctor_workstation.services import (
|
||||
DemoDoctorRepository,
|
||||
RemoteDoctorRepository,
|
||||
TokenStore,
|
||||
build_repository,
|
||||
)
|
||||
from doctor_workstation.ui import LoginWindow, ShellWindow, apply_theme
|
||||
from doctor_workstation.ui.widgets import (
|
||||
friendly_error,
|
||||
run_async,
|
||||
set_authentication_expired_handler,
|
||||
show_toast,
|
||||
)
|
||||
from doctor_workstation.video import BackendMode, launch_video_call
|
||||
from doctor_workstation.video.window import WEBENGINE_AVAILABLE
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _ChineseQtTranslator(QTranslator):
|
||||
"""Guarantee Chinese labels for common Qt standard buttons.
|
||||
|
||||
Qt's packaged ``qtbase_zh_CN`` catalog remains the primary source for
|
||||
framework text. This small fallback also keeps release builds localized
|
||||
when a packager omits the optional ``.qm`` files.
|
||||
"""
|
||||
|
||||
_BUTTON_TEXT = {
|
||||
"OK": "确定",
|
||||
"Open": "打开",
|
||||
"Save": "保存",
|
||||
"Save All": "全部保存",
|
||||
"Cancel": "取消",
|
||||
"Close": "关闭",
|
||||
"Yes": "是",
|
||||
"Yes to All": "全部确认",
|
||||
"No": "否",
|
||||
"No to All": "全部否定",
|
||||
"Abort": "中止",
|
||||
"Retry": "重试",
|
||||
"Ignore": "忽略",
|
||||
"Discard": "放弃",
|
||||
"Help": "帮助",
|
||||
"Apply": "应用",
|
||||
"Reset": "重置",
|
||||
"Restore Defaults": "恢复默认设置",
|
||||
"Don't Save": "不保存",
|
||||
}
|
||||
|
||||
def translate(
|
||||
self,
|
||||
context: str,
|
||||
source_text: str,
|
||||
disambiguation: str | None = None,
|
||||
n: int = -1,
|
||||
) -> str | None:
|
||||
del context, disambiguation, n
|
||||
# Returning an empty string tells Qt that an unknown source string has
|
||||
# a valid, deliberately empty translation. That also erased internal
|
||||
# values such as QPageSize's "A4", producing zero-sized PDF pages.
|
||||
# ``None`` delegates unknown text to Qt's installed catalog/source.
|
||||
return self._BUTTON_TEXT.get(source_text.replace("&", ""))
|
||||
|
||||
|
||||
def _install_chinese_translations(application: QApplication) -> None:
|
||||
"""Install Simplified Chinese Qt catalogs once for the whole process."""
|
||||
|
||||
if getattr(application, "_doctor_workstation_chinese_translators", None):
|
||||
return
|
||||
|
||||
QLocale.setDefault(QLocale("zh_CN"))
|
||||
translators: list[QTranslator] = []
|
||||
translations_path = QLibraryInfo.path(QLibraryInfo.LibraryPath.TranslationsPath)
|
||||
for catalog in ("qt_zh_CN", "qtbase_zh_CN"):
|
||||
translator = QTranslator(application)
|
||||
if translator.load(catalog, translations_path):
|
||||
application.installTranslator(translator)
|
||||
translators.append(translator)
|
||||
|
||||
fallback = _ChineseQtTranslator(application)
|
||||
application.installTranslator(fallback)
|
||||
translators.append(fallback)
|
||||
application._doctor_workstation_chinese_translators = translators # type: ignore[attr-defined]
|
||||
|
||||
|
||||
class _UnconfiguredRepository:
|
||||
"""Login boundary used until an administrator supplies a backend URL."""
|
||||
|
||||
def login(
|
||||
self,
|
||||
account: str,
|
||||
password: str,
|
||||
*,
|
||||
remember_account: bool = False,
|
||||
) -> Session:
|
||||
del account, password, remember_account
|
||||
raise ValueError("请先展开“服务器设置”,填写管理员提供的 HTTPS 接口地址。")
|
||||
|
||||
def get_current_user(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class DemoVideoDialog(QDialog):
|
||||
"""Non-network video-room preview used only by the explicit demo mode."""
|
||||
|
||||
def __init__(self, patient_name: str, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self._seconds = 0
|
||||
self.setWindowTitle("视频面诊 · 演示模式")
|
||||
self.setMinimumSize(760, 520)
|
||||
self.resize(980, 660)
|
||||
self.setModal(False)
|
||||
self.setStyleSheet(
|
||||
"QDialog{background:#F7F9FE;color:#111F46;}"
|
||||
"QLabel{color:#111F46;}"
|
||||
"QFrame#RemoteStage{background:#0E1421;border:1px solid #29334F;border-radius:16px;}"
|
||||
"QFrame#RemoteStage QLabel{color:#F7F9FE;}"
|
||||
"QFrame#LocalStage{background:#151D31;border:1px solid #3F4E75;border-radius:12px;}"
|
||||
"QPushButton{min-width:96px;min-height:40px;padding:0 16px;border-radius:9px;"
|
||||
"background:#FFFFFF;color:#3F4E75;border:1px solid #E6EAF5;font-weight:600;}"
|
||||
"QPushButton:hover{color:#4451E2;background:#F0F2FF;border-color:#5761F4;}"
|
||||
"QPushButton:checked{color:#FFFFFF;background:#5761F4;border-color:#5761F4;}"
|
||||
"QPushButton#Hangup{color:#FFFFFF;background:#F15B67;border-color:#F15B67;}"
|
||||
"QPushButton#Hangup:hover{background:#D94857;border-color:#D94857;}"
|
||||
)
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(22, 18, 22, 22)
|
||||
root.setSpacing(14)
|
||||
header = QHBoxLayout()
|
||||
title = QLabel(f"与 {patient_name or '患者'} 的视频面诊")
|
||||
title.setStyleSheet("font-size:18px;font-weight:700;")
|
||||
header.addWidget(title)
|
||||
header.addStretch(1)
|
||||
demo = QLabel("● 演示模式 · 未连接腾讯云")
|
||||
demo.setStyleSheet("color:#7886AA;font-size:12px;")
|
||||
header.addWidget(demo)
|
||||
self.duration_label = QLabel("00:00")
|
||||
self.duration_label.setStyleSheet("font-weight:700;")
|
||||
header.addWidget(self.duration_label)
|
||||
root.addLayout(header)
|
||||
|
||||
stage = QFrame()
|
||||
stage.setObjectName("RemoteStage")
|
||||
stage_layout = QVBoxLayout(stage)
|
||||
stage_layout.setContentsMargins(22, 22, 22, 22)
|
||||
stage_layout.addStretch(1)
|
||||
avatar = QLabel((patient_name or "患")[:1])
|
||||
avatar.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
avatar.setFixedSize(104, 104)
|
||||
avatar.setStyleSheet(
|
||||
"background:#F0F2FF;color:#5761F4;border-radius:52px;font-size:42px;font-weight:700;"
|
||||
)
|
||||
stage_layout.addWidget(avatar, 0, Qt.AlignmentFlag.AlignHCenter)
|
||||
waiting = QLabel("等待患者接听…")
|
||||
waiting.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
waiting.setStyleSheet("font-size:17px;font-weight:600;")
|
||||
stage_layout.addWidget(waiting)
|
||||
hint = QLabel("生产模式将通过后端短时 UserSig 初始化腾讯 TUICallKit")
|
||||
hint.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
hint.setStyleSheet("color:#A4ADC3;font-size:12px;")
|
||||
stage_layout.addWidget(hint)
|
||||
stage_layout.addStretch(1)
|
||||
|
||||
local = QFrame(stage)
|
||||
local.setObjectName("LocalStage")
|
||||
local.setGeometry(24, 24, 178, 112)
|
||||
local_layout = QVBoxLayout(local)
|
||||
local_label = QLabel("医生画面")
|
||||
local_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
local_label.setStyleSheet("color:#D9E0F2;font-weight:600;")
|
||||
local_layout.addWidget(local_label)
|
||||
root.addWidget(stage, 1)
|
||||
|
||||
controls = QHBoxLayout()
|
||||
controls.addStretch(1)
|
||||
self.mic_button = QPushButton("麦克风 开")
|
||||
self.mic_button.setCheckable(True)
|
||||
self.mic_button.toggled.connect(
|
||||
lambda muted: self.mic_button.setText("麦克风 关" if muted else "麦克风 开")
|
||||
)
|
||||
controls.addWidget(self.mic_button)
|
||||
self.camera_button = QPushButton("摄像头 开")
|
||||
self.camera_button.setCheckable(True)
|
||||
self.camera_button.toggled.connect(
|
||||
lambda off: self.camera_button.setText("摄像头 关" if off else "摄像头 开")
|
||||
)
|
||||
controls.addWidget(self.camera_button)
|
||||
hangup = QPushButton("结束面诊")
|
||||
hangup.setObjectName("Hangup")
|
||||
hangup.clicked.connect(self.close)
|
||||
controls.addWidget(hangup)
|
||||
controls.addStretch(1)
|
||||
root.addLayout(controls)
|
||||
|
||||
self._timer = QTimer(self)
|
||||
self._timer.timeout.connect(self._tick)
|
||||
self._timer.start(1000)
|
||||
|
||||
def _tick(self) -> None:
|
||||
self._seconds += 1
|
||||
minutes, seconds = divmod(self._seconds, 60)
|
||||
self.duration_label.setText(f"{minutes:02d}:{seconds:02d}")
|
||||
|
||||
|
||||
class ApplicationController(QObject):
|
||||
"""Own windows, repositories and the authenticated application lifecycle."""
|
||||
|
||||
def __init__(self, application: QApplication, config: AppConfig) -> None:
|
||||
super().__init__()
|
||||
self.application = application
|
||||
self.config = config
|
||||
self.token_store = TokenStore(config.config_dir / "credentials.json")
|
||||
self.demo_repository = DemoDoctorRepository()
|
||||
self.remote_repository: RemoteDoctorRepository | None = None
|
||||
self.login_window: LoginWindow | None = None
|
||||
self.shell_window: ShellWindow | None = None
|
||||
self.current_repository: Any = None
|
||||
self.current_demo_mode = config.demo_mode
|
||||
self.video_calls: dict[str, Any] = {}
|
||||
self.video_pending: dict[str, object] = {}
|
||||
self.demo_video_dialogs: dict[str, DemoVideoDialog] = {}
|
||||
self._restore_generation = 0
|
||||
self._restore_in_progress = False
|
||||
self._restore_worker: Any = None
|
||||
self._shutting_down = False
|
||||
self._authentication_expiry_in_progress = False
|
||||
self._rebuild_remote_repository()
|
||||
set_authentication_expired_handler(self._on_authentication_expired)
|
||||
application.aboutToQuit.connect(self.shutdown)
|
||||
|
||||
def start(self) -> None:
|
||||
"""Show login immediately, then validate a production token off-thread."""
|
||||
|
||||
self._show_login()
|
||||
self._begin_session_restore()
|
||||
|
||||
def _base_repository(self) -> Any:
|
||||
return self.remote_repository or _UnconfiguredRepository()
|
||||
|
||||
def _show_login(self) -> None:
|
||||
if self.login_window is None:
|
||||
self.login_window = LoginWindow(
|
||||
self._base_repository(),
|
||||
self.config,
|
||||
self.demo_repository,
|
||||
credential_store=self.token_store,
|
||||
)
|
||||
self.login_window.login_succeeded.connect(self._on_login_succeeded)
|
||||
self.login_window.config_changed.connect(self._on_config_changed)
|
||||
self.login_window.demo_mode_changed.connect(self._on_demo_mode_changed)
|
||||
self._apply_window_icon(self.login_window)
|
||||
else:
|
||||
self.login_window.repository = self._base_repository()
|
||||
self.login_window.config = self.config
|
||||
if not self.login_window.demo_check.isChecked():
|
||||
self.login_window.active_repository = self._base_repository()
|
||||
self.login_window.restore_remembered_credentials()
|
||||
self.login_window.show()
|
||||
self.login_window.raise_()
|
||||
self.login_window.activateWindow()
|
||||
|
||||
def _on_config_changed(self, payload: Any) -> None:
|
||||
previous_connection = (
|
||||
self.config.api_base_url,
|
||||
self.config.request_timeout,
|
||||
self.config.verify_ssl,
|
||||
)
|
||||
if isinstance(payload, AppConfig):
|
||||
updated = payload
|
||||
elif isinstance(payload, dict):
|
||||
aliases = {
|
||||
"base_url": "api_base_url",
|
||||
"read_timeout": "request_timeout",
|
||||
}
|
||||
changes = {aliases.get(key, key): value for key, value in payload.items()}
|
||||
allowed = {
|
||||
"api_base_url",
|
||||
"demo_mode",
|
||||
"video_mode",
|
||||
"video_web_url",
|
||||
"verify_ssl",
|
||||
"request_timeout",
|
||||
"log_level",
|
||||
"remembered_account",
|
||||
}
|
||||
updated = self.config.with_updates(
|
||||
**{key: value for key, value in changes.items() if key in allowed}
|
||||
)
|
||||
else:
|
||||
return
|
||||
self.config = updated
|
||||
with suppress(OSError):
|
||||
self.config.save_preferences()
|
||||
next_connection = (
|
||||
self.config.api_base_url,
|
||||
self.config.request_timeout,
|
||||
self.config.verify_ssl,
|
||||
)
|
||||
if next_connection != previous_connection:
|
||||
self._cancel_session_restore()
|
||||
self._rebuild_remote_repository()
|
||||
if self.login_window is not None:
|
||||
self.login_window.repository = self._base_repository()
|
||||
if not self.login_window.demo_check.isChecked():
|
||||
self.login_window.active_repository = self._base_repository()
|
||||
if self.login_window is not None:
|
||||
self.login_window.config = self.config
|
||||
|
||||
def _on_demo_mode_changed(self, enabled: bool) -> None:
|
||||
self.current_demo_mode = enabled
|
||||
if enabled:
|
||||
self._cancel_session_restore()
|
||||
|
||||
def _rebuild_remote_repository(self) -> None:
|
||||
old = self.remote_repository
|
||||
self.remote_repository = None
|
||||
if self.config.api_base_url:
|
||||
repository = build_repository(
|
||||
demo=False,
|
||||
base_url=self.config.api_base_url,
|
||||
token_store=self.token_store,
|
||||
timeout=self.config.request_timeout,
|
||||
verify=self.config.verify_ssl,
|
||||
)
|
||||
if isinstance(repository, RemoteDoctorRepository):
|
||||
self.remote_repository = repository
|
||||
if old is not None and old is not self.current_repository:
|
||||
with suppress(Exception):
|
||||
old.client.close()
|
||||
|
||||
def _begin_session_restore(self) -> None:
|
||||
"""Validate a scoped persisted token without racing manual login."""
|
||||
|
||||
repository = self.remote_repository
|
||||
if (
|
||||
self._shutting_down
|
||||
or self.config.demo_mode
|
||||
or repository is None
|
||||
or self.current_repository is not None
|
||||
):
|
||||
return
|
||||
self._restore_generation += 1
|
||||
generation = self._restore_generation
|
||||
self._restore_in_progress = True
|
||||
if self.login_window is not None:
|
||||
self.login_window.set_session_restore_pending(True)
|
||||
self._restore_worker = run_async(
|
||||
repository.restore_session,
|
||||
on_success=lambda session: self._on_restore_success(
|
||||
session,
|
||||
repository,
|
||||
generation,
|
||||
),
|
||||
on_error=lambda error: self._on_restore_error(
|
||||
error,
|
||||
repository,
|
||||
generation,
|
||||
),
|
||||
on_finished=lambda: self._on_restore_finished(repository, generation),
|
||||
)
|
||||
|
||||
def _restore_is_current(
|
||||
self,
|
||||
repository: RemoteDoctorRepository,
|
||||
generation: int,
|
||||
) -> bool:
|
||||
"""Return whether a restore callback still owns the login surface."""
|
||||
|
||||
return (
|
||||
not self._shutting_down
|
||||
and self._restore_in_progress
|
||||
and generation == self._restore_generation
|
||||
and repository is self.remote_repository
|
||||
)
|
||||
|
||||
def _finish_session_restore(
|
||||
self,
|
||||
repository: RemoteDoctorRepository,
|
||||
generation: int,
|
||||
) -> bool:
|
||||
"""Release login controls only for the currently active restore."""
|
||||
|
||||
if not self._restore_is_current(repository, generation):
|
||||
return False
|
||||
self._restore_in_progress = False
|
||||
self._restore_worker = None
|
||||
if self.login_window is not None:
|
||||
self.login_window.set_session_restore_pending(False)
|
||||
return True
|
||||
|
||||
def _on_restore_success(
|
||||
self,
|
||||
session: object,
|
||||
repository: RemoteDoctorRepository,
|
||||
generation: int,
|
||||
) -> None:
|
||||
"""Enter the shell only for a current, fully validated session."""
|
||||
|
||||
if not self._finish_session_restore(repository, generation):
|
||||
return
|
||||
if session is None:
|
||||
return
|
||||
if not isinstance(session, Session) or not session.authenticated:
|
||||
with suppress(Exception):
|
||||
repository.logout()
|
||||
self._login_guard_error("已保存的登录状态无效,请重新登录。")
|
||||
return
|
||||
self._on_login_succeeded(
|
||||
{
|
||||
"session": session,
|
||||
"user": session.user,
|
||||
"repository": repository,
|
||||
"demo_mode": False,
|
||||
"restored_session": True,
|
||||
}
|
||||
)
|
||||
|
||||
def _on_restore_error(
|
||||
self,
|
||||
error: Exception,
|
||||
repository: RemoteDoctorRepository,
|
||||
generation: int,
|
||||
) -> None:
|
||||
"""Return control to login after a current restore attempt fails."""
|
||||
|
||||
if not self._finish_session_restore(repository, generation):
|
||||
return
|
||||
if isinstance(error, AuthenticationExpiredError):
|
||||
message = "登录状态已失效,请重新登录。"
|
||||
else:
|
||||
message = f"自动恢复登录失败:{friendly_error(error)}"
|
||||
self._login_guard_error(message)
|
||||
|
||||
def _on_restore_finished(
|
||||
self,
|
||||
repository: RemoteDoctorRepository,
|
||||
generation: int,
|
||||
) -> None:
|
||||
"""Release controls when a worker finishes without a result callback."""
|
||||
|
||||
self._finish_session_restore(repository, generation)
|
||||
|
||||
def _cancel_session_restore(self) -> None:
|
||||
"""Invalidate late callbacks and re-enable manual login controls."""
|
||||
|
||||
self._restore_generation += 1
|
||||
if not self._restore_in_progress:
|
||||
return
|
||||
self._restore_in_progress = False
|
||||
self._restore_worker = None
|
||||
if self.login_window is not None:
|
||||
self.login_window.set_session_restore_pending(False)
|
||||
|
||||
def _on_login_succeeded(self, payload: dict[str, Any]) -> None:
|
||||
self._cancel_session_restore()
|
||||
session = payload.get("session")
|
||||
repository = payload.get("repository")
|
||||
if not isinstance(session, Session) or repository is None:
|
||||
self._login_guard_error("登录响应不完整,请重试。")
|
||||
return
|
||||
if session.password_change_required:
|
||||
with suppress(Exception):
|
||||
repository.logout()
|
||||
self._login_guard_error("该账号需要先修改初始密码,请在管理后台完成后重新登录。")
|
||||
return
|
||||
if session.work_wechat_binding_required:
|
||||
with suppress(Exception):
|
||||
repository.logout()
|
||||
self._login_guard_error("该账号需要先绑定企业微信,请在管理后台完成绑定后重新登录。")
|
||||
return
|
||||
|
||||
demo_mode = bool(payload.get("demo_mode"))
|
||||
if not demo_mode and not session.menu:
|
||||
with suppress(Exception):
|
||||
repository.logout()
|
||||
self._login_guard_error("当前账号没有可用医生端菜单,请联系管理员授权。")
|
||||
return
|
||||
|
||||
self.current_repository = repository
|
||||
self._authentication_expiry_in_progress = False
|
||||
self.current_demo_mode = demo_mode
|
||||
self.shell_window = ShellWindow(repository, payload, session.permissions)
|
||||
self.shell_window.logout_requested.connect(self._logout)
|
||||
self.shell_window.video_requested.connect(self._request_video)
|
||||
self._apply_window_icon(self.shell_window)
|
||||
if self.login_window is not None:
|
||||
self.login_window.hide()
|
||||
self.shell_window.show()
|
||||
self.shell_window.raise_()
|
||||
self.shell_window.activateWindow()
|
||||
|
||||
def _login_guard_error(self, message: str) -> None:
|
||||
if self.login_window is not None:
|
||||
self.login_window.error_banner.show_message(message, "warning")
|
||||
self.login_window.show()
|
||||
|
||||
def _on_authentication_expired(self, error: AuthenticationExpiredError) -> bool:
|
||||
"""Consume an active-shell expiry and atomically return to login."""
|
||||
|
||||
if self.shell_window is None or self.current_repository is None:
|
||||
return False
|
||||
if self._authentication_expiry_in_progress:
|
||||
return True
|
||||
self._authentication_expiry_in_progress = True
|
||||
LOGGER.info(
|
||||
"authenticated session expired",
|
||||
extra={"api_code": error.code, "request_id": error.request_id},
|
||||
)
|
||||
self._logout(message="登录状态已失效,请重新登录。")
|
||||
return True
|
||||
|
||||
def _logout(self, *, message: str = "") -> None:
|
||||
"""Clear authenticated resources and return to the login window."""
|
||||
|
||||
calls = tuple(self.video_calls.values())
|
||||
for call in calls:
|
||||
with suppress(Exception):
|
||||
call.close()
|
||||
self._wait_for_video_lifecycle(calls, timeout=1.25)
|
||||
self.video_calls.clear()
|
||||
self.video_pending.clear()
|
||||
for dialog in self.demo_video_dialogs.values():
|
||||
dialog.close()
|
||||
self.demo_video_dialogs.clear()
|
||||
if self.current_repository is not None:
|
||||
with suppress(Exception):
|
||||
self.current_repository.logout()
|
||||
self.current_repository = None
|
||||
if self.shell_window is not None:
|
||||
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")
|
||||
|
||||
def _request_video(self, payload: dict[str, Any]) -> None:
|
||||
parent = self.shell_window
|
||||
if parent is None or self.current_repository is None:
|
||||
return
|
||||
patient_id = payload.get("patient_id")
|
||||
diagnosis_id = payload.get("diagnosis_id")
|
||||
patient_name = str(payload.get("patient_name") or "患者")
|
||||
open_im = str(payload.get("mode") or "video").lower() == "im"
|
||||
if patient_id in (None, "") or diagnosis_id in (None, ""):
|
||||
show_toast(parent, "患者或诊单信息不完整,无法发起视频。", "danger", 4200)
|
||||
return
|
||||
|
||||
call_key = str(diagnosis_id)
|
||||
existing_call = self.video_calls.get(call_key)
|
||||
if open_im and existing_call is not None and getattr(existing_call, "open_im", False):
|
||||
qt_window = getattr(existing_call, "qt_window", None)
|
||||
if qt_window is not None:
|
||||
qt_window.show()
|
||||
qt_window.raise_()
|
||||
qt_window.activateWindow()
|
||||
show_toast(parent, "该患者的 IM 会话已经打开。", "info", 3200)
|
||||
return
|
||||
if (
|
||||
call_key in self.video_pending
|
||||
or existing_call is not None
|
||||
or call_key in self.demo_video_dialogs
|
||||
):
|
||||
show_toast(parent, "该问诊的视频正在准备或通话中。", "info", 3600)
|
||||
return
|
||||
|
||||
closed_previous_im = False
|
||||
if open_im:
|
||||
for key, call in tuple(self.video_calls.items()):
|
||||
if key == call_key or not getattr(call, "open_im", False):
|
||||
continue
|
||||
closed_previous_im = True
|
||||
self.video_calls.pop(key, None)
|
||||
with suppress(Exception):
|
||||
call.close()
|
||||
|
||||
if self.current_demo_mode:
|
||||
dialog = DemoVideoDialog(patient_name, parent)
|
||||
dialog.finished.connect(
|
||||
lambda _result, key=call_key, item=dialog: self._forget_demo_dialog(
|
||||
key,
|
||||
item,
|
||||
)
|
||||
)
|
||||
self.demo_video_dialogs[call_key] = dialog
|
||||
dialog.show()
|
||||
return
|
||||
|
||||
show_toast(
|
||||
parent,
|
||||
"正在打开患者 IM 会话…" if open_im else "正在获取安全通话凭证…",
|
||||
"info",
|
||||
)
|
||||
repository = self.current_repository
|
||||
marker = object()
|
||||
self.video_pending[call_key] = marker
|
||||
|
||||
def get_ticket() -> Any:
|
||||
return repository.get_call_ticket(
|
||||
patient_id=int(patient_id),
|
||||
diagnosis_id=int(diagnosis_id),
|
||||
)
|
||||
|
||||
def request_ticket() -> None:
|
||||
if self.video_pending.get(call_key) is not marker:
|
||||
return
|
||||
run_async(
|
||||
get_ticket,
|
||||
on_success=lambda ticket: self._launch_video(
|
||||
ticket,
|
||||
diagnosis_id=diagnosis_id,
|
||||
patient_id=patient_id,
|
||||
repository=repository,
|
||||
call_key=call_key,
|
||||
marker=marker,
|
||||
open_im=open_im,
|
||||
patient_name=patient_name,
|
||||
),
|
||||
on_error=lambda error: self._video_ticket_error(
|
||||
call_key,
|
||||
marker,
|
||||
parent,
|
||||
error,
|
||||
),
|
||||
)
|
||||
|
||||
# Tencent IM may take a brief moment to release the previous browser
|
||||
# connection. The admin version also has only one ChatDialog instance.
|
||||
if closed_previous_im:
|
||||
QTimer.singleShot(400, request_ticket)
|
||||
else:
|
||||
request_ticket()
|
||||
|
||||
def _video_ticket_error(
|
||||
self,
|
||||
call_key: str,
|
||||
marker: object,
|
||||
parent: QWidget,
|
||||
error: Exception,
|
||||
) -> None:
|
||||
if self.video_pending.get(call_key) is not marker:
|
||||
return
|
||||
self.video_pending.pop(call_key, None)
|
||||
if self.shell_window is parent:
|
||||
show_toast(
|
||||
parent,
|
||||
f"视频准备失败:{friendly_error(error)}",
|
||||
"danger",
|
||||
5200,
|
||||
)
|
||||
|
||||
def _launch_video(
|
||||
self,
|
||||
ticket: Any,
|
||||
*,
|
||||
diagnosis_id: Any,
|
||||
patient_id: Any,
|
||||
repository: Any,
|
||||
call_key: str,
|
||||
marker: object,
|
||||
open_im: bool = False,
|
||||
patient_name: str = "患者",
|
||||
) -> None:
|
||||
if self.video_pending.get(call_key) is not marker:
|
||||
return
|
||||
self.video_pending.pop(call_key, None)
|
||||
if (
|
||||
self.shell_window is None
|
||||
or self.current_repository is not repository
|
||||
or call_key in self.video_calls
|
||||
):
|
||||
return
|
||||
try:
|
||||
mode = BackendMode.parse(self.config.video_mode)
|
||||
if mode is BackendMode.BROWSER:
|
||||
raise ValueError("当前后端未提供一次性通话交接票据,浏览器视频模式已安全停用。")
|
||||
if not WEBENGINE_AVAILABLE:
|
||||
raise ValueError("当前安装缺少 QtWebEngine,无法打开受信任的视频窗口。")
|
||||
call = launch_video_call(
|
||||
ticket,
|
||||
repository=repository,
|
||||
diagnosis_id=diagnosis_id,
|
||||
patient_id=patient_id,
|
||||
backend_mode=mode,
|
||||
local_dist=video_dist_path(),
|
||||
remote_url=self.config.video_web_url or None,
|
||||
logger=logging.getLogger("doctor_workstation.video"),
|
||||
open_im=open_im,
|
||||
patient_name=patient_name,
|
||||
)
|
||||
except Exception as error:
|
||||
LOGGER.exception("video call could not be launched")
|
||||
show_toast(
|
||||
self.shell_window,
|
||||
f"视频启动失败:{friendly_error(error)}",
|
||||
"danger",
|
||||
5600,
|
||||
)
|
||||
return
|
||||
self.video_calls[call_key] = call
|
||||
qt_window = getattr(call, "qt_window", None)
|
||||
if qt_window is not None:
|
||||
qt_window.destroyed.connect(
|
||||
lambda _obj=None, key=call_key, expected=call: self._release_video_call(
|
||||
key,
|
||||
expected,
|
||||
)
|
||||
)
|
||||
|
||||
def _release_video_call(self, call_key: str, call: Any) -> None:
|
||||
if self.video_calls.get(call_key) is call:
|
||||
self.video_calls.pop(call_key, None)
|
||||
|
||||
def _forget_demo_dialog(self, call_key: str, dialog: DemoVideoDialog) -> None:
|
||||
if self.demo_video_dialogs.get(call_key) is dialog:
|
||||
self.demo_video_dialogs.pop(call_key, None)
|
||||
dialog.deleteLater()
|
||||
|
||||
@staticmethod
|
||||
def _wait_for_video_lifecycle(calls: tuple[Any, ...], *, timeout: float) -> bool:
|
||||
"""Give queued endCall writes one short shared deadline after media closes."""
|
||||
|
||||
deadline = time.monotonic() + max(0.0, timeout)
|
||||
complete = True
|
||||
for call in calls:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
complete = False
|
||||
break
|
||||
wait = getattr(call, "wait_for_lifecycle", None)
|
||||
if callable(wait) and not wait(remaining):
|
||||
complete = False
|
||||
if not complete:
|
||||
LOGGER.warning("video lifecycle cleanup exceeded its bounded deadline")
|
||||
return complete
|
||||
|
||||
@staticmethod
|
||||
def _apply_window_icon(window: QWidget) -> None:
|
||||
icon_file = resource_path("icon.svg")
|
||||
if icon_file.exists():
|
||||
window.setWindowIcon(QIcon(str(icon_file)))
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Invalidate asynchronous restoration and release owned resources."""
|
||||
|
||||
if self._shutting_down:
|
||||
return
|
||||
self._shutting_down = True
|
||||
self._cancel_session_restore()
|
||||
set_authentication_expired_handler(None)
|
||||
calls = tuple(self.video_calls.values())
|
||||
for call in calls:
|
||||
with suppress(Exception):
|
||||
call.close()
|
||||
self._wait_for_video_lifecycle(calls, timeout=1.25)
|
||||
if self.remote_repository is not None:
|
||||
with suppress(Exception):
|
||||
self.remote_repository.client.close()
|
||||
|
||||
|
||||
def _create_application(argv: list[str]) -> QApplication:
|
||||
with suppress(AttributeError):
|
||||
QGuiApplication.setHighDpiScaleFactorRoundingPolicy(
|
||||
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
|
||||
)
|
||||
with suppress(AttributeError):
|
||||
QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontCreateNativeWidgetSiblings, True)
|
||||
application = QApplication(argv)
|
||||
_install_chinese_translations(application)
|
||||
application.setApplicationName("甄养堂医生工作站")
|
||||
application.setApplicationDisplayName("甄养堂医生工作站")
|
||||
application.setOrganizationName("ZhenYangTang")
|
||||
application.setOrganizationDomain("zhenyangtang.com")
|
||||
application.setQuitOnLastWindowClosed(True)
|
||||
icon_file = resource_path("icon.svg")
|
||||
if icon_file.exists():
|
||||
application.setWindowIcon(QIcon(str(icon_file)))
|
||||
apply_theme(application)
|
||||
return application
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Start the GUI application and return its process exit code."""
|
||||
|
||||
config = AppConfig.load()
|
||||
configure_logging(config.log_dir, config.log_level)
|
||||
LOGGER.info("doctor workstation starting", extra={"demo_mode": config.demo_mode})
|
||||
raw_argv = list(sys.argv if argv is None else argv)
|
||||
smoke_test = "--smoke-test" in raw_argv
|
||||
application = _create_application(
|
||||
[argument for argument in raw_argv if argument != "--smoke-test"]
|
||||
)
|
||||
controller = ApplicationController(application, config)
|
||||
controller.start()
|
||||
if smoke_test or os.getenv("DOCTOR_SMOKE_TEST") == "1":
|
||||
QTimer.singleShot(1200, application.quit)
|
||||
return application.exec()
|
||||
|
||||
|
||||
__all__ = ["ApplicationController", "DemoVideoDialog", "main"]
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Application configuration and per-user preferences.
|
||||
|
||||
Secrets are intentionally excluded: the desktop client only receives a short-lived
|
||||
TRTC UserSig from the authenticated backend and never stores an SDKSecretKey.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from contextlib import suppress
|
||||
from dataclasses import asdict, dataclass, fields, replace
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
except ImportError: # pragma: no cover - optional during pure unit tests
|
||||
load_dotenv = None
|
||||
|
||||
try:
|
||||
from platformdirs import user_config_dir, user_log_dir
|
||||
except ImportError: # pragma: no cover - deterministic fallback
|
||||
user_config_dir = None
|
||||
user_log_dir = None
|
||||
|
||||
|
||||
APP_NAME = "ZhenyangDoctor"
|
||||
APP_AUTHOR = "Zhenyangtang"
|
||||
|
||||
|
||||
def _as_bool(value: Any, default: bool) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if value is None:
|
||||
return default
|
||||
return str(value).strip().lower() in {"1", "true", "yes", "on", "y"}
|
||||
|
||||
|
||||
def _safe_timeout(value: str | int | float | None, default: float = 30.0) -> float:
|
||||
try:
|
||||
parsed = float(value) # type: ignore[arg-type]
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return max(3.0, min(parsed, 120.0))
|
||||
|
||||
|
||||
def _config_home() -> Path:
|
||||
override = os.getenv("DOCTOR_CONFIG_DIR", "").strip()
|
||||
if override:
|
||||
return Path(override).expanduser()
|
||||
if user_config_dir is not None:
|
||||
return Path(user_config_dir(APP_NAME, APP_AUTHOR))
|
||||
return Path.home() / f".{APP_NAME.lower()}"
|
||||
|
||||
|
||||
def _log_home() -> Path:
|
||||
override = os.getenv("DOCTOR_LOG_DIR", "").strip()
|
||||
if override:
|
||||
return Path(override).expanduser()
|
||||
if user_log_dir is not None:
|
||||
return Path(user_log_dir(APP_NAME, APP_AUTHOR))
|
||||
return _config_home() / "logs"
|
||||
|
||||
|
||||
def normalize_api_base_url(value: str) -> str:
|
||||
"""Return a normalized HTTP(S) base URL ending in ``/adminapi``.
|
||||
|
||||
Empty values are accepted for demo mode. Credentials, fragments and query
|
||||
strings are rejected to prevent accidentally persisting tokens in settings.
|
||||
"""
|
||||
|
||||
raw = (value or "").strip().rstrip("/")
|
||||
if not raw:
|
||||
return ""
|
||||
parts = urlsplit(raw)
|
||||
if parts.scheme not in {"http", "https"} or not parts.netloc:
|
||||
raise ValueError("服务器地址必须是完整的 http:// 或 https:// 地址")
|
||||
if parts.username or parts.password or parts.query or parts.fragment:
|
||||
raise ValueError("服务器地址不能包含账号、密码、查询参数或片段")
|
||||
path = parts.path.rstrip("/")
|
||||
if not path.endswith("/adminapi"):
|
||||
path = f"{path}/adminapi" if path else "/adminapi"
|
||||
return urlunsplit((parts.scheme, parts.netloc, path, "", ""))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AppConfig:
|
||||
"""Runtime configuration loaded from environment and user preferences."""
|
||||
|
||||
api_base_url: str = ""
|
||||
demo_mode: bool = True
|
||||
video_mode: str = "embedded"
|
||||
video_web_url: str = ""
|
||||
verify_ssl: bool = True
|
||||
request_timeout: float = 30.0
|
||||
log_level: str = "INFO"
|
||||
remembered_account: str = ""
|
||||
|
||||
@property
|
||||
def config_dir(self) -> Path:
|
||||
return _config_home()
|
||||
|
||||
@property
|
||||
def log_dir(self) -> Path:
|
||||
return _log_home()
|
||||
|
||||
@property
|
||||
def preferences_file(self) -> Path:
|
||||
return self.config_dir / "preferences.json"
|
||||
|
||||
@classmethod
|
||||
def load(cls, env_file: Path | None = None) -> AppConfig:
|
||||
if load_dotenv is not None:
|
||||
load_dotenv(dotenv_path=env_file, override=False)
|
||||
|
||||
raw_url = os.getenv("DOCTOR_API_BASE_URL", "")
|
||||
try:
|
||||
api_url = normalize_api_base_url(raw_url)
|
||||
except ValueError:
|
||||
api_url = ""
|
||||
|
||||
config = cls(
|
||||
api_base_url=api_url,
|
||||
demo_mode=_as_bool(os.getenv("DOCTOR_DEMO_MODE"), True),
|
||||
video_mode=os.getenv("DOCTOR_VIDEO_MODE", "embedded").strip().lower(),
|
||||
video_web_url=os.getenv("DOCTOR_VIDEO_WEB_URL", "").strip(),
|
||||
verify_ssl=_as_bool(os.getenv("DOCTOR_VERIFY_SSL"), True),
|
||||
request_timeout=_safe_timeout(os.getenv("DOCTOR_REQUEST_TIMEOUT")),
|
||||
log_level=os.getenv("DOCTOR_LOG_LEVEL", "INFO").strip().upper(),
|
||||
)
|
||||
return config._merge_preferences()
|
||||
|
||||
def _merge_preferences(self) -> AppConfig:
|
||||
try:
|
||||
payload = json.loads(self.preferences_file.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError, TypeError):
|
||||
return self
|
||||
allowed = {item.name for item in fields(self)}
|
||||
clean: dict[str, Any] = {key: value for key, value in payload.items() if key in allowed}
|
||||
if "api_base_url" in clean:
|
||||
try:
|
||||
clean["api_base_url"] = normalize_api_base_url(str(clean["api_base_url"]))
|
||||
except ValueError:
|
||||
clean.pop("api_base_url", None)
|
||||
if "video_mode" in clean and clean["video_mode"] not in {"embedded", "browser"}:
|
||||
clean.pop("video_mode", None)
|
||||
if "request_timeout" in clean:
|
||||
clean["request_timeout"] = _safe_timeout(clean["request_timeout"])
|
||||
if "verify_ssl" in clean:
|
||||
clean["verify_ssl"] = _as_bool(clean["verify_ssl"], True)
|
||||
return replace(self, **clean)
|
||||
|
||||
def save_preferences(self) -> None:
|
||||
"""Persist non-secret preferences atomically with user-only intent."""
|
||||
|
||||
self.config_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = self.preferences_file
|
||||
temporary = target.with_suffix(".tmp")
|
||||
payload = asdict(self)
|
||||
temporary.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
with suppress(OSError):
|
||||
os.chmod(temporary, 0o600)
|
||||
temporary.replace(target)
|
||||
|
||||
def with_updates(self, **changes: Any) -> AppConfig:
|
||||
if "api_base_url" in changes:
|
||||
changes["api_base_url"] = normalize_api_base_url(str(changes["api_base_url"]))
|
||||
if "video_mode" in changes and changes["video_mode"] not in {"embedded", "browser"}:
|
||||
raise ValueError("视频模式只能是 embedded 或 browser")
|
||||
if "request_timeout" in changes:
|
||||
changes["request_timeout"] = _safe_timeout(changes["request_timeout"])
|
||||
if "verify_ssl" in changes:
|
||||
changes["verify_ssl"] = _as_bool(changes["verify_ssl"], True)
|
||||
return replace(self, **changes)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""UI-independent domain primitives for the doctor workstation."""
|
||||
|
||||
from .errors import (
|
||||
ApiBusinessError,
|
||||
ApiError,
|
||||
ApiHttpError,
|
||||
ApiProtocolError,
|
||||
ApiTimeoutError,
|
||||
ApiTransportError,
|
||||
AuthenticationError,
|
||||
AuthenticationExpiredError,
|
||||
InstallationRequiredError,
|
||||
NeedBindWorkWechatError,
|
||||
OpenNewPageError,
|
||||
OpenPageRequiredError,
|
||||
RepositoryNotFoundError,
|
||||
WorkWechatBindingRequiredError,
|
||||
)
|
||||
from .models import (
|
||||
Appointment,
|
||||
CallTicket,
|
||||
Consultation,
|
||||
PageResult,
|
||||
Patient,
|
||||
Prescription,
|
||||
PrescriptionTemplate,
|
||||
UserProfile,
|
||||
)
|
||||
from .permissions import PermissionSet
|
||||
from .session import Session
|
||||
|
||||
__all__ = [
|
||||
"ApiBusinessError",
|
||||
"ApiError",
|
||||
"ApiHttpError",
|
||||
"ApiProtocolError",
|
||||
"ApiTimeoutError",
|
||||
"ApiTransportError",
|
||||
"Appointment",
|
||||
"AuthenticationError",
|
||||
"AuthenticationExpiredError",
|
||||
"CallTicket",
|
||||
"Consultation",
|
||||
"InstallationRequiredError",
|
||||
"NeedBindWorkWechatError",
|
||||
"OpenNewPageError",
|
||||
"OpenPageRequiredError",
|
||||
"PageResult",
|
||||
"Patient",
|
||||
"PermissionSet",
|
||||
"Prescription",
|
||||
"PrescriptionTemplate",
|
||||
"RepositoryNotFoundError",
|
||||
"Session",
|
||||
"UserProfile",
|
||||
"WorkWechatBindingRequiredError",
|
||||
]
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Structured errors shared by HTTP and repository implementations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ApiError(RuntimeError):
|
||||
"""Base API error carrying machine-readable response context."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
code: int | None = None,
|
||||
data: Any = None,
|
||||
status_code: int | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> None:
|
||||
"""Initialise a structured API error."""
|
||||
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.code = code
|
||||
self.data = data
|
||||
self.status_code = status_code
|
||||
self.request_id = request_id
|
||||
|
||||
|
||||
class ApiTransportError(ApiError):
|
||||
"""A network failure occurred before a valid API response was received."""
|
||||
|
||||
|
||||
class ApiTimeoutError(ApiTransportError):
|
||||
"""A request exceeded its configured timeout and exhausted safe retries."""
|
||||
|
||||
|
||||
class ApiHttpError(ApiTransportError):
|
||||
"""The server returned a non-successful HTTP status code."""
|
||||
|
||||
|
||||
class ApiProtocolError(ApiError):
|
||||
"""The response was not valid JSON or did not contain a valid envelope."""
|
||||
|
||||
|
||||
class ApiBusinessError(ApiError):
|
||||
"""The API returned envelope code ``0`` for a rejected business action."""
|
||||
|
||||
|
||||
class AuthenticationExpiredError(ApiError):
|
||||
"""The API returned envelope code ``-1`` and the session must be cleared."""
|
||||
|
||||
|
||||
class WorkWechatBindingRequiredError(ApiError):
|
||||
"""The API returned code ``10`` and Enterprise WeChat binding is required."""
|
||||
|
||||
|
||||
class OpenPageRequiredError(ApiError):
|
||||
"""The API returned code ``2`` with an external page that needs user action."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
url: str = "",
|
||||
data: Any = None,
|
||||
status_code: int | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> None:
|
||||
"""Initialise the redirect signal without opening a browser implicitly."""
|
||||
|
||||
super().__init__(
|
||||
message,
|
||||
code=2,
|
||||
data=data,
|
||||
status_code=status_code,
|
||||
request_id=request_id,
|
||||
)
|
||||
self.url = url
|
||||
|
||||
|
||||
class InstallationRequiredError(ApiError):
|
||||
"""The legacy API returned code ``-2`` for a missing companion component."""
|
||||
|
||||
|
||||
class RepositoryNotFoundError(KeyError):
|
||||
"""A requested in-memory or remote domain object could not be found."""
|
||||
|
||||
|
||||
# Readable compatibility aliases for callers that use shorter exception names.
|
||||
AuthenticationError = AuthenticationExpiredError
|
||||
NeedBindWorkWechatError = WorkWechatBindingRequiredError
|
||||
OpenNewPageError = OpenPageRequiredError
|
||||
@@ -0,0 +1,913 @@
|
||||
"""Typed domain models used by the doctor workstation service layer.
|
||||
|
||||
The production API is not backed by a published schema and has accumulated a
|
||||
few field aliases over time. The ``from_dict`` factories in this module are
|
||||
therefore deliberately conservative: known fields are normalised while the
|
||||
complete source mapping is retained in ``raw`` for forward compatibility.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from math import ceil
|
||||
from typing import Any, Generic, TypeVar
|
||||
|
||||
JSONDict = dict[str, Any]
|
||||
T = TypeVar("T")
|
||||
U = TypeVar("U")
|
||||
|
||||
|
||||
def _mapping(value: object) -> Mapping[str, Any]:
|
||||
return value if isinstance(value, Mapping) else {}
|
||||
|
||||
|
||||
def _text(value: object, default: str = "") -> str:
|
||||
if value is None:
|
||||
return default
|
||||
return str(value)
|
||||
|
||||
|
||||
def _integer(value: object, default: int | None = 0) -> int | None:
|
||||
if value is None or value == "":
|
||||
return default
|
||||
if isinstance(value, bool):
|
||||
return int(value)
|
||||
try:
|
||||
return int(value) # type: ignore[arg-type]
|
||||
except (TypeError, ValueError):
|
||||
try:
|
||||
return int(float(str(value)))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _number(value: object) -> float | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return float(value) # type: ignore[arg-type]
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _boolean(value: object, default: bool = False) -> bool:
|
||||
if value is None or value == "":
|
||||
return default
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() not in {"0", "false", "no", "off", "null"}
|
||||
return bool(value)
|
||||
|
||||
|
||||
def _int_or_text(value: object, default: int | str = 0) -> int | str:
|
||||
if value is None or value == "":
|
||||
return default
|
||||
converted = _integer(value, None)
|
||||
return converted if converted is not None else str(value)
|
||||
|
||||
|
||||
def _dict_list(value: object) -> list[JSONDict]:
|
||||
if not isinstance(value, (list, tuple)):
|
||||
return []
|
||||
return [dict(item) for item in value if isinstance(item, Mapping)]
|
||||
|
||||
|
||||
def _string_list(value: object) -> list[str]:
|
||||
"""Return a clean list for APIs that alternate between CSV and arrays."""
|
||||
|
||||
values: object = value.split(",") if isinstance(value, str) else value
|
||||
if not isinstance(values, (list, tuple, set, frozenset)):
|
||||
return []
|
||||
return [text for item in values if (text := _text(item).strip())]
|
||||
|
||||
|
||||
def _string_tuple(value: object) -> tuple[str, ...]:
|
||||
if isinstance(value, str):
|
||||
values: object = value.split(",")
|
||||
else:
|
||||
values = value
|
||||
if not isinstance(values, (list, tuple, set, frozenset)):
|
||||
return ()
|
||||
return tuple(item for item in (_text(entry).strip() for entry in values) if item)
|
||||
|
||||
|
||||
def _role_tuple(value: object) -> tuple[int, ...]:
|
||||
if isinstance(value, str):
|
||||
values: object = value.split(",")
|
||||
elif isinstance(value, (int, float)):
|
||||
values = [value]
|
||||
else:
|
||||
values = value
|
||||
if not isinstance(values, (list, tuple, set, frozenset)):
|
||||
return ()
|
||||
result: list[int] = []
|
||||
for entry in values:
|
||||
candidate = entry.get("id") if isinstance(entry, Mapping) else entry
|
||||
role_id = _integer(candidate, None)
|
||||
if role_id is not None and role_id not in result:
|
||||
result.append(role_id)
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def _formula_type(value: object) -> int | str:
|
||||
"""Normalise known main/aux formula labels while preserving unknown values."""
|
||||
|
||||
text = _text(value).strip()
|
||||
lowered = text.lower()
|
||||
if lowered in {"", "1", "main", "primary", "主方"}:
|
||||
return "main"
|
||||
if lowered in {"2", "aux", "auxiliary", "secondary", "辅方"}:
|
||||
return "aux"
|
||||
converted = _integer(value, None)
|
||||
return converted if converted is not None else text
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class UserProfile:
|
||||
"""Authenticated doctor profile returned by ``auth.admin/mySelf``."""
|
||||
|
||||
id: int = 0
|
||||
account: str = ""
|
||||
name: str = ""
|
||||
avatar: str = ""
|
||||
phone: str = ""
|
||||
role_ids: tuple[int, ...] = ()
|
||||
root: bool = False
|
||||
department_id: int | None = None
|
||||
department_name: str = ""
|
||||
permissions: tuple[str, ...] = ()
|
||||
raw: JSONDict = field(default_factory=dict, repr=False, compare=False)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping[str, Any] | None) -> UserProfile:
|
||||
"""Build a profile from either a user object or a ``mySelf`` result."""
|
||||
|
||||
outer = _mapping(data)
|
||||
nested_user = outer.get("user")
|
||||
source = _mapping(nested_user) if isinstance(nested_user, Mapping) else outer
|
||||
roles = source.get("role_ids", source.get("role_id", source.get("roles")))
|
||||
permissions = outer.get("permissions", source.get("permissions", ()))
|
||||
department = _mapping(source.get("department", source.get("dept")))
|
||||
return cls(
|
||||
id=_integer(source.get("id", source.get("user_id")), 0) or 0,
|
||||
account=_text(source.get("account", source.get("username"))),
|
||||
name=_text(
|
||||
source.get(
|
||||
"name",
|
||||
source.get("real_name", source.get("nickname", source.get("account"))),
|
||||
)
|
||||
),
|
||||
avatar=_text(source.get("avatar")),
|
||||
phone=_text(source.get("phone", source.get("mobile"))),
|
||||
role_ids=_role_tuple(roles),
|
||||
root=_boolean(source.get("root", source.get("is_root"))),
|
||||
department_id=_integer(
|
||||
source.get("department_id", source.get("dept_id", department.get("id"))),
|
||||
None,
|
||||
),
|
||||
department_name=_text(
|
||||
source.get(
|
||||
"department_name",
|
||||
source.get("dept_name", department.get("name")),
|
||||
)
|
||||
),
|
||||
permissions=_string_tuple(permissions),
|
||||
raw=dict(source),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Appointment:
|
||||
"""A doctor appointment and the patient summary shown in queue views."""
|
||||
|
||||
id: int = 0
|
||||
patient_id: int = 0
|
||||
diagnosis_id: int | None = None
|
||||
patient_name: str = ""
|
||||
patient_phone: str = ""
|
||||
gender: int | str | None = None
|
||||
gender_desc: str = ""
|
||||
age: int | None = None
|
||||
height: float | None = None
|
||||
weight: float | None = None
|
||||
doctor_id: int | None = None
|
||||
doctor_name: str = ""
|
||||
assistant_id: int | None = None
|
||||
assistant_name: str = ""
|
||||
appointment_date: str = ""
|
||||
appointment_time: str = ""
|
||||
period: str = ""
|
||||
appointment_type: int | str | None = None
|
||||
appointment_type_text: str = ""
|
||||
channel: int | str | None = None
|
||||
channel_text: str = ""
|
||||
status: int | str = 0
|
||||
status_desc: str = ""
|
||||
diagnosis_confirmed: bool = False
|
||||
has_prescription: bool = False
|
||||
prescription_audit_status: int | None = None
|
||||
prescription_void_status: int | None = None
|
||||
remark: str = ""
|
||||
raw: JSONDict = field(default_factory=dict, repr=False, compare=False)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping[str, Any] | None) -> Appointment:
|
||||
"""Build an appointment while accepting historical API aliases."""
|
||||
|
||||
source = _mapping(data)
|
||||
return cls(
|
||||
id=_integer(source.get("id", source.get("appointment_id")), 0) or 0,
|
||||
patient_id=_integer(source.get("patient_id", source.get("source_patient_id")), 0) or 0,
|
||||
diagnosis_id=_integer(source.get("diagnosis_id"), None),
|
||||
patient_name=_text(source.get("patient_name", source.get("name"))),
|
||||
patient_phone=_text(
|
||||
source.get("patient_phone", source.get("phone", source.get("phone_masked")))
|
||||
),
|
||||
gender=source.get("gender", source.get("gender_desc")),
|
||||
gender_desc=_text(source.get("gender_desc")),
|
||||
age=_integer(source.get("age"), None),
|
||||
height=_number(source.get("height")),
|
||||
weight=_number(source.get("weight")),
|
||||
doctor_id=_integer(source.get("doctor_id"), None),
|
||||
doctor_name=_text(source.get("doctor_name")),
|
||||
assistant_id=_integer(source.get("assistant_id"), None),
|
||||
assistant_name=_text(source.get("assistant_name")),
|
||||
appointment_date=_text(source.get("appointment_date", source.get("date"))),
|
||||
appointment_time=_text(
|
||||
source.get(
|
||||
"appointment_time",
|
||||
source.get("appointment_time_text", source.get("time")),
|
||||
)
|
||||
),
|
||||
period=_text(source.get("period")),
|
||||
appointment_type=source.get("appointment_type", source.get("type")),
|
||||
appointment_type_text=_text(
|
||||
source.get("appointment_type_text", source.get("type_text"))
|
||||
),
|
||||
channel=source.get("channel", source.get("appointment_channel")),
|
||||
channel_text=_text(source.get("channel_text", source.get("channel_name"))),
|
||||
status=_int_or_text(source.get("status"), 0),
|
||||
status_desc=_text(source.get("status_desc", source.get("appointment_status_text"))),
|
||||
diagnosis_confirmed=_boolean(source.get("diagnosis_confirmed")),
|
||||
has_prescription=_boolean(source.get("has_prescription")),
|
||||
prescription_audit_status=_integer(source.get("prescription_audit_status"), None),
|
||||
prescription_void_status=_integer(source.get("prescription_void_status"), None),
|
||||
remark=_text(source.get("remark")),
|
||||
raw=dict(source),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Patient:
|
||||
"""A patient row from the doctor's scoped first-visit patient list."""
|
||||
|
||||
id: int = 0
|
||||
diagnosis_id: int | None = None
|
||||
source_patient_id: int | None = None
|
||||
name: str = ""
|
||||
gender: int | str | None = None
|
||||
gender_desc: str = ""
|
||||
age: int | None = None
|
||||
phone: str = ""
|
||||
phone_masked: str = ""
|
||||
has_id_card: bool = False
|
||||
assistant_id: int | None = None
|
||||
assistant_name: str = ""
|
||||
appointment_id: int | None = None
|
||||
appointment_doctor_id: int | None = None
|
||||
appointment_doctor_name: str = ""
|
||||
appointment_status: int | str | None = None
|
||||
appointment_status_text: str = ""
|
||||
appointment_time_text: str = ""
|
||||
appointment_date: str = ""
|
||||
appointment_time: str = ""
|
||||
appointments: list[JSONDict] = field(default_factory=list)
|
||||
revisit_count: int = 0
|
||||
confirmed: bool = False
|
||||
confirmation_text: str = ""
|
||||
diagnosis_date_text: str = ""
|
||||
status_filter: str = ""
|
||||
id_card: str = ""
|
||||
region: str = ""
|
||||
is_self_patient: bool = False
|
||||
raw: JSONDict = field(default_factory=dict, repr=False, compare=False)
|
||||
|
||||
@property
|
||||
def patient_name(self) -> str:
|
||||
"""Return the backend-style alias for ``name``."""
|
||||
|
||||
return self.name
|
||||
|
||||
@property
|
||||
def patient_phone(self) -> str:
|
||||
"""Return the best available phone value under the queue-style alias."""
|
||||
|
||||
return self.phone_masked or self.phone
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping[str, Any] | None) -> Patient:
|
||||
"""Build a patient from a tolerant first-visit list row."""
|
||||
|
||||
source = _mapping(data)
|
||||
diagnosis_id = _integer(source.get("diagnosis_id", source.get("id")), None)
|
||||
item_id = _integer(source.get("id", diagnosis_id), 0) or 0
|
||||
return cls(
|
||||
id=item_id,
|
||||
diagnosis_id=diagnosis_id,
|
||||
source_patient_id=_integer(source.get("source_patient_id"), None),
|
||||
name=_text(source.get("patient_name", source.get("name"))),
|
||||
gender=source.get("gender", source.get("gender_desc")),
|
||||
gender_desc=_text(source.get("gender_desc")),
|
||||
age=_integer(source.get("age"), None),
|
||||
phone=_text(source.get("phone", source.get("patient_phone"))),
|
||||
phone_masked=_text(source.get("phone_masked", source.get("phone"))),
|
||||
has_id_card=_boolean(source.get("has_id_card")),
|
||||
assistant_id=_integer(source.get("assistant_id"), None),
|
||||
assistant_name=_text(source.get("assistant_name")),
|
||||
appointment_id=_integer(source.get("appointment_id"), None),
|
||||
appointment_doctor_id=_integer(source.get("appointment_doctor_id"), None),
|
||||
appointment_doctor_name=_text(source.get("appointment_doctor_name")),
|
||||
appointment_status=(
|
||||
_int_or_text(source.get("appointment_status"))
|
||||
if source.get("appointment_status") not in (None, "")
|
||||
else None
|
||||
),
|
||||
appointment_status_text=_text(source.get("appointment_status_text")),
|
||||
appointment_time_text=_text(source.get("appointment_time_text")),
|
||||
appointment_date=_text(source.get("appointment_date")),
|
||||
appointment_time=_text(source.get("appointment_time")),
|
||||
appointments=_dict_list(source.get("appointments")),
|
||||
revisit_count=_integer(source.get("revisit_count"), 0) or 0,
|
||||
confirmed=_boolean(source.get("confirmed", source.get("diagnosis_confirmed"))),
|
||||
confirmation_text=_text(source.get("confirmation_text")),
|
||||
diagnosis_date_text=_text(source.get("diagnosis_date_text")),
|
||||
status_filter=_text(source.get("status_filter", source.get("visit_status"))),
|
||||
id_card=_text(source.get("id_card")),
|
||||
region=_text(source.get("region", source.get("region_text"))),
|
||||
is_self_patient=_boolean(source.get("is_self_patient")),
|
||||
raw=dict(source),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Consultation:
|
||||
"""A diagnosis/consultation row used by the consultation workspace."""
|
||||
|
||||
id: int = 0
|
||||
patient_id: int | None = None
|
||||
appointment_id: int | None = None
|
||||
patient_name: str = ""
|
||||
patient_phone: str = ""
|
||||
phone_masked: str = ""
|
||||
id_card: str = ""
|
||||
gender: int | str | None = None
|
||||
gender_desc: str = ""
|
||||
age: int | None = None
|
||||
doctor_id: int | None = None
|
||||
doctor_name: str = ""
|
||||
assistant_id: int | None = None
|
||||
assistant_name: str = ""
|
||||
diagnosis_date: str = ""
|
||||
appointment_date: str = ""
|
||||
appointment_time: str = ""
|
||||
period: str = ""
|
||||
has_appointment: bool = False
|
||||
appointment_status: int | str | None = None
|
||||
appointment_status_text: str = ""
|
||||
appointments: list[JSONDict] = field(default_factory=list)
|
||||
consultation_type: int | str | None = None
|
||||
clinical_diagnosis: str = ""
|
||||
chief_complaint: str = ""
|
||||
present_illness: str = ""
|
||||
past_history: str = ""
|
||||
allergy_history: str = ""
|
||||
personal_history: str = ""
|
||||
family_history: str = ""
|
||||
current_medicine: str = ""
|
||||
local_diagnosis: str = ""
|
||||
prescription_opinion: str = ""
|
||||
tongue: str = ""
|
||||
pulse: str = ""
|
||||
status: int | str = 0
|
||||
status_desc: str = ""
|
||||
confirmed: bool = False
|
||||
diagnosis_view_records: list[JSONDict] = field(default_factory=list)
|
||||
has_prescription: bool = False
|
||||
unserved_days: int | None = None
|
||||
video_hint: str = ""
|
||||
source: int | str | None = None
|
||||
source_text: str = ""
|
||||
remark: str = ""
|
||||
raw: JSONDict = field(default_factory=dict, repr=False, compare=False)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping[str, Any] | None) -> Consultation:
|
||||
"""Build a consultation from a diagnosis row or reception detail."""
|
||||
|
||||
source = _mapping(data)
|
||||
nested = _mapping(source.get("diagnosis"))
|
||||
if nested:
|
||||
merged: JSONDict = dict(source)
|
||||
merged.update(nested)
|
||||
source = merged
|
||||
appointments = _dict_list(source.get("appointments"))
|
||||
appointment = _mapping(source.get("appointment", source.get("latest_appointment")))
|
||||
if not appointment:
|
||||
appointment = appointments[0] if appointments else {}
|
||||
view_records = _dict_list(
|
||||
source.get("DiagnosisViewRecord", source.get("diagnosis_view_records"))
|
||||
)
|
||||
confirmed_value: object = source.get("confirmed", source.get("diagnosis_confirmed"))
|
||||
if confirmed_value in (None, "") and view_records:
|
||||
confirmed_value = any(_boolean(item.get("is_confirmed")) for item in view_records)
|
||||
explicit_has_appointment = source.get("has_appointment")
|
||||
has_appointment = (
|
||||
_boolean(explicit_has_appointment)
|
||||
if explicit_has_appointment not in (None, "")
|
||||
else bool(appointment or appointments or source.get("appointment_id"))
|
||||
)
|
||||
appointment_status_value = source.get("appointment_status")
|
||||
if appointment_status_value in (None, ""):
|
||||
appointment_status_value = appointment.get("status")
|
||||
return cls(
|
||||
id=_integer(source.get("id", source.get("diagnosis_id")), 0) or 0,
|
||||
patient_id=_integer(source.get("patient_id", source.get("source_patient_id")), None),
|
||||
appointment_id=_integer(source.get("appointment_id", appointment.get("id")), None),
|
||||
patient_name=_text(source.get("patient_name", source.get("name"))),
|
||||
patient_phone=_text(source.get("patient_phone", source.get("phone"))),
|
||||
phone_masked=_text(source.get("phone_masked")),
|
||||
id_card=_text(source.get("id_card")),
|
||||
gender=source.get("gender", source.get("gender_desc")),
|
||||
gender_desc=_text(source.get("gender_desc")),
|
||||
age=_integer(source.get("age"), None),
|
||||
doctor_id=_integer(source.get("doctor_id", appointment.get("doctor_id")), None),
|
||||
doctor_name=_text(source.get("doctor_name", appointment.get("doctor_name"))),
|
||||
assistant_id=_integer(source.get("assistant_id"), None),
|
||||
assistant_name=_text(source.get("assistant_name")),
|
||||
diagnosis_date=_text(source.get("diagnosis_date", source.get("diagnosis_date_text"))),
|
||||
appointment_date=_text(
|
||||
source.get(
|
||||
"appointment_date",
|
||||
source.get(
|
||||
"latest_appointment_date",
|
||||
appointment.get("appointment_date", appointment.get("date")),
|
||||
),
|
||||
)
|
||||
),
|
||||
appointment_time=_text(
|
||||
source.get(
|
||||
"appointment_time",
|
||||
source.get(
|
||||
"appointment_time_text",
|
||||
source.get(
|
||||
"latest_appointment_time",
|
||||
appointment.get("appointment_time", appointment.get("time_text")),
|
||||
),
|
||||
),
|
||||
)
|
||||
),
|
||||
period=_text(source.get("period", appointment.get("period"))),
|
||||
has_appointment=has_appointment,
|
||||
appointment_status=(
|
||||
_int_or_text(appointment_status_value)
|
||||
if appointment_status_value not in (None, "")
|
||||
else None
|
||||
),
|
||||
appointment_status_text=_text(
|
||||
source.get(
|
||||
"appointment_status_text",
|
||||
appointment.get("status_text", appointment.get("status_desc")),
|
||||
)
|
||||
),
|
||||
appointments=appointments,
|
||||
consultation_type=source.get("consultation_type", source.get("visit_type")),
|
||||
clinical_diagnosis=_text(source.get("clinical_diagnosis")),
|
||||
chief_complaint=_text(source.get("chief_complaint", source.get("complaint"))),
|
||||
present_illness=_text(
|
||||
source.get("present_illness", source.get("present_illness_history"))
|
||||
),
|
||||
past_history=_text(source.get("past_history")),
|
||||
allergy_history=_text(source.get("allergy_history")),
|
||||
personal_history=_text(source.get("personal_history")),
|
||||
family_history=_text(source.get("family_history")),
|
||||
current_medicine=_text(source.get("current_medicine")),
|
||||
local_diagnosis=_text(source.get("local_diagnosis")),
|
||||
prescription_opinion=_text(source.get("prescription_opinion")),
|
||||
tongue=_text(source.get("tongue")),
|
||||
pulse=_text(source.get("pulse", source.get("pulse_condition"))),
|
||||
# Diagnosis enablement and appointment workflow are separate domains.
|
||||
status=_int_or_text(source.get("status"), 0),
|
||||
status_desc=_text(source.get("status_desc")),
|
||||
confirmed=_boolean(confirmed_value),
|
||||
diagnosis_view_records=view_records,
|
||||
has_prescription=_boolean(source.get("has_prescription")),
|
||||
unserved_days=_integer(
|
||||
source.get("unserved_days", source.get("unserved_day_count")), None
|
||||
),
|
||||
video_hint=_text(source.get("video_hint", source.get("call_hint"))),
|
||||
source=source.get("source", source.get("diagnosis_source")),
|
||||
source_text=_text(source.get("source_text", source.get("source_name"))),
|
||||
remark=_text(source.get("remark")),
|
||||
raw=dict(source),
|
||||
)
|
||||
|
||||
@property
|
||||
def diagnosis_confirmed(self) -> bool:
|
||||
"""Return the appointment-list alias for the confirmation flag."""
|
||||
|
||||
return self.confirmed
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class PrescriptionTemplate:
|
||||
"""A reusable prescription-library formula owned by a doctor."""
|
||||
|
||||
id: int = 0
|
||||
name: str = ""
|
||||
formula_type: int | str = 1
|
||||
herbs: list[JSONDict] = field(default_factory=list)
|
||||
is_public: bool = False
|
||||
disable_edit: bool = False
|
||||
creator_id: int | None = None
|
||||
creator_name: str = ""
|
||||
create_time: str = ""
|
||||
update_time: str = ""
|
||||
raw: JSONDict = field(default_factory=dict, repr=False, compare=False)
|
||||
|
||||
@property
|
||||
def prescription_name(self) -> str:
|
||||
"""Return the API field alias for the template name."""
|
||||
|
||||
return self.name
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping[str, Any] | None) -> PrescriptionTemplate:
|
||||
"""Build a prescription template from a list or detail response."""
|
||||
|
||||
source = _mapping(data)
|
||||
return cls(
|
||||
id=_integer(source.get("id"), 0) or 0,
|
||||
name=_text(source.get("prescription_name", source.get("name"))),
|
||||
formula_type=_formula_type(source.get("formula_type")),
|
||||
herbs=_dict_list(source.get("herbs")),
|
||||
is_public=_boolean(source.get("is_public")),
|
||||
disable_edit=_boolean(source.get("disable_edit")),
|
||||
creator_id=_integer(source.get("creator_id"), None),
|
||||
creator_name=_text(source.get("creator_name")),
|
||||
create_time=_text(source.get("create_time")),
|
||||
update_time=_text(source.get("update_time")),
|
||||
raw=dict(source),
|
||||
)
|
||||
|
||||
def to_api_dict(self, *, include_id: bool = True) -> JSONDict:
|
||||
"""Serialise this template using the server's field names."""
|
||||
|
||||
payload: JSONDict = {
|
||||
"prescription_name": self.name,
|
||||
"formula_type": "辅方" if _formula_type(self.formula_type) == "aux" else "主方",
|
||||
"herbs": [dict(item) for item in self.herbs],
|
||||
"is_public": int(self.is_public),
|
||||
"disable_edit": int(self.disable_edit),
|
||||
}
|
||||
if include_id and self.id:
|
||||
payload["id"] = self.id
|
||||
return payload
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Prescription:
|
||||
"""An issued prescription, including audit state and dosage information."""
|
||||
|
||||
id: int = 0
|
||||
diagnosis_id: int | None = None
|
||||
appointment_id: int | None = None
|
||||
case_record: JSONDict = field(default_factory=dict)
|
||||
sn: str = ""
|
||||
patient_name: str = ""
|
||||
phone: str = ""
|
||||
phone_masked: str = ""
|
||||
gender: int | str | None = None
|
||||
age: int | None = None
|
||||
visit_no: str = ""
|
||||
prescription_date: str = ""
|
||||
prescription_type: int | str | None = None
|
||||
herbs: list[JSONDict] = field(default_factory=list)
|
||||
clinical_diagnosis: str = ""
|
||||
tongue: str = ""
|
||||
tongue_image: str = ""
|
||||
pulse: str = ""
|
||||
pulse_condition: str = ""
|
||||
dosage_amount: float | None = None
|
||||
dosage_unit: str = ""
|
||||
dosage_bag_count: int | None = None
|
||||
need_decoction: bool = False
|
||||
bags_per_dose: int | None = None
|
||||
dose_count: int | None = None
|
||||
dose_unit: str = ""
|
||||
usage_days: int | None = None
|
||||
times_per_day: int | None = None
|
||||
usage_instruction: str = ""
|
||||
usage_time: str = ""
|
||||
usage_way: str = ""
|
||||
dietary_taboo: list[str] = field(default_factory=list)
|
||||
usage_notes: str = ""
|
||||
aux_usage: JSONDict = field(default_factory=dict)
|
||||
doctor_name: str = ""
|
||||
doctor_signature: str = ""
|
||||
creator_id: int | None = None
|
||||
assistant_name: str = ""
|
||||
is_system_auto: bool = False
|
||||
is_shared: bool = False
|
||||
visible_role_ids: tuple[int, ...] = ()
|
||||
audit_status: int | None = None
|
||||
audit_time: str = ""
|
||||
audit_by_name: str = ""
|
||||
audit_remark: str = ""
|
||||
business_prescription_audit_status: int | None = None
|
||||
business_prescription_audit_rejected: bool = False
|
||||
business_prescription_audit_remark: str = ""
|
||||
void_status: int | None = None
|
||||
void_by_name: str = ""
|
||||
void_time: str = ""
|
||||
has_prescription_order: bool = False
|
||||
prescription_order_id: int | None = None
|
||||
order_no: str = ""
|
||||
recipient_name: str = ""
|
||||
recipient_phone: str = ""
|
||||
shipping_province: str = ""
|
||||
shipping_city: str = ""
|
||||
shipping_district: str = ""
|
||||
shipping_address: str = ""
|
||||
pharmacy_remark: str = ""
|
||||
remark_assistant: str = ""
|
||||
medication_days: int | None = None
|
||||
pill_requirement: str = ""
|
||||
create_time: str = ""
|
||||
raw: JSONDict = field(default_factory=dict, repr=False, compare=False)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping[str, Any] | None) -> Prescription:
|
||||
"""Build a prescription from a compact list row or a full detail object."""
|
||||
|
||||
source = _mapping(data)
|
||||
return cls(
|
||||
id=_integer(source.get("id"), 0) or 0,
|
||||
diagnosis_id=_integer(source.get("diagnosis_id"), None),
|
||||
appointment_id=_integer(source.get("appointment_id"), None),
|
||||
case_record=dict(_mapping(source.get("case_record"))),
|
||||
sn=_text(source.get("sn")),
|
||||
patient_name=_text(source.get("patient_name")),
|
||||
phone=_text(source.get("phone", source.get("patient_phone"))),
|
||||
phone_masked=_text(source.get("phone_masked")),
|
||||
gender=source.get("gender", source.get("gender_desc")),
|
||||
age=_integer(source.get("age"), None),
|
||||
visit_no=_text(source.get("visit_no")),
|
||||
prescription_date=_text(source.get("prescription_date")),
|
||||
prescription_type=source.get("prescription_type"),
|
||||
herbs=_dict_list(source.get("herbs")),
|
||||
clinical_diagnosis=_text(source.get("clinical_diagnosis")),
|
||||
tongue=_text(source.get("tongue")),
|
||||
tongue_image=_text(source.get("tongue_image")),
|
||||
pulse=_text(source.get("pulse")),
|
||||
pulse_condition=_text(source.get("pulse_condition")),
|
||||
dosage_amount=_number(source.get("dosage_amount")),
|
||||
dosage_unit=_text(source.get("dosage_unit")),
|
||||
dosage_bag_count=_integer(source.get("dosage_bag_count"), None),
|
||||
need_decoction=_boolean(source.get("need_decoction")),
|
||||
bags_per_dose=_integer(source.get("bags_per_dose"), None),
|
||||
dose_count=_integer(source.get("dose_count"), None),
|
||||
dose_unit=_text(source.get("dose_unit")),
|
||||
usage_days=_integer(source.get("usage_days"), None),
|
||||
times_per_day=_integer(source.get("times_per_day"), None),
|
||||
usage_instruction=_text(source.get("usage_instruction")),
|
||||
usage_time=_text(source.get("usage_time")),
|
||||
usage_way=_text(source.get("usage_way")),
|
||||
dietary_taboo=_string_list(source.get("dietary_taboo")),
|
||||
usage_notes=_text(source.get("usage_notes")),
|
||||
aux_usage=dict(_mapping(source.get("aux_usage"))),
|
||||
doctor_name=_text(source.get("doctor_name")),
|
||||
doctor_signature=_text(source.get("doctor_signature")),
|
||||
creator_id=_integer(source.get("creator_id"), None),
|
||||
assistant_name=_text(source.get("assistant_name")),
|
||||
is_system_auto=_boolean(source.get("is_system_auto")),
|
||||
is_shared=_boolean(source.get("is_shared")),
|
||||
visible_role_ids=_role_tuple(source.get("visible_role_ids")),
|
||||
audit_status=_integer(source.get("audit_status"), None),
|
||||
audit_time=_text(source.get("audit_time")),
|
||||
audit_by_name=_text(source.get("audit_by_name")),
|
||||
audit_remark=_text(source.get("audit_remark")),
|
||||
business_prescription_audit_status=_integer(
|
||||
source.get("business_prescription_audit_status"), None
|
||||
),
|
||||
business_prescription_audit_rejected=_boolean(
|
||||
source.get("business_prescription_audit_rejected")
|
||||
),
|
||||
business_prescription_audit_remark=_text(
|
||||
source.get("business_prescription_audit_remark")
|
||||
),
|
||||
void_status=_integer(source.get("void_status"), None),
|
||||
void_by_name=_text(source.get("void_by_name")),
|
||||
void_time=_text(source.get("void_time")),
|
||||
has_prescription_order=_boolean(source.get("has_prescription_order")),
|
||||
prescription_order_id=_integer(source.get("prescription_order_id"), None),
|
||||
order_no=_text(source.get("order_no")),
|
||||
recipient_name=_text(source.get("recipient_name")),
|
||||
recipient_phone=_text(source.get("recipient_phone")),
|
||||
shipping_province=_text(source.get("shipping_province")),
|
||||
shipping_city=_text(source.get("shipping_city")),
|
||||
shipping_district=_text(source.get("shipping_district")),
|
||||
shipping_address=_text(source.get("shipping_address")),
|
||||
pharmacy_remark=_text(source.get("pharmacy_remark", source.get("pharmacy_note"))),
|
||||
remark_assistant=_text(source.get("remark_assistant")),
|
||||
medication_days=_integer(source.get("medication_days"), None),
|
||||
pill_requirement=_text(source.get("pill_requirement", source.get("make_pill_remark"))),
|
||||
create_time=_text(source.get("create_time")),
|
||||
raw=dict(source),
|
||||
)
|
||||
|
||||
def to_api_dict(self, *, include_id: bool = True) -> JSONDict:
|
||||
"""Serialise the complete editable prescription DTO for add/edit."""
|
||||
|
||||
payload: JSONDict = {
|
||||
"diagnosis_id": self.diagnosis_id,
|
||||
"appointment_id": self.appointment_id,
|
||||
"case_record": dict(self.case_record),
|
||||
"creator_id": self.creator_id,
|
||||
"is_system_auto": int(self.is_system_auto),
|
||||
"patient_name": self.patient_name,
|
||||
"phone": self.phone,
|
||||
"gender": self.gender,
|
||||
"age": self.age,
|
||||
"visit_no": self.visit_no,
|
||||
"prescription_date": self.prescription_date,
|
||||
"prescription_type": self.prescription_type,
|
||||
"tongue": self.tongue,
|
||||
"tongue_image": self.tongue_image,
|
||||
"pulse": self.pulse,
|
||||
"pulse_condition": self.pulse_condition,
|
||||
"clinical_diagnosis": self.clinical_diagnosis,
|
||||
"herbs": [dict(item) for item in self.herbs],
|
||||
"dosage_amount": self.dosage_amount,
|
||||
"dosage_unit": self.dosage_unit,
|
||||
"dosage_bag_count": self.dosage_bag_count,
|
||||
"need_decoction": int(self.need_decoction),
|
||||
"bags_per_dose": self.bags_per_dose,
|
||||
"dose_count": self.dose_count,
|
||||
"dose_unit": self.dose_unit,
|
||||
"usage_days": self.usage_days,
|
||||
"times_per_day": self.times_per_day,
|
||||
"usage_instruction": self.usage_instruction,
|
||||
"usage_time": self.usage_time,
|
||||
"usage_way": self.usage_way,
|
||||
"dietary_taboo": list(self.dietary_taboo),
|
||||
"usage_notes": self.usage_notes,
|
||||
"aux_usage": dict(self.aux_usage),
|
||||
"doctor_name": self.doctor_name,
|
||||
"doctor_signature": self.doctor_signature,
|
||||
"is_shared": int(self.is_shared),
|
||||
"visible_role_ids": list(self.visible_role_ids),
|
||||
"audit_status": self.audit_status,
|
||||
}
|
||||
if include_id and self.id:
|
||||
payload["id"] = self.id
|
||||
return {key: value for key, value in payload.items() if value is not None}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class PageResult(Generic[T]):
|
||||
"""A normalised paginated result with the API's optional extension data."""
|
||||
|
||||
items: list[T] = field(default_factory=list)
|
||||
total: int = 0
|
||||
page_no: int = 1
|
||||
page_size: int = 20
|
||||
extend: JSONDict = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def lists(self) -> list[T]:
|
||||
"""Return ``items`` under the legacy API name used by the web client."""
|
||||
|
||||
return self.items
|
||||
|
||||
@property
|
||||
def count(self) -> int:
|
||||
"""Return ``total`` under the legacy API name used by the web client."""
|
||||
|
||||
return self.total
|
||||
|
||||
@property
|
||||
def pages(self) -> int:
|
||||
"""Return the number of pages, or zero when the result is empty."""
|
||||
|
||||
return ceil(self.total / self.page_size) if self.total and self.page_size else 0
|
||||
|
||||
@classmethod
|
||||
def from_payload(
|
||||
cls,
|
||||
payload: object,
|
||||
parser: Callable[[Mapping[str, Any]], T],
|
||||
*,
|
||||
page_no: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> PageResult[T]:
|
||||
"""Normalise common list/count aliases and parse only mapping rows."""
|
||||
|
||||
top_source = _mapping(payload)
|
||||
if isinstance(payload, (list, tuple)):
|
||||
rows: object = payload
|
||||
source: Mapping[str, Any] = {}
|
||||
else:
|
||||
source = _mapping(payload)
|
||||
rows = []
|
||||
nested = source.get("data")
|
||||
if not any(key in source for key in ("lists", "items", "rows", "records")):
|
||||
if isinstance(nested, Mapping):
|
||||
source = nested
|
||||
elif isinstance(nested, (list, tuple)):
|
||||
rows = nested
|
||||
source = {}
|
||||
else:
|
||||
rows = []
|
||||
if not rows:
|
||||
rows = next(
|
||||
(
|
||||
source[key]
|
||||
for key in ("lists", "items", "rows", "records", "data")
|
||||
if isinstance(source.get(key), (list, tuple))
|
||||
),
|
||||
[],
|
||||
)
|
||||
parsed = [parser(row) for row in rows if isinstance(row, Mapping)]
|
||||
total = _integer(
|
||||
source.get("count", source.get("total", source.get("total_count"))),
|
||||
len(parsed),
|
||||
)
|
||||
result_page = _integer(
|
||||
source.get("page_no", source.get("page", source.get("current_page"))),
|
||||
page_no,
|
||||
)
|
||||
result_size = _integer(
|
||||
source.get("page_size", source.get("per_page", source.get("limit"))),
|
||||
page_size,
|
||||
)
|
||||
extend: JSONDict = {}
|
||||
for candidate in (
|
||||
top_source.get("extend", top_source.get("meta")),
|
||||
source.get("extend", source.get("meta")),
|
||||
):
|
||||
if isinstance(candidate, Mapping):
|
||||
extend.update(candidate)
|
||||
return cls(
|
||||
items=parsed,
|
||||
total=max(total or 0, 0),
|
||||
page_no=max(result_page or page_no, 1),
|
||||
page_size=max(result_size or page_size, 1),
|
||||
extend=extend,
|
||||
)
|
||||
|
||||
def map(self, transform: Callable[[T], U]) -> PageResult[U]:
|
||||
"""Return a page with transformed items and unchanged pagination data."""
|
||||
|
||||
return PageResult(
|
||||
items=[transform(item) for item in self.items],
|
||||
total=self.total,
|
||||
page_no=self.page_no,
|
||||
page_size=self.page_size,
|
||||
extend=dict(self.extend),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CallTicket:
|
||||
"""Short-lived Tencent IM/TRTC credentials for one consultation flow."""
|
||||
|
||||
sdk_app_id: int = 0
|
||||
user_id: str = ""
|
||||
user_sig: str = ""
|
||||
patient_user_id: str = ""
|
||||
assistant_id: str = ""
|
||||
diagnosis_id: int | None = None
|
||||
room_id: str = ""
|
||||
call_record_id: int | None = None
|
||||
is_lochost_vod: bool = False
|
||||
expires_at: int | None = None
|
||||
raw: JSONDict = field(default_factory=dict, repr=False, compare=False)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping[str, Any] | None) -> CallTicket:
|
||||
"""Build a call ticket from the backend's camelCase or snake_case form."""
|
||||
|
||||
source = _mapping(data)
|
||||
return cls(
|
||||
sdk_app_id=_integer(source.get("sdkAppId", source.get("sdk_app_id")), 0) or 0,
|
||||
user_id=_text(source.get("userId", source.get("user_id"))),
|
||||
user_sig=_text(source.get("userSig", source.get("user_sig"))),
|
||||
patient_user_id=_text(source.get("patientUserId", source.get("patient_user_id"))),
|
||||
assistant_id=_text(source.get("assistant_id", source.get("assistantId"))),
|
||||
diagnosis_id=_integer(source.get("diagnosis_id"), None),
|
||||
room_id=_text(source.get("room_id", source.get("roomId"))),
|
||||
call_record_id=_integer(source.get("call_record_id", source.get("callRecordId")), None),
|
||||
is_lochost_vod=_boolean(source.get("isLochostVod", source.get("is_lochost_vod"))),
|
||||
expires_at=_integer(source.get("expires_at", source.get("expireTime")), None),
|
||||
raw=dict(source),
|
||||
)
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Immutable permission helpers matching the admin client's semantics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Iterator
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
def _normalise(values: Iterable[str] | str | None) -> frozenset[str]:
|
||||
if values is None:
|
||||
return frozenset()
|
||||
candidates = (values,) if isinstance(values, str) else values
|
||||
return frozenset(value.strip() for value in candidates if value and value.strip())
|
||||
|
||||
|
||||
def _requirements(values: tuple[object, ...]) -> tuple[str, ...]:
|
||||
if len(values) == 1 and not isinstance(values[0], str):
|
||||
candidate = values[0]
|
||||
if isinstance(candidate, Iterable):
|
||||
values = tuple(candidate)
|
||||
return tuple(str(value).strip() for value in values if value is not None and str(value).strip())
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, init=False)
|
||||
class PermissionSet:
|
||||
"""A permission collection supporting wildcard, AND and OR checks.
|
||||
|
||||
``permissions`` accepts the flat permission list returned by ``mySelf``.
|
||||
``pages`` and ``actions`` are optional categories for callers that keep UI
|
||||
navigation and action capabilities separate; checks operate on their union.
|
||||
"""
|
||||
|
||||
permissions: frozenset[str]
|
||||
page_permissions: frozenset[str]
|
||||
action_permissions: frozenset[str]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
permissions: Iterable[str] | str | None = None,
|
||||
*,
|
||||
pages: Iterable[str] | str | None = None,
|
||||
actions: Iterable[str] | str | None = None,
|
||||
page_permissions: Iterable[str] | str | None = None,
|
||||
action_permissions: Iterable[str] | str | None = None,
|
||||
) -> None:
|
||||
"""Create an immutable, whitespace-normalised permission set."""
|
||||
|
||||
object.__setattr__(self, "permissions", _normalise(permissions))
|
||||
object.__setattr__(
|
||||
self,
|
||||
"page_permissions",
|
||||
_normalise(pages) | _normalise(page_permissions),
|
||||
)
|
||||
object.__setattr__(
|
||||
self,
|
||||
"action_permissions",
|
||||
_normalise(actions) | _normalise(action_permissions),
|
||||
)
|
||||
|
||||
@property
|
||||
def is_superuser(self) -> bool:
|
||||
"""Return whether the global ``*`` wildcard is present."""
|
||||
|
||||
return "*" in self._all_permissions
|
||||
|
||||
@property
|
||||
def _all_permissions(self) -> frozenset[str]:
|
||||
return self.permissions | self.page_permissions | self.action_permissions
|
||||
|
||||
def has(self, permission: str) -> bool:
|
||||
"""Return whether an exact or wildcard grant covers ``permission``."""
|
||||
|
||||
required = permission.strip()
|
||||
if not required:
|
||||
return False
|
||||
grants = self._all_permissions
|
||||
if "*" in grants or required in grants:
|
||||
return True
|
||||
return any(grant.endswith("/*") and required.startswith(grant[:-1]) for grant in grants)
|
||||
|
||||
def allows(self, permission: str) -> bool:
|
||||
"""Alias for :meth:`has`, convenient in UI guard code."""
|
||||
|
||||
return self.has(permission)
|
||||
|
||||
def has_all(self, *permissions: object) -> bool:
|
||||
"""Return true when every requested permission is granted (AND)."""
|
||||
|
||||
return all(self.has(permission) for permission in _requirements(permissions))
|
||||
|
||||
def all(self, *permissions: object) -> bool:
|
||||
"""Alias for :meth:`has_all`, mirroring the web client's AND helper."""
|
||||
|
||||
return self.has_all(*permissions)
|
||||
|
||||
def has_any(self, *permissions: object) -> bool:
|
||||
"""Return true when at least one requested permission is granted (OR)."""
|
||||
|
||||
return any(self.has(permission) for permission in _requirements(permissions))
|
||||
|
||||
def any(self, *permissions: object) -> bool:
|
||||
"""Alias for :meth:`has_any`, mirroring ``v-perms`` OR semantics."""
|
||||
|
||||
return self.has_any(*permissions)
|
||||
|
||||
def can_access_page(self, permission: str) -> bool:
|
||||
"""Check the permission protecting a page or navigation entry."""
|
||||
|
||||
return self.has(permission)
|
||||
|
||||
def has_page(self, permission: str) -> bool:
|
||||
"""Alias for :meth:`can_access_page`."""
|
||||
|
||||
return self.can_access_page(permission)
|
||||
|
||||
def can_perform_action(self, permission: str) -> bool:
|
||||
"""Check the permission protecting a button or write action."""
|
||||
|
||||
return self.has(permission)
|
||||
|
||||
def has_action(self, permission: str) -> bool:
|
||||
"""Alias for :meth:`can_perform_action`."""
|
||||
|
||||
return self.can_perform_action(permission)
|
||||
|
||||
def can(self, page_or_permission: str, action: str | None = None) -> bool:
|
||||
"""Check a direct permission or a ``page/action`` combination."""
|
||||
|
||||
if action is None:
|
||||
return self.has(page_or_permission)
|
||||
permission = f"{page_or_permission.rstrip('/')}/{action.lstrip('/')}"
|
||||
return self.has(permission)
|
||||
|
||||
def __contains__(self, permission: object) -> bool:
|
||||
"""Support ``permission in permission_set`` checks."""
|
||||
|
||||
return isinstance(permission, str) and self.has(permission)
|
||||
|
||||
def __iter__(self) -> Iterator[str]:
|
||||
"""Iterate over all explicit grants in stable sorted order."""
|
||||
|
||||
return iter(sorted(self._all_permissions))
|
||||
|
||||
def __len__(self) -> int:
|
||||
"""Return the number of distinct explicit grants."""
|
||||
|
||||
return len(self._all_permissions)
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
"""Return whether at least one grant exists."""
|
||||
|
||||
return bool(self._all_permissions)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Authenticated session state independent of the UI framework."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from .models import UserProfile
|
||||
from .permissions import PermissionSet
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Session:
|
||||
"""The token, user, permissions and login guards for one signed-in doctor."""
|
||||
|
||||
token: str = ""
|
||||
user: UserProfile = field(default_factory=UserProfile)
|
||||
permissions: PermissionSet = field(default_factory=PermissionSet)
|
||||
menu: list[dict[str, Any]] = field(default_factory=list)
|
||||
is_paw: int = 1
|
||||
need_bind_work_wechat: bool = False
|
||||
metadata: dict[str, Any] = field(default_factory=dict, repr=False)
|
||||
|
||||
@property
|
||||
def authenticated(self) -> bool:
|
||||
"""Return whether this session contains a non-empty access token."""
|
||||
|
||||
return bool(self.token.strip())
|
||||
|
||||
@property
|
||||
def password_change_required(self) -> bool:
|
||||
"""Return whether first-login password replacement is required."""
|
||||
|
||||
return self.is_paw == 0
|
||||
|
||||
@property
|
||||
def work_wechat_binding_required(self) -> bool:
|
||||
"""Return whether the user must bind Enterprise WeChat before use."""
|
||||
|
||||
return self.need_bind_work_wechat
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Structured application logging with credential redaction."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from pathlib import Path
|
||||
|
||||
_SECRET_PATTERNS = (
|
||||
re.compile(r'(?i)(token|usersig|authorization)(["\'\s:=]+)([^,\s"\']+)'),
|
||||
re.compile(r'(?i)(password)(["\'\s:=]+)([^,\s"\']+)'),
|
||||
)
|
||||
|
||||
|
||||
class SecretRedactionFilter(logging.Filter):
|
||||
"""Remove known credential-shaped values from every rendered log record."""
|
||||
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
rendered = record.getMessage()
|
||||
for pattern in _SECRET_PATTERNS:
|
||||
rendered = pattern.sub(r"\1\2<redacted>", rendered)
|
||||
record.msg = rendered
|
||||
record.args = ()
|
||||
return True
|
||||
|
||||
|
||||
def configure_logging(log_dir: Path, level: str = "INFO") -> Path:
|
||||
"""Configure console and rotating file logging and return the log path."""
|
||||
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_file = log_dir / "doctor-workstation.log"
|
||||
numeric_level = getattr(logging, level.upper(), logging.INFO)
|
||||
formatter = logging.Formatter(
|
||||
fmt="%(asctime)s %(levelname)s %(name)s — %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
redaction = SecretRedactionFilter()
|
||||
|
||||
root = logging.getLogger()
|
||||
root.setLevel(numeric_level)
|
||||
root.handlers.clear()
|
||||
|
||||
file_handler = RotatingFileHandler(
|
||||
log_file,
|
||||
maxBytes=2 * 1024 * 1024,
|
||||
backupCount=4,
|
||||
encoding="utf-8",
|
||||
)
|
||||
file_handler.setFormatter(formatter)
|
||||
file_handler.addFilter(redaction)
|
||||
root.addHandler(file_handler)
|
||||
|
||||
console = logging.StreamHandler()
|
||||
console.setFormatter(formatter)
|
||||
console.addFilter(redaction)
|
||||
root.addHandler(console)
|
||||
return log_file
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Locate bundled resources in source and PyInstaller builds."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def project_root() -> Path:
|
||||
frozen_root = getattr(sys, "_MEIPASS", None)
|
||||
if frozen_root:
|
||||
return Path(frozen_root)
|
||||
return Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def resource_path(*parts: str) -> Path:
|
||||
return project_root().joinpath("resources", *parts)
|
||||
|
||||
|
||||
def video_dist_path() -> Path:
|
||||
candidates = (
|
||||
project_root() / "video_companion" / "dist" / "index.html",
|
||||
project_root() / "video_companion_dist" / "index.html",
|
||||
)
|
||||
for candidate in candidates:
|
||||
if candidate.exists():
|
||||
return candidate
|
||||
return resource_path("video", "index.html")
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Transport, credential and repository adapters for the doctor workstation."""
|
||||
|
||||
from .api_client import ApiClient
|
||||
from .factory import build_repository
|
||||
from .mock_repository import DEMO_PERMISSIONS, DemoDoctorRepository
|
||||
from .repository import (
|
||||
DIAGNOSIS_AI_PERMISSIONS,
|
||||
PRESCRIPTION_LIBRARY_PERMISSIONS,
|
||||
PRESCRIPTION_PERMISSIONS,
|
||||
AuditAction,
|
||||
DoctorRepository,
|
||||
RemoteDoctorRepository,
|
||||
)
|
||||
from .token_store import KeyringLike, TokenStore
|
||||
|
||||
__all__ = [
|
||||
"ApiClient",
|
||||
"AuditAction",
|
||||
"DEMO_PERMISSIONS",
|
||||
"DemoDoctorRepository",
|
||||
"DIAGNOSIS_AI_PERMISSIONS",
|
||||
"DoctorRepository",
|
||||
"KeyringLike",
|
||||
"PRESCRIPTION_LIBRARY_PERMISSIONS",
|
||||
"PRESCRIPTION_PERMISSIONS",
|
||||
"RemoteDoctorRepository",
|
||||
"TokenStore",
|
||||
"build_repository",
|
||||
]
|
||||
@@ -0,0 +1,416 @@
|
||||
"""Synchronous HTTP client for the legacy admin API envelope."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections.abc import Callable, Mapping
|
||||
from threading import RLock
|
||||
from typing import Any
|
||||
from urllib.parse import urljoin, urlsplit, urlunsplit
|
||||
|
||||
import httpx
|
||||
|
||||
from doctor_workstation.core.errors import (
|
||||
ApiBusinessError,
|
||||
ApiHttpError,
|
||||
ApiProtocolError,
|
||||
ApiTimeoutError,
|
||||
ApiTransportError,
|
||||
AuthenticationExpiredError,
|
||||
InstallationRequiredError,
|
||||
OpenPageRequiredError,
|
||||
WorkWechatBindingRequiredError,
|
||||
)
|
||||
|
||||
|
||||
class ApiClient:
|
||||
"""A small, testable client implementing the admin API contract.
|
||||
|
||||
The supplied base URL may be either the site origin or an URL already
|
||||
ending in ``/adminapi``. Timeout retries are deliberately limited to GET
|
||||
requests so that medical write operations are never submitted twice.
|
||||
"""
|
||||
|
||||
API_VERSION = "1.9.4"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
*,
|
||||
token: str = "",
|
||||
timeout: float | httpx.Timeout = 30.0,
|
||||
max_retries: int = 2,
|
||||
retry_backoff: float = 0.0,
|
||||
verify: bool = True,
|
||||
transport: httpx.BaseTransport | None = None,
|
||||
client: httpx.Client | None = None,
|
||||
sleep: Callable[[float], None] = time.sleep,
|
||||
) -> None:
|
||||
"""Create a client without performing any network requests."""
|
||||
|
||||
if max_retries < 0:
|
||||
raise ValueError("max_retries must be non-negative")
|
||||
if retry_backoff < 0:
|
||||
raise ValueError("retry_backoff must be non-negative")
|
||||
if client is not None and transport is not None:
|
||||
raise ValueError("pass either client or transport, not both")
|
||||
self.base_url = self.normalise_base_url(base_url)
|
||||
self.timeout = timeout
|
||||
self.max_retries = max_retries
|
||||
self.retry_backoff = retry_backoff
|
||||
self._sleep = sleep
|
||||
self._token = token.strip()
|
||||
self._lock = RLock()
|
||||
self._owns_client = client is None
|
||||
self._client = client or httpx.Client(transport=transport, verify=verify)
|
||||
|
||||
@staticmethod
|
||||
def normalise_base_url(base_url: str) -> str:
|
||||
"""Return an absolute URL ending in exactly one ``/adminapi/``."""
|
||||
|
||||
candidate = base_url.strip()
|
||||
parsed = urlsplit(candidate)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise ValueError("base_url must be an absolute http(s) URL")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("base_url must not include query parameters or fragments")
|
||||
path = parsed.path.rstrip("/")
|
||||
if path.lower().endswith("/adminapi"):
|
||||
normalised_path = f"{path}/"
|
||||
else:
|
||||
normalised_path = f"{path}/adminapi/" if path else "/adminapi/"
|
||||
return urlunsplit((parsed.scheme, parsed.netloc, normalised_path, "", ""))
|
||||
|
||||
@property
|
||||
def token(self) -> str:
|
||||
"""Return the current in-memory access token."""
|
||||
|
||||
with self._lock:
|
||||
return self._token
|
||||
|
||||
@token.setter
|
||||
def token(self, value: str) -> None:
|
||||
"""Replace the in-memory access token used by later requests."""
|
||||
|
||||
with self._lock:
|
||||
self._token = value.strip()
|
||||
|
||||
def set_token(self, token: str) -> None:
|
||||
"""Set the authentication token; provided for explicit session code."""
|
||||
|
||||
self.token = token
|
||||
|
||||
def clear_token(self) -> None:
|
||||
"""Remove the authentication token from memory."""
|
||||
|
||||
self.token = ""
|
||||
|
||||
def get(
|
||||
self,
|
||||
endpoint: str,
|
||||
params: Mapping[str, Any] | None = None,
|
||||
*,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
timeout: float | httpx.Timeout | None = None,
|
||||
) -> Any:
|
||||
"""Issue a GET request and return the unwrapped envelope data."""
|
||||
|
||||
return self.request(
|
||||
"GET", endpoint, params=params, headers=headers, timeout=timeout
|
||||
)
|
||||
|
||||
def post(
|
||||
self,
|
||||
endpoint: str,
|
||||
payload: Mapping[str, Any] | None = None,
|
||||
*,
|
||||
json: Mapping[str, Any] | None = None,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
timeout: float | httpx.Timeout | None = None,
|
||||
) -> Any:
|
||||
"""Issue a non-retried JSON POST and return the unwrapped data."""
|
||||
|
||||
if payload is not None and json is not None:
|
||||
raise ValueError("pass either payload or json, not both")
|
||||
body = json if json is not None else payload
|
||||
return self.request(
|
||||
"POST", endpoint, json=body or {}, headers=headers, timeout=timeout
|
||||
)
|
||||
|
||||
def post_multipart(
|
||||
self,
|
||||
endpoint: str,
|
||||
*,
|
||||
files: Mapping[str, Any],
|
||||
data: Mapping[str, Any] | None = None,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
) -> Any:
|
||||
"""Issue a non-retried multipart POST and return unwrapped data.
|
||||
|
||||
``httpx`` owns the multipart boundary. In particular this method does
|
||||
not inherit the JSON ``Content-Type`` used by ordinary API writes.
|
||||
File objects remain owned by the caller and are consumed synchronously.
|
||||
"""
|
||||
|
||||
if not files:
|
||||
raise ValueError("multipart files must not be empty")
|
||||
return self.request(
|
||||
"POST",
|
||||
endpoint,
|
||||
data=data or {},
|
||||
files=files,
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
def get_bytes(self, url: str, *, max_bytes: int = 5 * 1024 * 1024) -> bytes:
|
||||
"""Download a public binary asset without applying the JSON envelope contract."""
|
||||
|
||||
if max_bytes <= 0:
|
||||
raise ValueError("max_bytes must be positive")
|
||||
candidate = url.strip()
|
||||
if not candidate:
|
||||
raise ValueError("url must not be empty")
|
||||
target = urljoin(self.base_url, candidate)
|
||||
parsed = urlsplit(target)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise ValueError("url must resolve to an absolute http(s) URL")
|
||||
try:
|
||||
response = self._client.get(
|
||||
target,
|
||||
headers={"Accept": "image/*,application/octet-stream;q=0.8"},
|
||||
timeout=self.timeout,
|
||||
follow_redirects=True,
|
||||
)
|
||||
except httpx.TimeoutException as exc:
|
||||
raise ApiTimeoutError("Image download timed out", data={"url": target}) from exc
|
||||
except httpx.RequestError as exc:
|
||||
raise ApiTransportError(
|
||||
f"Image download failed: {exc}", data={"url": target}
|
||||
) from exc
|
||||
request_id = self._request_id(response)
|
||||
if not 200 <= response.status_code < 300:
|
||||
raise ApiHttpError(
|
||||
f"Image server returned HTTP {response.status_code}",
|
||||
status_code=response.status_code,
|
||||
request_id=request_id,
|
||||
)
|
||||
length = response.headers.get("content-length")
|
||||
if length:
|
||||
try:
|
||||
if int(length) > max_bytes:
|
||||
raise ApiProtocolError(
|
||||
"Image response is too large",
|
||||
data={"max_bytes": max_bytes, "content_length": int(length)},
|
||||
status_code=response.status_code,
|
||||
request_id=request_id,
|
||||
)
|
||||
except ValueError:
|
||||
pass
|
||||
content = response.content
|
||||
if not content:
|
||||
raise ApiProtocolError(
|
||||
"Image response is empty",
|
||||
status_code=response.status_code,
|
||||
request_id=request_id,
|
||||
)
|
||||
if len(content) > max_bytes:
|
||||
raise ApiProtocolError(
|
||||
"Image response is too large",
|
||||
data={"max_bytes": max_bytes, "content_length": len(content)},
|
||||
status_code=response.status_code,
|
||||
request_id=request_id,
|
||||
)
|
||||
return content
|
||||
|
||||
def request(
|
||||
self,
|
||||
method: str,
|
||||
endpoint: str,
|
||||
*,
|
||||
params: Mapping[str, Any] | None = None,
|
||||
json: Mapping[str, Any] | None = None,
|
||||
data: Mapping[str, Any] | None = None,
|
||||
files: Mapping[str, Any] | None = None,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
timeout: float | httpx.Timeout | None = None,
|
||||
) -> Any:
|
||||
"""Issue one API request with structured transport/envelope errors."""
|
||||
|
||||
verb = method.upper().strip()
|
||||
if verb not in {"GET", "POST"}:
|
||||
raise ValueError("ApiClient only supports GET and POST")
|
||||
if verb == "GET" and (json is not None or data is not None or files is not None):
|
||||
raise ValueError("GET requests cannot include a body")
|
||||
if json is not None and (data is not None or files is not None):
|
||||
raise ValueError("JSON and multipart/form data are mutually exclusive")
|
||||
if files is not None and verb != "POST":
|
||||
raise ValueError("multipart uploads require POST")
|
||||
url = self._endpoint_url(endpoint)
|
||||
request_headers = self._headers(
|
||||
headers,
|
||||
json_content_type=files is None and data is None,
|
||||
)
|
||||
attempts = self.max_retries + 1 if verb == "GET" else 1
|
||||
response: httpx.Response | None = None
|
||||
request_timeout = self.timeout if timeout is None else timeout
|
||||
for attempt in range(attempts):
|
||||
try:
|
||||
response = self._client.request(
|
||||
verb,
|
||||
url,
|
||||
params=dict(params) if params is not None else None,
|
||||
json=dict(json) if verb == "POST" and json is not None else None,
|
||||
data=dict(data) if verb == "POST" and data is not None else None,
|
||||
files=dict(files) if files is not None else None,
|
||||
headers=request_headers,
|
||||
timeout=request_timeout,
|
||||
)
|
||||
break
|
||||
except httpx.TimeoutException as exc:
|
||||
if attempt + 1 < attempts:
|
||||
delay = self.retry_backoff * (2**attempt)
|
||||
if delay:
|
||||
self._sleep(delay)
|
||||
continue
|
||||
raise ApiTimeoutError(
|
||||
f"{verb} {endpoint} timed out after {attempt + 1} attempt(s)",
|
||||
data={"method": verb, "endpoint": endpoint, "attempts": attempt + 1},
|
||||
) from exc
|
||||
except httpx.RequestError as exc:
|
||||
raise ApiTransportError(
|
||||
f"{verb} {endpoint} failed: {exc}",
|
||||
data={"method": verb, "endpoint": endpoint},
|
||||
) from exc
|
||||
if response is None: # Defensive; the loop always returns or raises.
|
||||
raise ApiTransportError(f"{verb} {endpoint} produced no response")
|
||||
return self._unwrap(response)
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the internally-created HTTP transport."""
|
||||
|
||||
if self._owns_client:
|
||||
self._client.close()
|
||||
|
||||
def __enter__(self) -> ApiClient:
|
||||
"""Return this client for use as a context manager."""
|
||||
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
|
||||
"""Close owned resources when leaving a context manager."""
|
||||
|
||||
self.close()
|
||||
|
||||
def _endpoint_url(self, endpoint: str) -> str:
|
||||
value = endpoint.strip()
|
||||
parsed = urlsplit(value)
|
||||
if parsed.scheme or parsed.netloc:
|
||||
raise ValueError("endpoint must be a relative API path")
|
||||
path = parsed.path.lstrip("/")
|
||||
if path.lower().startswith("adminapi/"):
|
||||
path = path[len("adminapi/") :]
|
||||
if not path:
|
||||
raise ValueError("endpoint must not be empty")
|
||||
suffix = f"?{parsed.query}" if parsed.query else ""
|
||||
return f"{self.base_url}{path}{suffix}"
|
||||
|
||||
def _headers(
|
||||
self,
|
||||
extra: Mapping[str, str] | None,
|
||||
*,
|
||||
json_content_type: bool = True,
|
||||
) -> dict[str, str]:
|
||||
result = {
|
||||
"Accept": "application/json",
|
||||
"version": self.API_VERSION,
|
||||
}
|
||||
if json_content_type:
|
||||
result["Content-Type"] = "application/json;charset=UTF-8"
|
||||
token = self.token
|
||||
if token:
|
||||
result["token"] = token
|
||||
if extra:
|
||||
result.update(extra)
|
||||
if not json_content_type:
|
||||
for key in tuple(result):
|
||||
if key.lower() == "content-type":
|
||||
result.pop(key)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _request_id(response: httpx.Response) -> str | None:
|
||||
return response.headers.get("x-request-id") or response.headers.get("request-id")
|
||||
|
||||
def _unwrap(self, response: httpx.Response) -> Any:
|
||||
request_id = self._request_id(response)
|
||||
if not 200 <= response.status_code < 300:
|
||||
raise ApiHttpError(
|
||||
f"API returned HTTP {response.status_code}",
|
||||
status_code=response.status_code,
|
||||
request_id=request_id,
|
||||
)
|
||||
try:
|
||||
envelope = response.json()
|
||||
except (ValueError, UnicodeDecodeError) as exc:
|
||||
raise ApiProtocolError(
|
||||
"API response is not valid JSON",
|
||||
status_code=response.status_code,
|
||||
request_id=request_id,
|
||||
) from exc
|
||||
if not isinstance(envelope, Mapping):
|
||||
raise ApiProtocolError(
|
||||
"API response envelope must be an object",
|
||||
data=envelope,
|
||||
status_code=response.status_code,
|
||||
request_id=request_id,
|
||||
)
|
||||
raw_code = envelope.get("code")
|
||||
try:
|
||||
if isinstance(raw_code, bool):
|
||||
raise ValueError
|
||||
code = int(raw_code)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ApiProtocolError(
|
||||
"API response envelope has no valid code",
|
||||
data=dict(envelope),
|
||||
status_code=response.status_code,
|
||||
request_id=request_id,
|
||||
) from exc
|
||||
data = envelope.get("data")
|
||||
message = str(envelope.get("msg") or envelope.get("message") or "").strip()
|
||||
if code == 1:
|
||||
return data
|
||||
context = {
|
||||
"code": code,
|
||||
"data": data,
|
||||
"status_code": response.status_code,
|
||||
"request_id": request_id,
|
||||
}
|
||||
if code == 0:
|
||||
if not message and isinstance(data, str):
|
||||
message = data
|
||||
raise ApiBusinessError(message or "API rejected the operation", **context)
|
||||
if code == -1:
|
||||
raise AuthenticationExpiredError(message or "Login has expired", **context)
|
||||
if code == 10:
|
||||
raise WorkWechatBindingRequiredError(
|
||||
message or "Enterprise WeChat binding is required", **context
|
||||
)
|
||||
if code == 2:
|
||||
target = str(_mapping(data).get("url") or "")
|
||||
raise OpenPageRequiredError(
|
||||
message or "The operation must continue in another page",
|
||||
url=target,
|
||||
data=data,
|
||||
status_code=response.status_code,
|
||||
request_id=request_id,
|
||||
)
|
||||
if code == -2:
|
||||
raise InstallationRequiredError(
|
||||
message or "A required companion component is not installed", **context
|
||||
)
|
||||
raise ApiProtocolError(message or f"Unsupported API envelope code: {code}", **context)
|
||||
|
||||
|
||||
def _mapping(value: object) -> Mapping[str, Any]:
|
||||
return value if isinstance(value, Mapping) else {}
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Compatibility module exporting the in-memory demo repository."""
|
||||
|
||||
from .mock_repository import DEMO_PERMISSIONS, DemoDoctorRepository
|
||||
|
||||
__all__ = ["DEMO_PERMISSIONS", "DemoDoctorRepository"]
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Small construction helper used by the application bootstrap layer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
|
||||
from .api_client import ApiClient
|
||||
from .mock_repository import DemoDoctorRepository
|
||||
from .repository import DoctorRepository, RemoteDoctorRepository
|
||||
from .token_store import TokenStore
|
||||
|
||||
|
||||
def build_repository(
|
||||
*,
|
||||
demo: bool,
|
||||
base_url: str | None = None,
|
||||
token_store: TokenStore | None = None,
|
||||
client: ApiClient | None = None,
|
||||
token: str = "",
|
||||
timeout: float | httpx.Timeout = 30.0,
|
||||
max_retries: int = 2,
|
||||
verify: bool = True,
|
||||
) -> DoctorRepository:
|
||||
"""Build a demo or remote repository without depending on ``AppConfig``.
|
||||
|
||||
``client`` is primarily useful for tests or advanced bootstrap code. For
|
||||
normal remote use, provide ``base_url`` and this factory creates the
|
||||
correctly configured :class:`ApiClient`.
|
||||
"""
|
||||
|
||||
if demo:
|
||||
if client is not None:
|
||||
raise ValueError("client cannot be supplied in demo mode")
|
||||
return DemoDoctorRepository()
|
||||
api_client = client
|
||||
if api_client is None:
|
||||
if base_url is None or not base_url.strip():
|
||||
raise ValueError("base_url is required in remote mode")
|
||||
api_client = ApiClient(
|
||||
base_url,
|
||||
token=token,
|
||||
timeout=timeout,
|
||||
max_retries=max_retries,
|
||||
verify=verify,
|
||||
)
|
||||
return RemoteDoctorRepository(api_client, token_store)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
"""Compatibility module exporting the production doctor repository."""
|
||||
|
||||
from .repository import (
|
||||
DIAGNOSIS_AI_PERMISSIONS,
|
||||
PRESCRIPTION_LIBRARY_PERMISSIONS,
|
||||
PRESCRIPTION_PERMISSIONS,
|
||||
AuditAction,
|
||||
DoctorRepository,
|
||||
RemoteDoctorRepository,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AuditAction",
|
||||
"DoctorRepository",
|
||||
"DIAGNOSIS_AI_PERMISSIONS",
|
||||
"PRESCRIPTION_LIBRARY_PERMISSIONS",
|
||||
"PRESCRIPTION_PERMISSIONS",
|
||||
"RemoteDoctorRepository",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,490 @@
|
||||
"""Token persistence using OS keyring with a restricted-file fallback."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import ctypes
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import tempfile
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
|
||||
class KeyringLike(Protocol):
|
||||
"""The small subset shared by the optional keyring module and its backends."""
|
||||
|
||||
def get_password(self, service: str, username: str) -> str | None:
|
||||
"""Return a stored secret or ``None``."""
|
||||
|
||||
def set_password(self, service: str, username: str, password: str) -> None:
|
||||
"""Persist one secret."""
|
||||
|
||||
def delete_password(self, service: str, username: str) -> None:
|
||||
"""Delete one secret."""
|
||||
|
||||
|
||||
_AUTO_KEYRING = object()
|
||||
|
||||
|
||||
class TokenStore:
|
||||
"""Store tokens and optional login passwords with OS-protected storage.
|
||||
|
||||
If a working ``keyring`` backend is importable, the token is stored there
|
||||
and the JSON file contains at most the remembered account name and the
|
||||
non-secret API scope. Login passwords use the keyring first; on Windows,
|
||||
an unavailable keyring falls back to a DPAPI-encrypted blob that only the
|
||||
current Windows user can decrypt. Plaintext passwords are never written.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
path: str | os.PathLike[str] | None = None,
|
||||
*,
|
||||
service_name: str = "zyt-doctor-workstation",
|
||||
token_name: str = "access-token",
|
||||
keyring_backend: KeyringLike | None | object = _AUTO_KEYRING,
|
||||
) -> None:
|
||||
"""Create a token store without writing any files."""
|
||||
|
||||
self.path = Path(path) if path is not None else self.default_path()
|
||||
self.service_name = service_name
|
||||
self.token_name = token_name
|
||||
self._keyring = self._load_keyring(keyring_backend)
|
||||
self._uses_keyring = self._probe_keyring()
|
||||
|
||||
@staticmethod
|
||||
def default_path() -> Path:
|
||||
"""Return a per-user fallback credential path for the current platform."""
|
||||
|
||||
if os.name == "nt":
|
||||
root = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
|
||||
else:
|
||||
root = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
|
||||
return root / "ZYTDoctorWorkstation" / "credentials.json"
|
||||
|
||||
@property
|
||||
def uses_keyring(self) -> bool:
|
||||
"""Return whether token operations currently use a working keyring."""
|
||||
|
||||
return self._uses_keyring
|
||||
|
||||
def load_token(self, *, scope: str | None = None) -> str | None:
|
||||
"""Load a token, optionally requiring an exact persisted API scope.
|
||||
|
||||
Supplying ``scope`` is the safe choice for automatic login restoration:
|
||||
an older unscoped token, or a token issued by another API base URL, is
|
||||
never returned to the caller.
|
||||
"""
|
||||
|
||||
data = self._read_file()
|
||||
if scope is not None:
|
||||
expected_scope = self._normalise_scope(scope)
|
||||
stored_scope = self._normalise_scope(data.get("scope"))
|
||||
if not expected_scope or stored_scope != expected_scope:
|
||||
return None
|
||||
|
||||
if self._uses_keyring and self._keyring is not None:
|
||||
try:
|
||||
token = self._keyring.get_password(self.service_name, self.token_name)
|
||||
if token:
|
||||
return token
|
||||
except Exception:
|
||||
self._uses_keyring = False
|
||||
value = data.get("token")
|
||||
return str(value) if isinstance(value, str) and value else None
|
||||
|
||||
def save_token(
|
||||
self,
|
||||
token: str,
|
||||
*,
|
||||
account: str | None = None,
|
||||
scope: str | None = None,
|
||||
) -> None:
|
||||
"""Persist a token plus optional account and API-scope metadata.
|
||||
|
||||
Passing an empty ``account`` explicitly forgets a previously remembered
|
||||
account and its keyring password.
|
||||
"""
|
||||
|
||||
cleaned = token.strip()
|
||||
if not cleaned:
|
||||
self.clear_token()
|
||||
if account is not None:
|
||||
self.save_account(account)
|
||||
return
|
||||
data = self._read_file()
|
||||
if account is not None:
|
||||
account_value = account.strip()
|
||||
previous_account = str(data.get("account") or "").strip()
|
||||
previous_scope = self._normalise_scope(data.get("scope"))
|
||||
next_scope = (
|
||||
self._normalise_scope(scope) if scope is not None else previous_scope
|
||||
)
|
||||
if previous_account and (
|
||||
previous_account != account_value
|
||||
or (account_value and previous_scope != next_scope)
|
||||
):
|
||||
self.clear_password(account=previous_account, scope=previous_scope)
|
||||
data.pop("credential", None)
|
||||
if account_value:
|
||||
data["account"] = account_value
|
||||
else:
|
||||
data.pop("account", None)
|
||||
if scope is not None:
|
||||
scope_value = self._normalise_scope(scope)
|
||||
if scope_value:
|
||||
data["scope"] = scope_value
|
||||
else:
|
||||
data.pop("scope", None)
|
||||
if self._uses_keyring and self._keyring is not None:
|
||||
try:
|
||||
self._keyring.set_password(self.service_name, self.token_name, cleaned)
|
||||
data.pop("token", None)
|
||||
self._write_file(data)
|
||||
return
|
||||
except Exception:
|
||||
self._uses_keyring = False
|
||||
data["token"] = cleaned
|
||||
self._write_file(data)
|
||||
|
||||
def clear_token(self) -> None:
|
||||
"""Delete the token while retaining remembered login credentials."""
|
||||
|
||||
if self._uses_keyring and self._keyring is not None:
|
||||
try:
|
||||
self._keyring.delete_password(self.service_name, self.token_name)
|
||||
except Exception:
|
||||
self._uses_keyring = False
|
||||
data = self._read_file()
|
||||
data.pop("token", None)
|
||||
if not data.get("account"):
|
||||
data.pop("scope", None)
|
||||
self._write_file(data)
|
||||
|
||||
def load_account(self) -> str | None:
|
||||
"""Load the non-secret remembered login account."""
|
||||
|
||||
value = self._read_file().get("account")
|
||||
return str(value) if isinstance(value, str) and value else None
|
||||
|
||||
def save_account(self, account: str) -> None:
|
||||
"""Remember only the account name used to pre-fill the login form."""
|
||||
|
||||
data = self._read_file()
|
||||
cleaned = account.strip()
|
||||
if cleaned:
|
||||
data["account"] = cleaned
|
||||
else:
|
||||
data.pop("account", None)
|
||||
self._write_file(data)
|
||||
|
||||
def clear_account(self) -> None:
|
||||
"""Forget the remembered account and its keyring password."""
|
||||
|
||||
data = self._read_file()
|
||||
self.clear_password(
|
||||
account=str(data.get("account") or ""),
|
||||
scope=str(data.get("scope") or ""),
|
||||
)
|
||||
self.save_account("")
|
||||
|
||||
def load_password(self, *, account: str, scope: str) -> str | None:
|
||||
"""Load one scoped password from keyring or a Windows DPAPI blob."""
|
||||
|
||||
target = self._password_target(account, scope)
|
||||
if not target:
|
||||
return None
|
||||
if self._uses_keyring and self._keyring is not None:
|
||||
try:
|
||||
value = self._keyring.get_password(self.service_name, target)
|
||||
if value:
|
||||
return str(value)
|
||||
except Exception:
|
||||
self._uses_keyring = False
|
||||
data = self._read_file()
|
||||
if self._password_target(
|
||||
str(data.get("account") or ""),
|
||||
str(data.get("scope") or ""),
|
||||
) != target:
|
||||
return None
|
||||
credential = data.get("credential")
|
||||
if not isinstance(credential, str) or not credential:
|
||||
return None
|
||||
return self._unprotect_password(credential, target)
|
||||
|
||||
def save_password(self, password: str, *, account: str, scope: str) -> bool:
|
||||
"""Save one password using keyring or Windows user-scoped DPAPI."""
|
||||
|
||||
target = self._password_target(account, scope)
|
||||
if not target or not password:
|
||||
return False
|
||||
data = self._read_file()
|
||||
previous_target = self._password_target(
|
||||
str(data.get("account") or ""),
|
||||
str(data.get("scope") or ""),
|
||||
)
|
||||
if (
|
||||
previous_target
|
||||
and previous_target != target
|
||||
and self._uses_keyring
|
||||
and self._keyring is not None
|
||||
):
|
||||
with suppress(Exception):
|
||||
self._keyring.delete_password(self.service_name, previous_target)
|
||||
if self._uses_keyring and self._keyring is not None:
|
||||
try:
|
||||
self._keyring.set_password(self.service_name, target, password)
|
||||
except Exception:
|
||||
self._uses_keyring = False
|
||||
else:
|
||||
data["account"] = account.strip()
|
||||
data["scope"] = self._normalise_scope(scope)
|
||||
data.pop("credential", None)
|
||||
self._write_file(data)
|
||||
return True
|
||||
protected = self._protect_password(password, target)
|
||||
if not protected:
|
||||
return False
|
||||
data["account"] = account.strip()
|
||||
data["scope"] = self._normalise_scope(scope)
|
||||
data["credential"] = protected
|
||||
self._write_file(data)
|
||||
return True
|
||||
|
||||
def clear_password(self, *, account: str, scope: str) -> None:
|
||||
"""Delete one scoped login password from the OS keyring."""
|
||||
|
||||
target = self._password_target(account, scope)
|
||||
if not target:
|
||||
return
|
||||
if self._uses_keyring and self._keyring is not None:
|
||||
with suppress(Exception):
|
||||
self._keyring.delete_password(self.service_name, target)
|
||||
data = self._read_file()
|
||||
stored_target = self._password_target(
|
||||
str(data.get("account") or ""),
|
||||
str(data.get("scope") or ""),
|
||||
)
|
||||
if stored_target == target and "credential" in data:
|
||||
data.pop("credential", None)
|
||||
self._write_file(data)
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Delete both token and remembered account information."""
|
||||
|
||||
data = self._read_file()
|
||||
self.clear_password(
|
||||
account=str(data.get("account") or ""),
|
||||
scope=str(data.get("scope") or ""),
|
||||
)
|
||||
if self._uses_keyring and self._keyring is not None:
|
||||
try:
|
||||
self._keyring.delete_password(self.service_name, self.token_name)
|
||||
except Exception:
|
||||
self._uses_keyring = False
|
||||
try:
|
||||
self.path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
self._write_file({})
|
||||
|
||||
def get_token(self) -> str | None:
|
||||
"""Compatibility alias for :meth:`load_token`."""
|
||||
|
||||
return self.load_token()
|
||||
|
||||
def set_token(self, token: str) -> None:
|
||||
"""Compatibility alias for :meth:`save_token`."""
|
||||
|
||||
self.save_token(token)
|
||||
|
||||
def delete_token(self) -> None:
|
||||
"""Compatibility alias for :meth:`clear_token`."""
|
||||
|
||||
self.clear_token()
|
||||
|
||||
@staticmethod
|
||||
def _load_keyring(candidate: KeyringLike | None | object) -> KeyringLike | None:
|
||||
if candidate is not _AUTO_KEYRING:
|
||||
return candidate if candidate is not None else None # type: ignore[return-value]
|
||||
try:
|
||||
import keyring # type: ignore[import-not-found]
|
||||
|
||||
return keyring
|
||||
except (ImportError, RuntimeError):
|
||||
return None
|
||||
|
||||
def _probe_keyring(self) -> bool:
|
||||
if self._keyring is None:
|
||||
return False
|
||||
try:
|
||||
self._keyring.get_password(self.service_name, self.token_name)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _normalise_scope(value: object) -> str:
|
||||
"""Return a stable comparison form for a non-secret API base URL."""
|
||||
|
||||
return str(value or "").strip().rstrip("/")
|
||||
|
||||
def _password_target(self, account: str, scope: str) -> str:
|
||||
"""Return an opaque keyring name isolated by account and API server."""
|
||||
|
||||
clean_account = account.strip().casefold()
|
||||
clean_scope = self._normalise_scope(scope).casefold()
|
||||
if not clean_account or not clean_scope:
|
||||
return ""
|
||||
digest = hashlib.sha256(f"{clean_scope}\n{clean_account}".encode()).hexdigest()
|
||||
return f"login-password:{digest}"
|
||||
|
||||
def _protect_password(self, password: str, target: str) -> str | None:
|
||||
"""Return a Windows DPAPI blob, or ``None`` on unsupported systems."""
|
||||
|
||||
if os.name != "nt":
|
||||
return None
|
||||
try:
|
||||
encrypted = self._crypt_protect(
|
||||
password.encode("utf-8"),
|
||||
self._credential_entropy(target),
|
||||
)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return base64.b64encode(encrypted).decode("ascii")
|
||||
|
||||
def _unprotect_password(self, protected: str, target: str) -> str | None:
|
||||
"""Decrypt a Windows DPAPI blob for this account/server target."""
|
||||
|
||||
if os.name != "nt":
|
||||
return None
|
||||
try:
|
||||
encrypted = base64.b64decode(protected, validate=True)
|
||||
plaintext = self._crypt_unprotect(
|
||||
encrypted,
|
||||
self._credential_entropy(target),
|
||||
)
|
||||
return plaintext.decode("utf-8")
|
||||
except (OSError, UnicodeError, ValueError):
|
||||
return None
|
||||
|
||||
def _credential_entropy(self, target: str) -> bytes:
|
||||
return hashlib.sha256(f"{self.service_name}\n{target}".encode()).digest()
|
||||
|
||||
@staticmethod
|
||||
def _crypt_protect(data: bytes, entropy: bytes) -> bytes:
|
||||
from ctypes import wintypes
|
||||
|
||||
class DataBlob(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("size", wintypes.DWORD),
|
||||
("data", ctypes.POINTER(ctypes.c_ubyte)),
|
||||
]
|
||||
|
||||
def make_blob(value: bytes) -> tuple[DataBlob, ctypes.Array[Any]]:
|
||||
buffer = ctypes.create_string_buffer(value)
|
||||
blob = DataBlob(
|
||||
len(value),
|
||||
ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ubyte)),
|
||||
)
|
||||
return blob, buffer
|
||||
|
||||
source, _source_buffer = make_blob(data)
|
||||
optional_entropy, _entropy_buffer = make_blob(entropy)
|
||||
destination = DataBlob()
|
||||
if not ctypes.windll.crypt32.CryptProtectData(
|
||||
ctypes.byref(source),
|
||||
None,
|
||||
ctypes.byref(optional_entropy),
|
||||
None,
|
||||
None,
|
||||
0x01,
|
||||
ctypes.byref(destination),
|
||||
):
|
||||
raise ctypes.WinError()
|
||||
try:
|
||||
return ctypes.string_at(destination.data, destination.size)
|
||||
finally:
|
||||
ctypes.windll.kernel32.LocalFree(destination.data)
|
||||
|
||||
@staticmethod
|
||||
def _crypt_unprotect(data: bytes, entropy: bytes) -> bytes:
|
||||
from ctypes import wintypes
|
||||
|
||||
class DataBlob(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("size", wintypes.DWORD),
|
||||
("data", ctypes.POINTER(ctypes.c_ubyte)),
|
||||
]
|
||||
|
||||
def make_blob(value: bytes) -> tuple[DataBlob, ctypes.Array[Any]]:
|
||||
buffer = ctypes.create_string_buffer(value)
|
||||
blob = DataBlob(
|
||||
len(value),
|
||||
ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ubyte)),
|
||||
)
|
||||
return blob, buffer
|
||||
|
||||
source, _source_buffer = make_blob(data)
|
||||
optional_entropy, _entropy_buffer = make_blob(entropy)
|
||||
destination = DataBlob()
|
||||
if not ctypes.windll.crypt32.CryptUnprotectData(
|
||||
ctypes.byref(source),
|
||||
None,
|
||||
ctypes.byref(optional_entropy),
|
||||
None,
|
||||
None,
|
||||
0x01,
|
||||
ctypes.byref(destination),
|
||||
):
|
||||
raise ctypes.WinError()
|
||||
try:
|
||||
return ctypes.string_at(destination.data, destination.size)
|
||||
finally:
|
||||
ctypes.windll.kernel32.LocalFree(destination.data)
|
||||
|
||||
def _read_file(self) -> dict[str, Any]:
|
||||
try:
|
||||
content = self.path.read_text(encoding="utf-8")
|
||||
value = json.loads(content)
|
||||
except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):
|
||||
return {}
|
||||
if not isinstance(value, dict):
|
||||
return {}
|
||||
# Explicit allow-list guarantees accidental password-like fields are ignored.
|
||||
return {
|
||||
key: value[key]
|
||||
for key in ("token", "account", "scope", "credential")
|
||||
if key in value
|
||||
}
|
||||
|
||||
def _write_file(self, data: dict[str, Any]) -> None:
|
||||
safe = {
|
||||
key: data[key]
|
||||
for key in ("token", "account", "scope", "credential")
|
||||
if data.get(key)
|
||||
}
|
||||
if not safe:
|
||||
with suppress(OSError):
|
||||
self.path.unlink(missing_ok=True)
|
||||
return
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp_fd, temp_name = tempfile.mkstemp(prefix=f".{self.path.name}.", dir=self.path.parent)
|
||||
temp_path = Path(temp_name)
|
||||
try:
|
||||
os.chmod(temp_path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
with os.fdopen(temp_fd, "w", encoding="utf-8", newline="\n") as handle:
|
||||
temp_fd = -1
|
||||
json.dump(safe, handle, ensure_ascii=False, separators=(",", ":"))
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_path, self.path)
|
||||
os.chmod(self.path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
finally:
|
||||
if temp_fd >= 0:
|
||||
os.close(temp_fd)
|
||||
with suppress(OSError):
|
||||
temp_path.unlink(missing_ok=True)
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Qt Widgets user interface for the doctor workstation."""
|
||||
|
||||
from .login import LoginWindow
|
||||
from .shell import ShellWindow
|
||||
from .theme import apply_theme
|
||||
|
||||
__all__ = ["LoginWindow", "ShellWindow", "apply_theme"]
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,438 @@
|
||||
"""Focused editors and responsive layouts used by diagnosis detail views."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QDate, QRect, QSize, Qt, QTime
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QDateEdit,
|
||||
QDialog,
|
||||
QDoubleSpinBox,
|
||||
QFormLayout,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLayout,
|
||||
QLayoutItem,
|
||||
QLineEdit,
|
||||
QPlainTextEdit,
|
||||
QPushButton,
|
||||
QScrollArea,
|
||||
QSpinBox,
|
||||
QTimeEdit,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
|
||||
class FlowLayout(QLayout):
|
||||
"""A small Qt flow layout that wraps visible widgets at the available width."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent: QWidget | None = None,
|
||||
*,
|
||||
horizontal_spacing: int = 8,
|
||||
vertical_spacing: int = 8,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self._items: list[QLayoutItem] = []
|
||||
self._horizontal_spacing = horizontal_spacing
|
||||
self._vertical_spacing = vertical_spacing
|
||||
self._height_cache: dict[int, int] = {}
|
||||
self.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
def addItem(self, item: QLayoutItem) -> None: # noqa: N802 - Qt virtual
|
||||
self._height_cache.clear()
|
||||
self._items.append(item)
|
||||
|
||||
def count(self) -> int:
|
||||
return len(self._items)
|
||||
|
||||
def itemAt(self, index: int) -> QLayoutItem | None: # noqa: N802 - Qt virtual
|
||||
return self._items[index] if 0 <= index < len(self._items) else None
|
||||
|
||||
def takeAt(self, index: int) -> QLayoutItem | None: # noqa: N802 - Qt virtual
|
||||
self._height_cache.clear()
|
||||
return self._items.pop(index) if 0 <= index < len(self._items) else None
|
||||
|
||||
def expandingDirections(self) -> Qt.Orientations: # noqa: N802 - Qt virtual
|
||||
return Qt.Orientation(0)
|
||||
|
||||
def hasHeightForWidth(self) -> bool: # noqa: N802 - Qt virtual
|
||||
return True
|
||||
|
||||
def heightForWidth(self, width: int) -> int: # noqa: N802 - Qt virtual
|
||||
key = max(0, int(width))
|
||||
cached = self._height_cache.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
height = self._do_layout(QRect(0, 0, key, 0), test_only=True)
|
||||
self._height_cache[key] = height
|
||||
return height
|
||||
|
||||
def setGeometry(self, rect: QRect) -> None: # noqa: N802 - Qt virtual
|
||||
super().setGeometry(rect)
|
||||
self._do_layout(rect, test_only=False)
|
||||
|
||||
def invalidate(self) -> None: # noqa: N802 - Qt virtual
|
||||
self._height_cache.clear()
|
||||
super().invalidate()
|
||||
|
||||
def sizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
||||
return self.minimumSize()
|
||||
|
||||
def minimumSize(self) -> QSize: # noqa: N802 - Qt virtual
|
||||
size = QSize()
|
||||
for item in self._visible_items():
|
||||
size = size.expandedTo(item.minimumSize())
|
||||
margins = self.contentsMargins()
|
||||
size += QSize(margins.left() + margins.right(), margins.top() + margins.bottom())
|
||||
return size
|
||||
|
||||
def _visible_items(self) -> list[QLayoutItem]:
|
||||
return [
|
||||
item for item in self._items if item.widget() is None or not item.widget().isHidden()
|
||||
]
|
||||
|
||||
def _do_layout(self, rect: QRect, *, test_only: bool) -> int:
|
||||
margins = self.contentsMargins()
|
||||
effective = rect.adjusted(
|
||||
margins.left(), margins.top(), -margins.right(), -margins.bottom()
|
||||
)
|
||||
x = effective.x()
|
||||
y = effective.y()
|
||||
line_height = 0
|
||||
for item in self._visible_items():
|
||||
hint = item.sizeHint().expandedTo(item.minimumSize())
|
||||
next_x = x + hint.width()
|
||||
if line_height and next_x > effective.right() + 1:
|
||||
x = effective.x()
|
||||
y += line_height + self._vertical_spacing
|
||||
next_x = x + hint.width()
|
||||
line_height = 0
|
||||
if not test_only:
|
||||
item.setGeometry(QRect(x, y, hint.width(), hint.height()))
|
||||
x = next_x + self._horizontal_spacing
|
||||
line_height = max(line_height, hint.height())
|
||||
return y + line_height - rect.y() + margins.bottom()
|
||||
|
||||
|
||||
def _mapping(value: Any) -> dict[str, Any]:
|
||||
if isinstance(value, Mapping):
|
||||
return dict(value)
|
||||
with suppress(TypeError):
|
||||
return dict(vars(value))
|
||||
return {}
|
||||
|
||||
|
||||
def _value(source: Mapping[str, Any], *keys: str, default: Any = "") -> Any:
|
||||
for key in keys:
|
||||
value = source.get(key)
|
||||
if value not in (None, ""):
|
||||
return value
|
||||
return default
|
||||
|
||||
|
||||
class DailyRecordEditorDialog(QDialog):
|
||||
"""Create/edit the exact blood, diet, and exercise DTOs used by admin."""
|
||||
|
||||
_LABELS = {"blood": "血糖 / 血压", "diet": "饮食", "exercise": "运动"}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
kind: str,
|
||||
record: Any,
|
||||
*,
|
||||
parent: QWidget | None = None,
|
||||
) -> None:
|
||||
if kind not in self._LABELS:
|
||||
raise ValueError(f"unsupported daily record kind: {kind}")
|
||||
super().__init__(parent)
|
||||
self.kind = kind
|
||||
self.source = _mapping(record)
|
||||
self.record_id = _positive_int(self.source.get("id"))
|
||||
self.setObjectName("DiagnosisDailyEditor")
|
||||
self.setModal(True)
|
||||
self.setWindowTitle(f"{'编辑' if self.record_id else '新增'}{self._LABELS[kind]}记录")
|
||||
self.resize(650, 620 if kind == "blood" else 590)
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(0, 0, 0, 0)
|
||||
root.setSpacing(0)
|
||||
|
||||
header = QFrame()
|
||||
header.setObjectName("DiagnosisEditorHeader")
|
||||
header_layout = QVBoxLayout(header)
|
||||
header_layout.setContentsMargins(22, 18, 22, 16)
|
||||
header_layout.setSpacing(5)
|
||||
heading = QLabel(self.windowTitle())
|
||||
heading.setObjectName("DiagnosisDialogHeading")
|
||||
header_layout.addWidget(heading)
|
||||
guidance = QLabel("保存后将重新加载当前日期范围;带 * 的字段为必填项。")
|
||||
guidance.setObjectName("DiagnosisDialogGuidance")
|
||||
guidance.setWordWrap(True)
|
||||
header_layout.addWidget(guidance)
|
||||
root.addWidget(header)
|
||||
|
||||
scroll = QScrollArea()
|
||||
scroll.setObjectName("DiagnosisEditorScroll")
|
||||
scroll.setWidgetResizable(True)
|
||||
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
content = QWidget()
|
||||
content.setObjectName("DiagnosisEditorContent")
|
||||
self.form = QFormLayout(content)
|
||||
self.form.setContentsMargins(22, 20, 22, 22)
|
||||
self.form.setHorizontalSpacing(20)
|
||||
self.form.setVerticalSpacing(12)
|
||||
self.form.setLabelAlignment(
|
||||
Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter
|
||||
)
|
||||
self.form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
|
||||
scroll.setWidget(content)
|
||||
root.addWidget(scroll, 1)
|
||||
|
||||
footer = QFrame()
|
||||
footer.setObjectName("DiagnosisEditorFooter")
|
||||
footer_layout = QVBoxLayout(footer)
|
||||
footer_layout.setContentsMargins(22, 12, 22, 14)
|
||||
footer_layout.setSpacing(10)
|
||||
self.date_edit = QDateEdit()
|
||||
self.date_edit.setCalendarPopup(True)
|
||||
self.date_edit.setDisplayFormat("yyyy-MM-dd")
|
||||
self.date_edit.setMaximumDate(QDate.currentDate())
|
||||
date = QDate.fromString(str(self.source.get("record_date") or ""), "yyyy-MM-dd")
|
||||
self.date_edit.setDate(date if date.isValid() else QDate.currentDate())
|
||||
self._field(self.date_edit)
|
||||
self.form.addRow("记录日期 *", self.date_edit)
|
||||
|
||||
if kind == "blood":
|
||||
self._build_blood()
|
||||
elif kind == "diet":
|
||||
self._build_diet()
|
||||
else:
|
||||
self._build_exercise()
|
||||
|
||||
self.error_label = QLabel()
|
||||
self.error_label.setObjectName("DiagnosisEditorError")
|
||||
self.error_label.setWordWrap(True)
|
||||
self.error_label.hide()
|
||||
footer_layout.addWidget(self.error_label)
|
||||
actions = QHBoxLayout()
|
||||
actions.setContentsMargins(0, 0, 0, 0)
|
||||
actions.setSpacing(8)
|
||||
actions.addStretch(1)
|
||||
cancel = QPushButton("取消")
|
||||
cancel.setProperty("variant", "ghost")
|
||||
cancel.clicked.connect(self.reject)
|
||||
actions.addWidget(cancel)
|
||||
save = QPushButton("保存记录")
|
||||
save.setObjectName("DiagnosisDailyEditorSave")
|
||||
save.setProperty("variant", "primary")
|
||||
save.setDefault(True)
|
||||
save.clicked.connect(self.accept)
|
||||
actions.addWidget(save)
|
||||
footer_layout.addLayout(actions)
|
||||
root.addWidget(footer)
|
||||
|
||||
@staticmethod
|
||||
def _field(widget: QWidget) -> QWidget:
|
||||
widget.setProperty("diagnosisField", True)
|
||||
return widget
|
||||
|
||||
def _double(self, *keys: str, maximum: float = 50.0) -> QDoubleSpinBox:
|
||||
editor = QDoubleSpinBox()
|
||||
editor.setRange(0.0, maximum)
|
||||
editor.setDecimals(2)
|
||||
editor.setSingleStep(0.1)
|
||||
editor.setSpecialValueText("未填写")
|
||||
with suppress(TypeError, ValueError):
|
||||
editor.setValue(float(_value(self.source, *keys, default=0) or 0))
|
||||
self._field(editor)
|
||||
return editor
|
||||
|
||||
def _integer(self, *keys: str, maximum: int) -> QSpinBox:
|
||||
editor = QSpinBox()
|
||||
editor.setRange(0, maximum)
|
||||
editor.setSpecialValueText("未填写")
|
||||
editor.setValue(_positive_int(_value(self.source, *keys, default=0), allow_zero=True))
|
||||
self._field(editor)
|
||||
return editor
|
||||
|
||||
def _line(self, *keys: str) -> QLineEdit:
|
||||
editor = QLineEdit(str(_value(self.source, *keys, default="") or ""))
|
||||
editor.setMaxLength(500)
|
||||
self._field(editor)
|
||||
return editor
|
||||
|
||||
def _plain(self, *keys: str, height: int = 72) -> QPlainTextEdit:
|
||||
editor = QPlainTextEdit(str(_value(self.source, *keys, default="") or ""))
|
||||
editor.setMaximumHeight(height)
|
||||
self._field(editor)
|
||||
return editor
|
||||
|
||||
def _build_blood(self) -> None:
|
||||
self.time_edit = QTimeEdit()
|
||||
self.time_edit.setDisplayFormat("HH:mm")
|
||||
parsed = QTime.fromString(str(self.source.get("record_time") or ""), "HH:mm")
|
||||
self.time_edit.setTime(parsed if parsed.isValid() else QTime.currentTime())
|
||||
self._field(self.time_edit)
|
||||
self.form.addRow("记录时间", self.time_edit)
|
||||
self.fasting = self._double("fasting_blood_sugar", "fasting_glucose")
|
||||
self.postprandial = self._double("postprandial_blood_sugar", "postprandial_glucose")
|
||||
self.other = self._double("other_blood_sugar", "other_glucose")
|
||||
self.systolic = self._integer("systolic_pressure", "systolic", maximum=300)
|
||||
self.diastolic = self._integer("diastolic_pressure", "diastolic", maximum=200)
|
||||
self.western = self._line("western_medicine")
|
||||
self.insulin = self._line("insulin")
|
||||
self.remark = self._plain("remark", height=82)
|
||||
self.form.addRow("空腹血糖(mmol/L)", self.fasting)
|
||||
self.form.addRow("餐后 2 小时血糖(mmol/L)", self.postprandial)
|
||||
self.form.addRow("其他血糖(mmol/L)", self.other)
|
||||
self.form.addRow("收缩压(mmHg)", self.systolic)
|
||||
self.form.addRow("舒张压(mmHg)", self.diastolic)
|
||||
self.form.addRow("西药", self.western)
|
||||
self.form.addRow("胰岛素", self.insulin)
|
||||
self.form.addRow("备注", self.remark)
|
||||
|
||||
def _build_diet(self) -> None:
|
||||
self.breakfast = self._plain("breakfast_foods", "breakfast")
|
||||
self.lunch = self._plain("lunch_foods", "lunch")
|
||||
self.dinner = self._plain("dinner_foods", "dinner")
|
||||
self.note = self._plain("note", height=82)
|
||||
self.form.addRow("早餐", self.breakfast)
|
||||
self.form.addRow("午餐", self.lunch)
|
||||
self.form.addRow("晚餐", self.dinner)
|
||||
self.form.addRow("备注", self.note)
|
||||
preserved = QLabel("已有餐食图片会原样保留;图片增删仍由服务端素材入口处理。")
|
||||
preserved.setObjectName("DiagnosisDialogGuidance")
|
||||
preserved.setWordWrap(True)
|
||||
self.form.addRow("图片", preserved)
|
||||
|
||||
def _build_exercise(self) -> None:
|
||||
self.exercise_type = QComboBox()
|
||||
self.exercise_type.addItem("请选择运动类型", "")
|
||||
for value in ("散步", "慢跑", "游泳", "瑜伽", "骑自行车", "打太极拳", "其他"):
|
||||
self.exercise_type.addItem(value, value)
|
||||
current_type = str(self.source.get("exercise_type") or "")
|
||||
if current_type and self.exercise_type.findData(current_type) < 0:
|
||||
self.exercise_type.addItem(current_type, current_type)
|
||||
if current_type:
|
||||
self.exercise_type.setCurrentIndex(self.exercise_type.findData(current_type))
|
||||
self._field(self.exercise_type)
|
||||
self.duration = self._integer("duration", maximum=300)
|
||||
self.intensity = QComboBox()
|
||||
for label, value in (("低强度", 1), ("中强度", 2), ("高强度", 3)):
|
||||
self.intensity.addItem(label, value)
|
||||
requested = _positive_int(self.source.get("intensity"), allow_zero=True) or 1
|
||||
self.intensity.setCurrentIndex(max(0, self.intensity.findData(requested)))
|
||||
self._field(self.intensity)
|
||||
self.note = self._plain("note", height=90)
|
||||
self.form.addRow("运动类型 *", self.exercise_type)
|
||||
self.form.addRow("运动时长(分钟)*", self.duration)
|
||||
self.form.addRow("运动强度 *", self.intensity)
|
||||
self.form.addRow("备注", self.note)
|
||||
preserved = QLabel("已有运动图片会原样保留。")
|
||||
preserved.setObjectName("DiagnosisDialogGuidance")
|
||||
self.form.addRow("图片", preserved)
|
||||
|
||||
def payload(self) -> dict[str, Any]:
|
||||
payload = dict(self.source)
|
||||
payload["record_date"] = self.date_edit.date().toString("yyyy-MM-dd")
|
||||
if self.kind == "blood":
|
||||
payload.update(
|
||||
{
|
||||
"record_time": self.time_edit.time().toString("HH:mm"),
|
||||
"fasting_blood_sugar": self.fasting.value(),
|
||||
"postprandial_blood_sugar": self.postprandial.value(),
|
||||
"other_blood_sugar": self.other.value(),
|
||||
"systolic_pressure": self.systolic.value(),
|
||||
"diastolic_pressure": self.diastolic.value(),
|
||||
"western_medicine": self.western.text().strip(),
|
||||
"insulin": self.insulin.text().strip(),
|
||||
"remark": self.remark.toPlainText().strip(),
|
||||
}
|
||||
)
|
||||
elif self.kind == "diet":
|
||||
payload.update(
|
||||
{
|
||||
"breakfast_foods": self.breakfast.toPlainText().strip(),
|
||||
"lunch_foods": self.lunch.toPlainText().strip(),
|
||||
"dinner_foods": self.dinner.toPlainText().strip(),
|
||||
"note": self.note.toPlainText().strip(),
|
||||
"breakfast_images": payload.get("breakfast_images") or [],
|
||||
"lunch_images": payload.get("lunch_images") or [],
|
||||
"dinner_images": payload.get("dinner_images") or [],
|
||||
}
|
||||
)
|
||||
else:
|
||||
payload.update(
|
||||
{
|
||||
"exercise_type": str(self.exercise_type.currentData() or "").strip(),
|
||||
"duration": self.duration.value(),
|
||||
"intensity": int(self.intensity.currentData() or 1),
|
||||
"images": payload.get("images") or [],
|
||||
"note": self.note.toPlainText().strip(),
|
||||
}
|
||||
)
|
||||
return payload
|
||||
|
||||
def validation_error(self) -> str:
|
||||
if not self.date_edit.date().isValid():
|
||||
return "请选择记录日期。"
|
||||
if self.date_edit.date() > QDate.currentDate():
|
||||
return "记录日期不能晚于今天。"
|
||||
payload = self.payload()
|
||||
if self.kind == "blood":
|
||||
measurements = (
|
||||
payload["fasting_blood_sugar"],
|
||||
payload["postprandial_blood_sugar"],
|
||||
payload["other_blood_sugar"],
|
||||
payload["systolic_pressure"],
|
||||
payload["diastolic_pressure"],
|
||||
)
|
||||
if not any(float(value or 0) > 0 for value in measurements) and not any(
|
||||
payload[key] for key in ("western_medicine", "insulin", "remark")
|
||||
):
|
||||
return "请至少填写一项血糖、血压、用药或备注。"
|
||||
elif self.kind == "diet":
|
||||
if not any(
|
||||
payload[key]
|
||||
for key in (
|
||||
"breakfast_foods",
|
||||
"lunch_foods",
|
||||
"dinner_foods",
|
||||
"breakfast_images",
|
||||
"lunch_images",
|
||||
"dinner_images",
|
||||
"note",
|
||||
)
|
||||
):
|
||||
return "请至少填写一餐、图片或备注。"
|
||||
elif not payload["exercise_type"] or int(payload["duration"] or 0) <= 0:
|
||||
return "请选择运动类型并填写大于 0 的运动时长。"
|
||||
return ""
|
||||
|
||||
def accept(self) -> None:
|
||||
error = self.validation_error()
|
||||
if error:
|
||||
self.error_label.setText(error)
|
||||
self.error_label.show()
|
||||
return
|
||||
self.error_label.hide()
|
||||
super().accept()
|
||||
|
||||
|
||||
def _positive_int(value: Any, *, allow_zero: bool = False) -> int:
|
||||
try:
|
||||
parsed = int(value or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
return parsed if parsed > 0 or (allow_zero and parsed == 0) else 0
|
||||
|
||||
|
||||
__all__ = ["DailyRecordEditorDialog", "FlowLayout"]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,675 @@
|
||||
"""Safe in-application replay players for diagnosis call recordings.
|
||||
|
||||
The web diagnosis page keeps the preferred recording in the table and lists
|
||||
the remaining sources underneath it. This module mirrors that contract with
|
||||
QtMultimedia while retaining the older standalone dialog as a codec fallback.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import weakref
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import Qt, QUrl, Signal
|
||||
from PySide6.QtGui import QCloseEvent, QDesktopServices
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QPushButton,
|
||||
QSizePolicy,
|
||||
QSlider,
|
||||
QStackedLayout,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
try:
|
||||
from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer
|
||||
from PySide6.QtMultimediaWidgets import QVideoWidget
|
||||
|
||||
MULTIMEDIA_AVAILABLE = True
|
||||
except ImportError: # pragma: no cover - exercised only by minimal PySide builds
|
||||
QAudioOutput = QMediaPlayer = QVideoWidget = None # type: ignore[assignment,misc]
|
||||
MULTIMEDIA_AVAILABLE = False
|
||||
|
||||
|
||||
def safe_http_url(target: str) -> QUrl | None:
|
||||
url = QUrl(str(target).strip())
|
||||
if not url.isValid() or url.scheme().lower() not in {"http", "https"}:
|
||||
return None
|
||||
if not url.host():
|
||||
return None
|
||||
return url
|
||||
|
||||
|
||||
def normalize_recording_urls(urls: Sequence[Any] | Any) -> list[str]:
|
||||
"""Trim and de-duplicate backend recording URLs without inventing values."""
|
||||
|
||||
if isinstance(urls, (str, bytes, bytearray)) or not isinstance(urls, Sequence):
|
||||
candidates: Sequence[Any] = [urls]
|
||||
else:
|
||||
candidates = urls
|
||||
normalized: list[str] = []
|
||||
for candidate in candidates:
|
||||
value = str(candidate or "").strip()
|
||||
if value and value not in normalized:
|
||||
normalized.append(value)
|
||||
return normalized
|
||||
|
||||
|
||||
_INLINE_RECORDING_PATTERN = re.compile(
|
||||
r"\.(?:mp4|webm|ogg|mov|mkv|m4v|m3u8)(?:\?|#|$)", re.IGNORECASE
|
||||
)
|
||||
|
||||
|
||||
def should_inline_recording(target: str) -> bool:
|
||||
"""Return whether a safe remote source is suitable for native inline replay."""
|
||||
|
||||
return safe_http_url(target) is not None and bool(
|
||||
_INLINE_RECORDING_PATTERN.search(str(target).strip())
|
||||
)
|
||||
|
||||
|
||||
def preferred_recording_url(urls: Sequence[Any] | Any) -> str | None:
|
||||
"""Choose the same preferred source order as the diagnosis web client."""
|
||||
|
||||
normalized = [url for url in normalize_recording_urls(urls) if safe_http_url(url)]
|
||||
if not normalized:
|
||||
return None
|
||||
priorities = (
|
||||
lambda url: bool(re.search(r"\.mp4(?:\?|#|$)", url, re.IGNORECASE)),
|
||||
lambda url: bool(
|
||||
re.search(r"\.m3u8(?:\?|#|$)", url, re.IGNORECASE)
|
||||
and re.search(r"vod-qcloud\.com", url, re.IGNORECASE)
|
||||
),
|
||||
lambda url: bool(
|
||||
re.search(r"\.m3u8(?:\?|#|$)", url, re.IGNORECASE)
|
||||
and re.search(r"\.cos\.[^/]+\.myqcloud\.com", url, re.IGNORECASE)
|
||||
),
|
||||
lambda url: bool(re.search(r"\.m3u8(?:\?|#|$)", url, re.IGNORECASE)),
|
||||
)
|
||||
for matches in priorities:
|
||||
preferred = next((url for url in normalized if matches(url)), None)
|
||||
if preferred:
|
||||
return preferred
|
||||
return normalized[0]
|
||||
|
||||
|
||||
def alternate_recording_label(target: str, index: int) -> str:
|
||||
"""Return the source label used by the web playback block."""
|
||||
|
||||
value = str(target or "").strip()
|
||||
ordinal = index + 1
|
||||
if re.search(r"\.mp4(?:\?|#|$)", value, re.IGNORECASE):
|
||||
return f"MP4 {ordinal}"
|
||||
if re.search(r"vod-qcloud\.com", value, re.IGNORECASE) and re.search(
|
||||
r"\.m3u8", value, re.IGNORECASE
|
||||
):
|
||||
return f"点播 {ordinal}"
|
||||
if re.search(r"\.cos\.[^/]+\.myqcloud\.com", value, re.IGNORECASE) and re.search(
|
||||
r"\.m3u8", value, re.IGNORECASE
|
||||
):
|
||||
return f"COS HLS {ordinal}"
|
||||
if re.search(r"\.m3u8", value, re.IGNORECASE):
|
||||
return f"HLS {ordinal}"
|
||||
return f"链接 {ordinal}"
|
||||
|
||||
|
||||
def open_safe_http_url(target: str) -> bool:
|
||||
"""Open only an absolute HTTP(S) target with the operating system."""
|
||||
|
||||
url = safe_http_url(target)
|
||||
return bool(url is not None and QDesktopServices.openUrl(url))
|
||||
|
||||
|
||||
_INLINE_PLAYER_QSS = """
|
||||
QWidget#DiagnosisInlineRecordingPlayer {
|
||||
background: #FFFFFF;
|
||||
border: 1px solid #E6EAF5;
|
||||
border-radius: 9px;
|
||||
}
|
||||
QFrame#DiagnosisInlineRecordingSurface {
|
||||
background: #11182E;
|
||||
border: 0;
|
||||
border-radius: 8px 8px 0 0;
|
||||
}
|
||||
QLabel#DiagnosisInlineRecordingPlaceholder {
|
||||
color: #C7D0E8;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
QLabel#DiagnosisInlineRecordingTime {
|
||||
color: #64739A;
|
||||
font-size: 11px;
|
||||
}
|
||||
QPushButton[recordingControl="true"] {
|
||||
min-height: 24px;
|
||||
max-height: 24px;
|
||||
padding: 0 8px;
|
||||
color: #3F4E75;
|
||||
background: #FAFBFE;
|
||||
border: 1px solid #D8DEEE;
|
||||
border-radius: 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QPushButton[recordingControl="true"]:hover,
|
||||
QPushButton[recordingControl="true"]:focus {
|
||||
color: #4451E2;
|
||||
background: #F0F2FF;
|
||||
border-color: #8D9BFF;
|
||||
}
|
||||
QPushButton#DiagnosisInlineRecordingPlay {
|
||||
color: #FFFFFF;
|
||||
background: #5761F4;
|
||||
border-color: #5761F4;
|
||||
}
|
||||
QPushButton#DiagnosisInlineRecordingPlay:hover,
|
||||
QPushButton#DiagnosisInlineRecordingPlay:focus {
|
||||
color: #FFFFFF;
|
||||
background: #4C57E9;
|
||||
border-color: #4C57E9;
|
||||
}
|
||||
QPushButton[recordingControl="true"]:disabled {
|
||||
color: #A4ADC3;
|
||||
background: #F0F2F8;
|
||||
border-color: #E6EAF5;
|
||||
}
|
||||
QSlider::groove:horizontal { height: 3px; background: #D8DEEE; border-radius: 1px; }
|
||||
QSlider::sub-page:horizontal { background: #5761F4; border-radius: 1px; }
|
||||
QSlider::handle:horizontal {
|
||||
width: 10px;
|
||||
margin: -4px 0;
|
||||
background: #FFFFFF;
|
||||
border: 1px solid #5761F4;
|
||||
border-radius: 5px;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class InlineRecordingPlayer(QWidget):
|
||||
"""A lazy, owner-safe QtMultimedia player capped at 180 px."""
|
||||
|
||||
fallback_requested = Signal(str)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
target: str,
|
||||
*,
|
||||
render_owner: object | None = None,
|
||||
owner_generation: int | None = None,
|
||||
parent: QWidget | None = None,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self.target = str(target).strip()
|
||||
self.url = safe_http_url(self.target)
|
||||
self._owner_ref = weakref.ref(render_owner) if render_owner is not None else None
|
||||
self._owner_generation = owner_generation
|
||||
self._source_attached = False
|
||||
self.player = None
|
||||
self.audio_output = None
|
||||
self.setObjectName("DiagnosisInlineRecordingPlayer")
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
|
||||
self.setProperty("maximumPlaybackHeight", 180)
|
||||
self.setMinimumHeight(158)
|
||||
self.setMaximumHeight(180)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
self.setStyleSheet(_INLINE_PLAYER_QSS)
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(1, 1, 1, 5)
|
||||
root.setSpacing(4)
|
||||
surface = QFrame()
|
||||
surface.setObjectName("DiagnosisInlineRecordingSurface")
|
||||
surface.setMinimumHeight(122)
|
||||
surface.setMaximumHeight(142)
|
||||
self._surface_stack = QStackedLayout(surface)
|
||||
self._surface_stack.setContentsMargins(0, 0, 0, 0)
|
||||
self._surface_stack.setStackingMode(QStackedLayout.StackingMode.StackOne)
|
||||
|
||||
# A diagnosis can contain dozens of call records and is rendered in two
|
||||
# tables. Creating a native player for every row exhausts the Windows
|
||||
# multimedia backend and can terminate the process with 0xC0000005.
|
||||
# Keep the backend genuinely lazy and create one only on first playback.
|
||||
self.video = None
|
||||
|
||||
self.placeholder = QLabel(
|
||||
"预览待加载\n点击播放开始加载"
|
||||
if MULTIMEDIA_AVAILABLE
|
||||
else "当前环境未包含 QtMultimedia\n可安全外部打开"
|
||||
)
|
||||
self.placeholder.setObjectName("DiagnosisInlineRecordingPlaceholder")
|
||||
self.placeholder.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.placeholder.setWordWrap(True)
|
||||
self._surface_stack.addWidget(self.placeholder)
|
||||
self._surface_stack.setCurrentWidget(self.placeholder)
|
||||
root.addWidget(surface, 1)
|
||||
|
||||
controls = QHBoxLayout()
|
||||
controls.setContentsMargins(5, 0, 5, 0)
|
||||
controls.setSpacing(5)
|
||||
self.play_button = QPushButton("播放")
|
||||
self.play_button.setObjectName("DiagnosisInlineRecordingPlay")
|
||||
self.play_button.setProperty("recordingControl", True)
|
||||
self.play_button.clicked.connect(self._toggle_playback)
|
||||
controls.addWidget(self.play_button)
|
||||
self.position = QSlider(Qt.Orientation.Horizontal)
|
||||
self.position.setObjectName("DiagnosisInlineRecordingPosition")
|
||||
self.position.setRange(0, 0)
|
||||
self.position.sliderMoved.connect(self._seek)
|
||||
controls.addWidget(self.position, 1)
|
||||
self.time_label = QLabel("00:00 / 00:00")
|
||||
self.time_label.setObjectName("DiagnosisInlineRecordingTime")
|
||||
controls.addWidget(self.time_label)
|
||||
external = QPushButton("外部打开")
|
||||
external.setObjectName("DiagnosisInlineRecordingExternal")
|
||||
external.setProperty("recordingControl", True)
|
||||
external.setToolTip("使用系统默认程序安全打开此 HTTP(S) 回放地址")
|
||||
external.clicked.connect(self._open_external)
|
||||
controls.addWidget(external)
|
||||
fallback = QPushButton("独立窗口")
|
||||
fallback.setObjectName("DiagnosisInlineRecordingFallback")
|
||||
fallback.setProperty("recordingControl", True)
|
||||
fallback.setToolTip("系统解码器兼容性不佳时在独立播放器中重试")
|
||||
fallback.clicked.connect(lambda: self.fallback_requested.emit(self.target))
|
||||
controls.addWidget(fallback)
|
||||
root.addLayout(controls)
|
||||
|
||||
valid = self.url is not None
|
||||
self.play_button.setEnabled(valid and MULTIMEDIA_AVAILABLE)
|
||||
external.setEnabled(valid)
|
||||
fallback.setEnabled(valid)
|
||||
if not valid:
|
||||
self.placeholder.setText("回放地址无效\n仅允许包含主机名的 HTTP(S) 地址")
|
||||
|
||||
def _owner_is_current(self) -> bool:
|
||||
if self._owner_ref is None or self._owner_generation is None:
|
||||
return True
|
||||
owner = self._owner_ref()
|
||||
if owner is None:
|
||||
return False
|
||||
generations = getattr(owner, "_tab_generations", None)
|
||||
if isinstance(generations, dict) and "video" in generations:
|
||||
return generations["video"] == self._owner_generation
|
||||
current = getattr(owner, "_media_generation", self._owner_generation)
|
||||
return current == self._owner_generation
|
||||
|
||||
def _ensure_player(self) -> bool:
|
||||
"""Create the native multimedia objects on first playback only."""
|
||||
|
||||
if self.player is not None:
|
||||
return True
|
||||
if (
|
||||
not MULTIMEDIA_AVAILABLE
|
||||
or QMediaPlayer is None
|
||||
or QAudioOutput is None
|
||||
or QVideoWidget is None
|
||||
):
|
||||
return False
|
||||
try:
|
||||
video = QVideoWidget()
|
||||
video.setObjectName("DiagnosisInlineRecordingVideo")
|
||||
audio_output = QAudioOutput(self)
|
||||
player = QMediaPlayer(self)
|
||||
player.setAudioOutput(audio_output)
|
||||
player.setVideoOutput(video)
|
||||
player.positionChanged.connect(self._position_changed)
|
||||
player.durationChanged.connect(self._duration_changed)
|
||||
player.playbackStateChanged.connect(self._state_changed)
|
||||
player.errorOccurred.connect(self._player_error)
|
||||
self.video = video
|
||||
self.audio_output = audio_output
|
||||
self.player = player
|
||||
self._surface_stack.addWidget(video)
|
||||
except (RuntimeError, TypeError):
|
||||
self.video = None
|
||||
self.audio_output = None
|
||||
self.player = None
|
||||
self.placeholder.setText(
|
||||
"系统媒体组件初始化失败\n可安全外部打开或使用独立窗口"
|
||||
)
|
||||
self._surface_stack.setCurrentWidget(self.placeholder)
|
||||
self.play_button.setEnabled(False)
|
||||
return False
|
||||
return True
|
||||
|
||||
def _attach_source(self) -> bool:
|
||||
if self.url is None:
|
||||
return False
|
||||
if not self._owner_is_current():
|
||||
self.play_button.setEnabled(False)
|
||||
self.placeholder.setText("该回放列表已刷新\n请在最新记录中播放")
|
||||
self._surface_stack.setCurrentWidget(self.placeholder)
|
||||
return False
|
||||
if not self._ensure_player() or self.player is None:
|
||||
return False
|
||||
if not self._source_attached:
|
||||
self.player.setSource(self.url)
|
||||
self._source_attached = True
|
||||
self.placeholder.setText("正在加载回放…")
|
||||
return True
|
||||
|
||||
def _toggle_playback(self) -> None:
|
||||
if not self._attach_source() or self.player is None:
|
||||
return
|
||||
if self.player.playbackState() == QMediaPlayer.PlaybackState.PlayingState:
|
||||
self.player.pause()
|
||||
else:
|
||||
self.player.play()
|
||||
|
||||
def _state_changed(self, state: object) -> None:
|
||||
if self.player is None:
|
||||
return
|
||||
playing = state == QMediaPlayer.PlaybackState.PlayingState
|
||||
self.play_button.setText("暂停" if playing else "播放")
|
||||
if playing and self.video is not None:
|
||||
self._surface_stack.setCurrentWidget(self.video)
|
||||
|
||||
def _player_error(self, _error: object, message: str = "") -> None:
|
||||
detail = message.strip() if message else "系统媒体后端无法播放该格式"
|
||||
self.placeholder.setText(f"{detail}\n可安全外部打开或使用独立窗口")
|
||||
self._surface_stack.setCurrentWidget(self.placeholder)
|
||||
|
||||
def _duration_changed(self, duration: int) -> None:
|
||||
self.position.setRange(0, max(0, duration))
|
||||
current = self.player.position() if self.player is not None else 0
|
||||
self.time_label.setText(f"{_clock(current)} / {_clock(duration)}")
|
||||
|
||||
def _position_changed(self, position: int) -> None:
|
||||
if not self.position.isSliderDown():
|
||||
self.position.setValue(position)
|
||||
duration = self.player.duration() if self.player is not None else 0
|
||||
self.time_label.setText(f"{_clock(position)} / {_clock(duration)}")
|
||||
|
||||
def _seek(self, position: int) -> None:
|
||||
if self.player is not None and self._owner_is_current():
|
||||
self.player.setPosition(position)
|
||||
|
||||
def _open_external(self) -> None:
|
||||
if not open_safe_http_url(self.target):
|
||||
self.placeholder.setText("系统未能打开该安全外部链接")
|
||||
self._surface_stack.setCurrentWidget(self.placeholder)
|
||||
|
||||
def stop(self) -> None:
|
||||
if self.player is not None:
|
||||
self.player.stop()
|
||||
|
||||
def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 - Qt virtual
|
||||
self.stop()
|
||||
super().closeEvent(event)
|
||||
|
||||
|
||||
class RecordingPlaybackCell(QWidget):
|
||||
"""One call-record playback cell: preferred inline, alternates underneath."""
|
||||
|
||||
fallback_requested = Signal(str)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
urls: Sequence[Any] | Any,
|
||||
*,
|
||||
record_id: int,
|
||||
render_owner: object | None = None,
|
||||
owner_generation: int | None = None,
|
||||
parent: QWidget | None = None,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("DiagnosisRecordingPlaybackCell")
|
||||
self.setProperty("callRecordId", record_id)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
self.urls = normalize_recording_urls(urls)
|
||||
self.preferred = preferred_recording_url(self.urls)
|
||||
self.inline_player: InlineRecordingPlayer | None = None
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(5, 5, 5, 5)
|
||||
layout.setSpacing(6)
|
||||
if self.preferred and should_inline_recording(self.preferred):
|
||||
self.inline_player = InlineRecordingPlayer(
|
||||
self.preferred,
|
||||
render_owner=render_owner,
|
||||
owner_generation=owner_generation,
|
||||
parent=self,
|
||||
)
|
||||
self.inline_player.fallback_requested.connect(self.fallback_requested.emit)
|
||||
layout.addWidget(self.inline_player)
|
||||
elif self.preferred:
|
||||
primary = QPushButton("安全打开回放")
|
||||
primary.setObjectName("DiagnosisRecordingPrimaryLink")
|
||||
primary.setProperty("variant", "link")
|
||||
primary.setToolTip(self.preferred)
|
||||
primary.clicked.connect(
|
||||
lambda _checked=False, target=self.preferred: self._open_external(target)
|
||||
)
|
||||
layout.addWidget(primary, 0, Qt.AlignmentFlag.AlignLeft)
|
||||
elif self.urls:
|
||||
invalid = QLabel("回放地址无效(仅支持 HTTP(S))")
|
||||
invalid.setObjectName("DiagnosisUnsupportedState")
|
||||
invalid.setWordWrap(True)
|
||||
layout.addWidget(invalid)
|
||||
else:
|
||||
empty = QLabel("暂无录制回放")
|
||||
empty.setObjectName("DiagnosisEmptyState")
|
||||
layout.addWidget(empty)
|
||||
|
||||
alternates = [url for url in self.urls if url != self.preferred]
|
||||
if alternates:
|
||||
separator = QFrame()
|
||||
separator.setObjectName("DiagnosisRecordingAlternateSeparator")
|
||||
separator.setFrameShape(QFrame.Shape.HLine)
|
||||
separator.setStyleSheet("color:#E6EAF5;")
|
||||
layout.addWidget(separator)
|
||||
label = QLabel("备用地址")
|
||||
label.setObjectName("DiagnosisRecordingAlternateLabel")
|
||||
label.setStyleSheet("color:#7886AA; font-size:12px;")
|
||||
layout.addWidget(label)
|
||||
links = QHBoxLayout()
|
||||
links.setContentsMargins(0, 0, 0, 0)
|
||||
links.setSpacing(10)
|
||||
for index, target in enumerate(alternates):
|
||||
button = QPushButton(alternate_recording_label(target, index))
|
||||
button.setObjectName("DiagnosisRecordingAlternateLink")
|
||||
button.setProperty("variant", "link")
|
||||
button.setProperty("recordingUrl", target)
|
||||
button.setToolTip(target)
|
||||
button.setEnabled(safe_http_url(target) is not None)
|
||||
button.clicked.connect(
|
||||
lambda _checked=False, selected=target: self._open_external(selected)
|
||||
)
|
||||
links.addWidget(button)
|
||||
links.addStretch(1)
|
||||
layout.addLayout(links)
|
||||
self.link_status = QLabel("")
|
||||
self.link_status.setObjectName("DiagnosisRecordingLinkStatus")
|
||||
self.link_status.setStyleSheet("color:#D94856; font-size:11px;")
|
||||
self.link_status.setWordWrap(True)
|
||||
self.link_status.hide()
|
||||
layout.addWidget(self.link_status)
|
||||
|
||||
def required_table_row_height(self) -> int:
|
||||
"""Return the real height a table row needs to avoid clipping this cell."""
|
||||
|
||||
cell_layout = self.layout()
|
||||
if cell_layout is not None:
|
||||
cell_layout.activate()
|
||||
# The diagnosis table style gives every item 7 px of vertical padding,
|
||||
# and QTableWidget also reserves a grid line. Cell-widget geometry is
|
||||
# inset by those pixels, so the section must include that allowance in
|
||||
# addition to the player's own layout hint.
|
||||
content_height = max(self.sizeHint().height(), self.minimumSizeHint().height())
|
||||
return content_height + 16
|
||||
|
||||
def _open_external(self, target: str) -> None:
|
||||
if open_safe_http_url(target):
|
||||
self.link_status.hide()
|
||||
return
|
||||
self.link_status.setText("系统未能打开该安全外部链接。")
|
||||
self.link_status.show()
|
||||
|
||||
def stop(self) -> None:
|
||||
if self.inline_player is not None:
|
||||
self.inline_player.stop()
|
||||
|
||||
def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 - Qt virtual
|
||||
self.stop()
|
||||
super().closeEvent(event)
|
||||
|
||||
|
||||
class RecordingPlayerDialog(QDialog):
|
||||
"""Native, cross-platform replay window with a safe browser fallback."""
|
||||
|
||||
def __init__(self, target: str, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.target = str(target).strip()
|
||||
self.url = safe_http_url(self.target)
|
||||
self.setObjectName("DiagnosisRecordingPlayer")
|
||||
self.setWindowTitle("视频回放")
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
|
||||
self.resize(820, 560)
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(18, 16, 18, 16)
|
||||
root.setSpacing(12)
|
||||
heading = QLabel("视频回放")
|
||||
heading.setObjectName("DiagnosisDialogHeading")
|
||||
root.addWidget(heading)
|
||||
self.status = QLabel("点击播放,在工作站内查看服务端回放。")
|
||||
self.status.setObjectName("DiagnosisDialogGuidance")
|
||||
self.status.setWordWrap(True)
|
||||
root.addWidget(self.status)
|
||||
|
||||
self.player = None
|
||||
self.audio_output = None
|
||||
if MULTIMEDIA_AVAILABLE:
|
||||
surface = QFrame()
|
||||
surface.setObjectName("DiagnosisRecordingSurface")
|
||||
surface.setMinimumHeight(360)
|
||||
surface_stack = QStackedLayout(surface)
|
||||
surface_stack.setContentsMargins(1, 1, 1, 1)
|
||||
surface_stack.setStackingMode(QStackedLayout.StackingMode.StackOne)
|
||||
self.video = QVideoWidget()
|
||||
surface_stack.addWidget(self.video)
|
||||
self.placeholder = QLabel("应用内播放器已就绪\n点击下方“播放”开始查看")
|
||||
self.placeholder.setObjectName("DiagnosisRecordingPlaceholder")
|
||||
self.placeholder.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
surface_stack.addWidget(self.placeholder)
|
||||
surface_stack.setCurrentWidget(self.placeholder)
|
||||
self._surface_stack = surface_stack
|
||||
root.addWidget(surface, 1)
|
||||
self.audio_output = QAudioOutput(self)
|
||||
self.player = QMediaPlayer(self)
|
||||
self.player.setAudioOutput(self.audio_output)
|
||||
self.player.setVideoOutput(self.video)
|
||||
self.player.positionChanged.connect(self._position_changed)
|
||||
self.player.durationChanged.connect(self._duration_changed)
|
||||
self.player.playbackStateChanged.connect(self._state_changed)
|
||||
self.player.errorOccurred.connect(self._player_error)
|
||||
if self.url is not None:
|
||||
self.player.setSource(self.url)
|
||||
else:
|
||||
unavailable = QLabel("当前 PySide6 构建未包含 QtMultimedia,仍可安全外部打开。")
|
||||
unavailable.setObjectName("DiagnosisUnsupportedState")
|
||||
unavailable.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
unavailable.setMinimumHeight(320)
|
||||
root.addWidget(unavailable, 1)
|
||||
|
||||
controls = QHBoxLayout()
|
||||
self.play_button = QPushButton("播放")
|
||||
self.play_button.setProperty("variant", "primary")
|
||||
self.play_button.clicked.connect(self._toggle_playback)
|
||||
controls.addWidget(self.play_button)
|
||||
self.position = QSlider(Qt.Orientation.Horizontal)
|
||||
self.position.setRange(0, 0)
|
||||
self.position.sliderMoved.connect(self._seek)
|
||||
controls.addWidget(self.position, 1)
|
||||
self.time_label = QLabel("00:00 / 00:00")
|
||||
self.time_label.setObjectName("DiagnosisRecordingTime")
|
||||
controls.addWidget(self.time_label)
|
||||
external = QPushButton("安全外部打开")
|
||||
external.setProperty("variant", "ghost")
|
||||
external.clicked.connect(self._open_external)
|
||||
controls.addWidget(external)
|
||||
close = QPushButton("关闭")
|
||||
close.setProperty("variant", "secondary")
|
||||
close.clicked.connect(self.close)
|
||||
controls.addWidget(close)
|
||||
root.addLayout(controls)
|
||||
|
||||
valid = self.url is not None
|
||||
self.play_button.setEnabled(valid and self.player is not None)
|
||||
external.setEnabled(valid)
|
||||
if not valid:
|
||||
self.status.setText("回放地址无效:仅允许包含主机名的 HTTP(S) 地址。")
|
||||
self.status.setProperty("kind", "danger")
|
||||
|
||||
def _toggle_playback(self) -> None:
|
||||
if self.player is None or self.url is None:
|
||||
return
|
||||
if self.player.playbackState() == QMediaPlayer.PlaybackState.PlayingState:
|
||||
self.player.pause()
|
||||
else:
|
||||
self.player.play()
|
||||
|
||||
def _state_changed(self, state: object) -> None:
|
||||
if self.player is None:
|
||||
return
|
||||
playing = state == QMediaPlayer.PlaybackState.PlayingState
|
||||
self.play_button.setText("暂停" if playing else "播放")
|
||||
if playing:
|
||||
self._surface_stack.setCurrentWidget(self.video)
|
||||
self.status.setText("正在应用内播放;如格式不受系统解码器支持,可安全外部打开。")
|
||||
|
||||
def _player_error(self, _error: object, message: str = "") -> None:
|
||||
self.status.setText(
|
||||
(message.strip() if message else "系统媒体后端无法播放该格式。")
|
||||
+ " 可使用右侧按钮安全外部打开。"
|
||||
)
|
||||
self.status.setProperty("kind", "warning")
|
||||
|
||||
def _duration_changed(self, duration: int) -> None:
|
||||
self.position.setRange(0, max(0, duration))
|
||||
current = self.player.position() if self.player is not None else 0
|
||||
self.time_label.setText(f"{_clock(current)} / {_clock(duration)}")
|
||||
|
||||
def _position_changed(self, position: int) -> None:
|
||||
if not self.position.isSliderDown():
|
||||
self.position.setValue(position)
|
||||
duration = self.player.duration() if self.player is not None else 0
|
||||
self.time_label.setText(f"{_clock(position)} / {_clock(duration)}")
|
||||
|
||||
def _seek(self, position: int) -> None:
|
||||
if self.player is not None:
|
||||
self.player.setPosition(position)
|
||||
|
||||
def _open_external(self) -> None:
|
||||
if not open_safe_http_url(self.target):
|
||||
self.status.setText("系统未能打开该安全外部链接。")
|
||||
self.status.setProperty("kind", "danger")
|
||||
|
||||
def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 - Qt virtual
|
||||
if self.player is not None:
|
||||
self.player.stop()
|
||||
super().closeEvent(event)
|
||||
|
||||
|
||||
def _clock(milliseconds: int) -> str:
|
||||
seconds = max(0, int(milliseconds) // 1000)
|
||||
return f"{seconds // 60:02d}:{seconds % 60:02d}"
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MULTIMEDIA_AVAILABLE",
|
||||
"InlineRecordingPlayer",
|
||||
"RecordingPlaybackCell",
|
||||
"RecordingPlayerDialog",
|
||||
"alternate_recording_label",
|
||||
"normalize_recording_urls",
|
||||
"open_safe_http_url",
|
||||
"preferred_recording_url",
|
||||
"safe_http_url",
|
||||
"should_inline_recording",
|
||||
]
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Reusable doctor-workstation dialogs."""
|
||||
|
||||
from .diagnosis import DiagnosisDialog, OrderDetailDrawer, present_order_detail
|
||||
|
||||
__all__ = ["DiagnosisDialog", "OrderDetailDrawer", "present_order_detail"]
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,17 @@
|
||||
"""Business pages shown inside :class:`doctor_workstation.ui.shell.ShellWindow`."""
|
||||
|
||||
from .appointments import AppointmentsPage
|
||||
from .consultations import ConsultationsPage
|
||||
from .patients import PatientsPage
|
||||
from .prescription_library import PrescriptionLibraryPage
|
||||
from .prescriptions import PrescriptionsPage
|
||||
from .reception import ReceptionPage
|
||||
|
||||
__all__ = [
|
||||
"AppointmentsPage",
|
||||
"ConsultationsPage",
|
||||
"PatientsPage",
|
||||
"PrescriptionLibraryPage",
|
||||
"PrescriptionsPage",
|
||||
"ReceptionPage",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,837 @@
|
||||
"""Reusable prescription-template library matching the admin workflow."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QSize, Qt
|
||||
from PySide6.QtGui import QColor, QFont
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractItemView,
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QFrame,
|
||||
QGridLayout,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QStackedWidget,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from ..dialogs.prescription import PrescriptionTemplateDialog
|
||||
from ..dialogs.prescription_ai import PrescriptionAiReportDialog, can_open_ai_explain
|
||||
from ..widgets import (
|
||||
EmptyState,
|
||||
MessageBanner,
|
||||
MetricCard,
|
||||
PageHeader,
|
||||
SortableTable,
|
||||
TableColumn,
|
||||
display_text,
|
||||
first_value,
|
||||
friendly_error,
|
||||
get_value,
|
||||
has_permission,
|
||||
invoke,
|
||||
page_items,
|
||||
page_total,
|
||||
run_async,
|
||||
show_toast,
|
||||
)
|
||||
from .prescriptions import (
|
||||
BusinessPager,
|
||||
_cell_host,
|
||||
_painted_icon,
|
||||
_row_action_button,
|
||||
_style_row_host,
|
||||
_tag_label,
|
||||
)
|
||||
|
||||
PRESCRIPTION_LIBRARY_PAGE_QSS = """
|
||||
#PrescriptionLibraryPage { background: #F8FAFF; }
|
||||
#PrescriptionLibraryPage QWidget#PageHeader { min-height: 84px; max-height: 84px; }
|
||||
#PrescriptionLibraryPage QWidget#PageHeader QLabel[role="breadcrumb"],
|
||||
#PrescriptionLibraryPage QWidget#PageHeader QLabel[role="breadcrumbSeparator"],
|
||||
#PrescriptionLibraryPage QWidget#PageHeader QLabel[role="breadcrumbCurrent"] {
|
||||
min-height: 16px; max-height: 16px;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[role="pageTitle"] {
|
||||
color: #15224A; font-size: 20px; font-weight: 700;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#PageHeader QLabel[role="muted"] {
|
||||
color: #7481A3; font-size: 12px; padding-top: 5px;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard {
|
||||
min-height: 80px; max-height: 80px;
|
||||
border: 1px solid #E2E7F4; border-radius: 12px; background: #FFFFFF;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricTitle"] {
|
||||
color: #405074; font-size: 12px; font-weight: 600;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricValue"] {
|
||||
color: #5265F6; font-size: 22px; font-weight: 700;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[metricIcon="true"] {
|
||||
border: 1px solid #DCE3FF; border-radius: 11px; background: #EEF1FF;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[metricIcon="true"][kind="info"] {
|
||||
border-color: #E5DFFF; background: #F2EEFF;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[metricIcon="true"][kind="success"] {
|
||||
border-color: #CDEFE3; background: #E8F8F2;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[metricIcon="true"][kind="warning"] {
|
||||
border-color: #F8DFC2; background: #FFF3E5;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryFilterBar,
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryTableCard {
|
||||
background: #FFFFFF; border: 1px solid #E2E7F4; border-radius: 13px;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar {
|
||||
background: #FFFFFF; border: 0; border-bottom: 1px solid #E7EBF5;
|
||||
border-top-left-radius: 13px; border-top-right-radius: 13px;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"] {
|
||||
min-width: 82px; min-height: 36px; max-height: 36px;
|
||||
padding: 0 8px; margin: 0 4px 0 0;
|
||||
color: #59698E; background: transparent; border: 0;
|
||||
border-bottom: 2px solid transparent; border-radius: 0;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:checked {
|
||||
color: #5265F6; background: transparent; border-bottom-color: #5265F6;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryFilterBar QLineEdit,
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryFilterBar QComboBox {
|
||||
min-height: 36px; max-height: 36px; padding: 0 11px;
|
||||
border-radius: 8px; font-size: 12px;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton {
|
||||
min-height: 34px; max-height: 34px; padding: 0 14px;
|
||||
border-radius: 8px; font-size: 12px;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton {
|
||||
min-height: 32px; max-height: 32px; padding: 0 13px;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"] {
|
||||
min-width: 27px; max-width: 27px; min-height: 27px; max-height: 27px;
|
||||
padding: 0; border-radius: 7px; background: #FFFFFF;
|
||||
border: 1px solid #DCE3F5;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:hover {
|
||||
background: #F3F5FF; border-color: #AAB7FF;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"] {
|
||||
background: #FFF9FA; border-color: #FFD9DE;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:hover {
|
||||
background: #FFF1F3; border-color: #FFACB8;
|
||||
}
|
||||
#PrescriptionLibraryPage QTableWidget {
|
||||
border: 0; border-radius: 0; background: #FFFFFF;
|
||||
alternate-background-color: #FBFCFF; font-size: 12px;
|
||||
}
|
||||
#PrescriptionLibraryPage QTableWidget::item {
|
||||
padding: 4px 8px; border-bottom: 1px solid #EDF0F7;
|
||||
}
|
||||
#PrescriptionLibraryPage QTableWidget::item:selected {
|
||||
color: #26365F; background: #FCFDFF;
|
||||
}
|
||||
#PrescriptionLibraryPage QHeaderView::section {
|
||||
min-height: 38px; max-height: 38px; padding: 0 8px;
|
||||
background: #F7F9FE; color: #7481A3;
|
||||
border: 0; border-bottom: 1px solid #E7EBF5;
|
||||
font-size: 12px; font-weight: 600;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#Pager { min-height: 42px; }
|
||||
#PrescriptionLibraryPage QWidget#Pager QPushButton {
|
||||
min-width: 34px; max-height: 32px; min-height: 32px; padding: 0 10px;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#Pager QLabel#PagerActive {
|
||||
min-width: 48px; min-height: 30px; border-radius: 7px;
|
||||
background: #5265F6; color: #FFFFFF; font-weight: 700;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#BusinessPager QPushButton[pagerPage="true"] {
|
||||
min-width: 34px; max-width: 34px; min-height: 32px; max-height: 32px;
|
||||
padding: 0; background: #FFFFFF; color: #405074; border-color: #E2E7F4;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#BusinessPager QPushButton[pagerPage="true"][active="true"] {
|
||||
background: #5265F6; color: #FFFFFF; border-color: #5265F6;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#BusinessPager QComboBox {
|
||||
min-height: 32px; max-height: 32px; min-width: 92px; padding: 0 9px;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _formula_text(value: Any, _row: Any = None) -> str:
|
||||
text = str(value or "").strip().lower()
|
||||
return "辅方" if text in {"2", "aux", "auxiliary", "secondary", "辅方"} else "主方"
|
||||
|
||||
|
||||
def _visibility_text(value: Any, _row: Any = None) -> str:
|
||||
return "所有人可见" if value in (True, 1, "1", "public", "all") else "仅自己可见"
|
||||
|
||||
|
||||
def _disable_edit_text(value: Any, _row: Any = None) -> str:
|
||||
return "已禁用" if value in (True, 1, "1") else "可修改"
|
||||
|
||||
|
||||
def _herb_count(_value: Any, row: Any) -> str:
|
||||
herbs = get_value(row, "herbs", None) or []
|
||||
return f"{len(herbs)}味" if isinstance(herbs, (list, tuple)) else "0味"
|
||||
|
||||
|
||||
def _herbs_detail(_value: Any, row: Any) -> str:
|
||||
herbs = get_value(row, "herbs", None) or []
|
||||
if not isinstance(herbs, (list, tuple)):
|
||||
return display_text(herbs)
|
||||
pieces = []
|
||||
for herb in herbs:
|
||||
name = first_value(herb, "name", "medicine_name", default="药材")
|
||||
dosage = first_value(herb, "dosage", "amount", default="")
|
||||
pieces.append(f"{name} {dosage}g".strip())
|
||||
return "、".join(pieces) if pieces else "暂无药材"
|
||||
|
||||
|
||||
def _efficacy_text(_value: Any, row: Any) -> str:
|
||||
return display_text(
|
||||
first_value(
|
||||
row,
|
||||
"efficacy",
|
||||
"efficacy_text",
|
||||
"effect",
|
||||
"effect_text",
|
||||
"indications",
|
||||
default="—",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _metric_card(title: str, kind: str = "accent") -> MetricCard:
|
||||
card = MetricCard(title, "0", kind=kind, glyph="")
|
||||
card.setFixedHeight(80)
|
||||
card.layout().setContentsMargins(18, 12, 16, 12)
|
||||
icon = QLabel(card)
|
||||
icon.setProperty("metricIcon", True)
|
||||
icon.setProperty("kind", kind)
|
||||
icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
icon.setFixedSize(42, 42)
|
||||
colors = {
|
||||
"accent": "#5365F5",
|
||||
"info": "#8268E8",
|
||||
"success": "#23A77D",
|
||||
"warning": "#E6932C",
|
||||
}
|
||||
icon.setPixmap(_painted_icon("document", colors.get(kind, "#5365F5"), 18).pixmap(18, 18))
|
||||
card.layout().addWidget(icon)
|
||||
return card
|
||||
|
||||
|
||||
class PrescriptionLibraryPage(QWidget):
|
||||
"""Filter, inspect, and manage reusable prescriptions."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
repository: Any,
|
||||
permissions: Any = None,
|
||||
current_user: Any = None,
|
||||
parent: QWidget | None = None,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("PrescriptionLibraryPage")
|
||||
self.setStyleSheet(PRESCRIPTION_LIBRARY_PAGE_QSS)
|
||||
self.repository = repository
|
||||
self.permissions = permissions
|
||||
self.current_user = current_user
|
||||
self._generation = 0
|
||||
self._loading = False
|
||||
self._refresh_pending = False
|
||||
self._page = 1
|
||||
self._page_size = 15
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(24, 19, 24, 14)
|
||||
root.setSpacing(12)
|
||||
header = PageHeader(
|
||||
"处方库",
|
||||
"管理常用处方模板,支持 AI 解析辅助开方。",
|
||||
)
|
||||
header.actions.setSpacing(16)
|
||||
self.new_button = QPushButton("新增处方", header)
|
||||
self.new_button.setMinimumWidth(124)
|
||||
self.new_button.setProperty("variant", "primary")
|
||||
self.new_button.setIcon(_painted_icon("plus", "#FFFFFF", 15))
|
||||
self.new_button.setIconSize(QSize(15, 15))
|
||||
self.new_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.new_button.setVisible(has_permission(permissions, "wcf.prescription/add"))
|
||||
self.new_button.clicked.connect(self._new_template)
|
||||
header.add_action(self.new_button)
|
||||
root.addWidget(header)
|
||||
|
||||
metrics = QHBoxLayout()
|
||||
metrics.setContentsMargins(0, 0, 0, 5)
|
||||
metrics.setSpacing(24)
|
||||
self.metric_cards = {
|
||||
"total": _metric_card("全部处方"),
|
||||
"private": _metric_card("仅自己", "info"),
|
||||
"public": _metric_card("公开处方", "success"),
|
||||
"month": _metric_card("本月新增", "warning"),
|
||||
}
|
||||
for metric in self.metric_cards.values():
|
||||
metrics.addWidget(metric)
|
||||
root.addLayout(metrics)
|
||||
|
||||
self.hint_banner = MessageBanner(parent=self)
|
||||
self.hint_banner.show_message(
|
||||
"AI 仅依据药材组合推测可能证候与主治方向,不能替代四诊、辨证和处方审核。",
|
||||
"warning",
|
||||
)
|
||||
self.hint_banner.hide()
|
||||
|
||||
filters = QFrame()
|
||||
filters.setObjectName("PrescriptionLibraryFilterBar")
|
||||
grid = QGridLayout(filters)
|
||||
grid.setContentsMargins(16, 11, 16, 11)
|
||||
grid.setHorizontalSpacing(20)
|
||||
self.name_filter = QLineEdit()
|
||||
self.name_filter.setPlaceholderText("搜索处方名称、药材、功效等关键词")
|
||||
self.name_filter.setClearButtonEnabled(True)
|
||||
self.name_filter.returnPressed.connect(self._search)
|
||||
grid.addWidget(self.name_filter, 0, 0)
|
||||
self.formula_filter = QComboBox()
|
||||
self.formula_filter.addItem("全部类型", "")
|
||||
self.formula_filter.addItem("主方", "主方")
|
||||
self.formula_filter.addItem("辅方", "辅方")
|
||||
grid.addWidget(self.formula_filter, 0, 1)
|
||||
self.visibility_filter = QComboBox()
|
||||
self.visibility_filter.addItem("全部公开范围", "")
|
||||
self.visibility_filter.addItem("仅自己可见", 0)
|
||||
self.visibility_filter.addItem("所有人可见", 1)
|
||||
grid.addWidget(self.visibility_filter, 0, 2)
|
||||
self.effect_filter = QComboBox()
|
||||
self.effect_filter.addItem("全部功效类型", "")
|
||||
self.effect_filter.addItem("益气养阴", "益气养阴")
|
||||
self.effect_filter.addItem("清热祛湿", "清热祛湿")
|
||||
self.effect_filter.addItem("滋阴补肾", "滋阴补肾")
|
||||
grid.addWidget(self.effect_filter, 0, 3)
|
||||
self.name_filter.setMinimumWidth(500)
|
||||
self.formula_filter.setFixedWidth(190)
|
||||
self.visibility_filter.setFixedWidth(174)
|
||||
self.effect_filter.setFixedWidth(190)
|
||||
self.query_button = QPushButton("查询")
|
||||
self.query_button.setFixedWidth(66)
|
||||
self.query_button.setProperty("variant", "secondary")
|
||||
self.query_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.query_button.clicked.connect(self._search)
|
||||
grid.addWidget(self.query_button, 0, 4)
|
||||
self.reset_button = QPushButton("重置")
|
||||
self.reset_button.setFixedWidth(66)
|
||||
self.reset_button.setProperty("variant", "ghost")
|
||||
self.reset_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.reset_button.clicked.connect(self._reset_filters)
|
||||
grid.addWidget(self.reset_button, 0, 5)
|
||||
grid.setColumnStretch(0, 1)
|
||||
root.addWidget(filters)
|
||||
|
||||
self.banner = MessageBanner()
|
||||
root.addWidget(self.banner)
|
||||
card = QFrame()
|
||||
card.setObjectName("PrescriptionLibraryTableCard")
|
||||
card_layout = QVBoxLayout(card)
|
||||
card_layout.setContentsMargins(0, 0, 0, 0)
|
||||
card_layout.setSpacing(0)
|
||||
toolbar_host = QFrame(card)
|
||||
toolbar_host.setObjectName("PrescriptionLibraryToolbar")
|
||||
toolbar = QHBoxLayout(toolbar_host)
|
||||
toolbar.setContentsMargins(16, 10, 16, 9)
|
||||
toolbar.setSpacing(8)
|
||||
self.all_tab = QPushButton("处方列表", toolbar_host)
|
||||
self.all_tab.setProperty("toolbarTab", True)
|
||||
self.all_tab.setCheckable(True)
|
||||
self.all_tab.setChecked(True)
|
||||
self.all_tab.clicked.connect(lambda: self._set_library_scope(False))
|
||||
toolbar.addWidget(self.all_tab)
|
||||
self.favorite_tab = QPushButton("我的收藏", toolbar_host)
|
||||
self.favorite_tab.setProperty("toolbarTab", True)
|
||||
self.favorite_tab.setCheckable(True)
|
||||
self.favorite_tab.clicked.connect(lambda: self._set_library_scope(True))
|
||||
toolbar.addWidget(self.favorite_tab)
|
||||
toolbar.addStretch(1)
|
||||
self.view_button = QPushButton("查看", card)
|
||||
self.view_button.setIcon(_painted_icon("eye", "#5265F6", 15))
|
||||
self.view_button.setIconSize(QSize(15, 15))
|
||||
self.view_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.view_button.setVisible(has_permission(permissions, "wcf.prescription/read"))
|
||||
self.view_button.setEnabled(False)
|
||||
self.view_button.clicked.connect(self._view_selected)
|
||||
toolbar.addWidget(self.view_button)
|
||||
self.ai_button = QPushButton("AI解释", card)
|
||||
self.ai_button.setProperty("variant", "secondary")
|
||||
self.ai_button.setIcon(_painted_icon("spark", "#5265F6", 15))
|
||||
self.ai_button.setIconSize(QSize(15, 15))
|
||||
self.ai_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.ai_button.setVisible(can_open_ai_explain(permissions))
|
||||
self.ai_button.setEnabled(False)
|
||||
self.ai_button.clicked.connect(self._explain_selected)
|
||||
toolbar.addWidget(self.ai_button)
|
||||
self.edit_button = QPushButton("编辑", card)
|
||||
self.edit_button.setIcon(_painted_icon("pencil", "#5265F6", 15))
|
||||
self.edit_button.setIconSize(QSize(15, 15))
|
||||
self.edit_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.edit_button.setVisible(has_permission(permissions, "wcf.prescription/edit"))
|
||||
self.edit_button.setEnabled(False)
|
||||
self.edit_button.clicked.connect(self._edit_selected)
|
||||
toolbar.addWidget(self.edit_button)
|
||||
self.delete_button = QPushButton("删除", card)
|
||||
self.delete_button.setProperty("variant", "danger")
|
||||
self.delete_button.setIcon(_painted_icon("trash", "#F34E64", 15))
|
||||
self.delete_button.setIconSize(QSize(15, 15))
|
||||
self.delete_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.delete_button.setVisible(has_permission(permissions, "wcf.prescription/delete"))
|
||||
self.delete_button.setEnabled(False)
|
||||
self.delete_button.clicked.connect(self._delete_selected)
|
||||
toolbar.addWidget(self.delete_button)
|
||||
refresh = QPushButton("刷新")
|
||||
refresh.setProperty("variant", "ghost")
|
||||
refresh.setIcon(_painted_icon("refresh", "#5D6E96", 15))
|
||||
refresh.setIconSize(QSize(15, 15))
|
||||
refresh.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
refresh.clicked.connect(self.refresh)
|
||||
toolbar.addWidget(refresh)
|
||||
card_layout.addWidget(toolbar_host)
|
||||
|
||||
self.stack = QStackedWidget()
|
||||
table_host = QWidget()
|
||||
table_layout = QVBoxLayout(table_host)
|
||||
table_layout.setContentsMargins(0, 0, 0, 0)
|
||||
self.table = SortableTable(
|
||||
[
|
||||
TableColumn("id", "ID", 62),
|
||||
TableColumn("prescription_name", "处方名称", 162),
|
||||
TableColumn("formula_type", "处方类型", 88, _formula_text),
|
||||
TableColumn("herbs", "药材数量", 84, _herb_count),
|
||||
TableColumn("herbs", "药材组成(部分)", 296, _herbs_detail),
|
||||
TableColumn("efficacy", "功效主治", 170, _efficacy_text),
|
||||
TableColumn("is_public", "公开范围", 135, _visibility_text),
|
||||
TableColumn("creator_name", "创建人", 100),
|
||||
TableColumn("create_time", "创建时间", 178),
|
||||
TableColumn("__actions__", "操作", 160, lambda _value, _row: ""),
|
||||
]
|
||||
)
|
||||
self.table.verticalHeader().setDefaultSectionSize(37)
|
||||
self.table.horizontalHeader().setFixedHeight(41)
|
||||
self.table.setWordWrap(False)
|
||||
self.table.setHorizontalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel)
|
||||
self.table.itemSelectionChanged.connect(self._selection_changed)
|
||||
self.table.itemDoubleClicked.connect(lambda _item: self._view_selected())
|
||||
table_layout.addWidget(self.table, 1)
|
||||
self.pager = BusinessPager(self._page_size)
|
||||
self.pager.page_changed.connect(self._change_page)
|
||||
table_layout.addWidget(self.pager)
|
||||
self.stack.addWidget(table_host)
|
||||
empty = EmptyState(
|
||||
"还没有处方模板",
|
||||
"可以新增常用药材组合,之后开方时快速导入。",
|
||||
"新增处方",
|
||||
)
|
||||
empty.action_button.setVisible(self.new_button.isVisible())
|
||||
empty.action_requested.connect(self._new_template)
|
||||
self.stack.addWidget(empty)
|
||||
card_layout.addWidget(self.stack, 1)
|
||||
root.addWidget(card, 1)
|
||||
|
||||
def _search(self) -> None:
|
||||
self._page = 1
|
||||
self.refresh()
|
||||
|
||||
def _set_library_scope(self, favorites_only: bool) -> None:
|
||||
"""Switch the visual library tab while retaining server-backed rows.
|
||||
|
||||
The current repository contract has no favorites discriminator, so the
|
||||
tab is a presentation-compatible scope until that capability is exposed.
|
||||
"""
|
||||
|
||||
self.all_tab.setChecked(not favorites_only)
|
||||
self.favorite_tab.setChecked(favorites_only)
|
||||
self._page = 1
|
||||
self.refresh()
|
||||
|
||||
def _reset_filters(self) -> None:
|
||||
self.name_filter.clear()
|
||||
self.formula_filter.setCurrentIndex(0)
|
||||
self.visibility_filter.setCurrentIndex(0)
|
||||
self.effect_filter.setCurrentIndex(0)
|
||||
self._search()
|
||||
|
||||
def _change_page(self, page: int) -> None:
|
||||
self._page = page
|
||||
self.refresh()
|
||||
|
||||
def refresh(self) -> None:
|
||||
if self._loading:
|
||||
self._refresh_pending = True
|
||||
return
|
||||
self._loading = True
|
||||
self._refresh_pending = False
|
||||
self._generation += 1
|
||||
generation = self._generation
|
||||
query = {
|
||||
"prescription_name": self.name_filter.text().strip(),
|
||||
"formula_type": self.formula_filter.currentData(),
|
||||
"is_public": self.visibility_filter.currentData(),
|
||||
"page": self._page,
|
||||
"page_size": self._page_size,
|
||||
}
|
||||
requested_page = self._page
|
||||
self.banner.show_message("正在加载处方库…", "info")
|
||||
run_async(
|
||||
lambda: invoke(
|
||||
self.repository,
|
||||
"prescription_library",
|
||||
**query,
|
||||
),
|
||||
on_success=lambda result: self._apply_result(result, generation, requested_page),
|
||||
on_error=lambda error: self._load_error(error, generation),
|
||||
on_finished=lambda: self._load_finished(generation),
|
||||
)
|
||||
|
||||
def _apply_result(self, result: Any, generation: int, requested_page: int) -> None:
|
||||
if generation != self._generation:
|
||||
return
|
||||
rows = page_items(result)
|
||||
effect = str(self.effect_filter.currentData() or "").strip()
|
||||
if effect:
|
||||
rows = [
|
||||
row
|
||||
for row in rows
|
||||
if effect
|
||||
in str(
|
||||
first_value(
|
||||
row,
|
||||
"efficacy",
|
||||
"efficacy_text",
|
||||
"effect",
|
||||
"effect_text",
|
||||
"indications",
|
||||
default="",
|
||||
)
|
||||
)
|
||||
]
|
||||
self.table.set_rows(rows)
|
||||
self._decorate_rows(rows)
|
||||
total = page_total(result, len(rows))
|
||||
self.pager.update_state(requested_page, total)
|
||||
public_count = sum(
|
||||
1 for row in rows if _truthy(first_value(row, "is_public", default=False))
|
||||
)
|
||||
month_prefix = datetime.now().strftime("%Y-%m")
|
||||
month_count = sum(
|
||||
1
|
||||
for row in rows
|
||||
if str(first_value(row, "create_time", "created_at", default="")).startswith(
|
||||
month_prefix
|
||||
)
|
||||
)
|
||||
self.metric_cards["total"].set_value(total)
|
||||
self.metric_cards["private"].set_value(max(0, len(rows) - public_count))
|
||||
self.metric_cards["public"].set_value(public_count)
|
||||
self.metric_cards["month"].set_value(month_count)
|
||||
self.stack.setCurrentIndex(0 if rows else 1)
|
||||
self.banner.clear()
|
||||
self._selection_changed()
|
||||
|
||||
def _decorate_rows(self, rows: list[Any]) -> None:
|
||||
"""Install compact tags and permission-aware row actions from the comp."""
|
||||
|
||||
for row_index, row in enumerate(rows):
|
||||
id_item = self.table.item(row_index, 0)
|
||||
if id_item is not None:
|
||||
id_item.setTextAlignment(
|
||||
Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter
|
||||
)
|
||||
|
||||
name_item = self.table.item(row_index, 1)
|
||||
if name_item is not None:
|
||||
name_item.setForeground(QColor("#24355F"))
|
||||
font = name_item.font()
|
||||
font.setWeight(QFont.Weight.DemiBold)
|
||||
name_item.setFont(font)
|
||||
|
||||
formula = _formula_text(first_value(row, "formula_type", default="主方"))
|
||||
formula_kind = "success" if formula == "主方" else "accent"
|
||||
self.table.setCellWidget(
|
||||
row_index,
|
||||
2,
|
||||
_style_row_host(
|
||||
_cell_host(
|
||||
_tag_label(formula, formula_kind, self.table.viewport())
|
||||
),
|
||||
row_index,
|
||||
),
|
||||
)
|
||||
|
||||
visibility_host = QWidget(self.table.viewport())
|
||||
_style_row_host(visibility_host, row_index)
|
||||
visibility_layout = QHBoxLayout(visibility_host)
|
||||
visibility_layout.setContentsMargins(8, 0, 6, 0)
|
||||
visibility_layout.setSpacing(6)
|
||||
visibility_icon = QLabel(visibility_host)
|
||||
visibility_icon.setFixedSize(15, 15)
|
||||
visibility_icon.setPixmap(_painted_icon("lock", "#60709A", 14).pixmap(14, 14))
|
||||
visibility_layout.addWidget(visibility_icon)
|
||||
visibility_label = QLabel(
|
||||
_visibility_text(first_value(row, "is_public", default=0)),
|
||||
visibility_host,
|
||||
)
|
||||
visibility_label.setStyleSheet("color:#3F4F76;background:transparent;border:0;")
|
||||
visibility_layout.addWidget(visibility_label)
|
||||
visibility_layout.addStretch(1)
|
||||
self.table.setCellWidget(row_index, 6, visibility_host)
|
||||
|
||||
actions_host = QWidget(self.table.viewport())
|
||||
_style_row_host(actions_host, row_index)
|
||||
actions = QHBoxLayout(actions_host)
|
||||
actions.setContentsMargins(6, 0, 6, 0)
|
||||
actions.setSpacing(5)
|
||||
actions.addStretch(1)
|
||||
if has_permission(self.permissions, "wcf.prescription/read"):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"eye",
|
||||
"查看处方模板",
|
||||
lambda _checked=False, target=row: self._run_row_action(
|
||||
target, self._view_selected
|
||||
),
|
||||
actions_host,
|
||||
)
|
||||
)
|
||||
if can_open_ai_explain(self.permissions):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"spark",
|
||||
"AI 解释",
|
||||
lambda _checked=False, target=row: self._run_row_action(
|
||||
target, self._explain_selected
|
||||
),
|
||||
actions_host,
|
||||
)
|
||||
)
|
||||
manageable = self._can_manage_row(row)
|
||||
if has_permission(self.permissions, "wcf.prescription/edit"):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"pencil",
|
||||
"编辑处方模板",
|
||||
lambda _checked=False, target=row: self._run_row_action(
|
||||
target, self._edit_selected
|
||||
),
|
||||
actions_host,
|
||||
enabled=manageable,
|
||||
)
|
||||
)
|
||||
if has_permission(self.permissions, "wcf.prescription/delete"):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"trash",
|
||||
"删除处方模板",
|
||||
lambda _checked=False, target=row: self._run_row_action(
|
||||
target, self._delete_selected
|
||||
),
|
||||
actions_host,
|
||||
danger=True,
|
||||
enabled=manageable,
|
||||
)
|
||||
)
|
||||
actions.addStretch(1)
|
||||
self.table.setCellWidget(row_index, 9, actions_host)
|
||||
|
||||
def _run_row_action(self, row: Any, callback: Any) -> None:
|
||||
target_id = first_value(row, "id", "template_id", default=None)
|
||||
for row_index in range(self.table.rowCount()):
|
||||
item = self.table.item(row_index, 0)
|
||||
candidate = item.data(Qt.ItemDataRole.UserRole) if item is not None else None
|
||||
candidate_id = first_value(candidate, "id", "template_id", default=None)
|
||||
if candidate is row or (
|
||||
target_id is not None and str(candidate_id) == str(target_id)
|
||||
):
|
||||
self.table.selectRow(row_index)
|
||||
break
|
||||
callback()
|
||||
|
||||
def _load_error(self, error: Exception, generation: int) -> None:
|
||||
if generation == self._generation:
|
||||
self.banner.show_message(friendly_error(error), "danger")
|
||||
|
||||
def _load_finished(self, generation: int) -> None:
|
||||
if generation == self._generation:
|
||||
self._loading = False
|
||||
if self._refresh_pending:
|
||||
self._refresh_pending = False
|
||||
self.refresh()
|
||||
|
||||
def _selection_changed(self) -> None:
|
||||
row = self.table.current_data()
|
||||
self.view_button.setEnabled(row is not None)
|
||||
self.ai_button.setEnabled(row is not None)
|
||||
manageable = self._can_manage_row(row)
|
||||
self.edit_button.setEnabled(row is not None and manageable)
|
||||
self.delete_button.setEnabled(row is not None and manageable)
|
||||
|
||||
def _can_manage_row(self, row: Any) -> bool:
|
||||
if row is None:
|
||||
return False
|
||||
user_id = first_value(self.current_user, "id", "user_id", default=None)
|
||||
creator_id = first_value(row, "creator_id", "doctor_id", default=None)
|
||||
if user_id is not None and creator_id is not None and str(user_id) == str(creator_id):
|
||||
return True
|
||||
if _truthy(first_value(self.current_user, "root", "is_root", default=False)):
|
||||
return True
|
||||
role_ids = first_value(self.current_user, "role_ids", "role_id", default=[]) or []
|
||||
if not isinstance(role_ids, (list, tuple, set)):
|
||||
role_ids = [role_ids]
|
||||
return any(str(role) in {"0", "3"} for role in role_ids)
|
||||
|
||||
def _new_template(self) -> None:
|
||||
if not has_permission(self.permissions, "wcf.prescription/add"):
|
||||
return
|
||||
dialog = PrescriptionTemplateDialog(
|
||||
self.repository,
|
||||
mode="add",
|
||||
parent=self,
|
||||
)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
self._save_template(dialog.payload(), None)
|
||||
|
||||
def _view_selected(self) -> None:
|
||||
row = self.table.current_data()
|
||||
if row is None or not has_permission(self.permissions, "wcf.prescription/read"):
|
||||
return
|
||||
PrescriptionTemplateDialog(
|
||||
self.repository,
|
||||
row,
|
||||
mode="view",
|
||||
parent=self,
|
||||
).exec()
|
||||
|
||||
def _explain_selected(self) -> None:
|
||||
row = self.table.current_data()
|
||||
if row is None or not can_open_ai_explain(self.permissions):
|
||||
return
|
||||
dialog = PrescriptionAiReportDialog(self.repository, self.permissions, parent=self)
|
||||
dialog.open_for(row)
|
||||
dialog.exec()
|
||||
|
||||
def _edit_selected(self) -> None:
|
||||
row = self.table.current_data()
|
||||
if (
|
||||
row is None
|
||||
or not has_permission(self.permissions, "wcf.prescription/edit")
|
||||
or not self._can_manage_row(row)
|
||||
):
|
||||
return
|
||||
dialog = PrescriptionTemplateDialog(
|
||||
self.repository,
|
||||
row,
|
||||
mode="edit",
|
||||
parent=self,
|
||||
)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
self._save_template(
|
||||
dialog.payload(),
|
||||
first_value(row, "id", "template_id", default=None),
|
||||
)
|
||||
|
||||
def _save_template(self, payload: dict[str, Any], template_id: Any) -> None:
|
||||
permission = "wcf.prescription/add" if template_id is None else "wcf.prescription/edit"
|
||||
if not has_permission(self.permissions, permission):
|
||||
return
|
||||
self._set_actions_enabled(False)
|
||||
if template_id is None:
|
||||
|
||||
def operation() -> Any:
|
||||
return invoke(
|
||||
self.repository,
|
||||
"create_prescription_template",
|
||||
template=payload,
|
||||
)
|
||||
else:
|
||||
|
||||
def operation() -> Any:
|
||||
return invoke(
|
||||
self.repository,
|
||||
"update_prescription_template",
|
||||
template=template_id,
|
||||
changes=payload,
|
||||
)
|
||||
|
||||
run_async(
|
||||
operation,
|
||||
on_success=lambda _result: self._mutation_success("处方模板已保存。"),
|
||||
on_error=lambda error: show_toast(self, friendly_error(error), "danger", 4300),
|
||||
on_finished=lambda: self._set_actions_enabled(True),
|
||||
)
|
||||
|
||||
def _delete_selected(self) -> None:
|
||||
row = self.table.current_data()
|
||||
template_id = first_value(row, "id", "template_id", default=None)
|
||||
if (
|
||||
row is None
|
||||
or template_id is None
|
||||
or not has_permission(self.permissions, "wcf.prescription/delete")
|
||||
or not self._can_manage_row(row)
|
||||
):
|
||||
return
|
||||
name = display_text(first_value(row, "prescription_name", "name", default="该模板"))
|
||||
answer = QMessageBox.warning(
|
||||
self,
|
||||
"删除处方模板",
|
||||
f"确定删除“{name}”吗?此操作无法撤销。",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel,
|
||||
QMessageBox.StandardButton.Cancel,
|
||||
)
|
||||
if answer != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
self._set_actions_enabled(False)
|
||||
run_async(
|
||||
lambda: invoke(
|
||||
self.repository,
|
||||
"delete_prescription_template",
|
||||
template_id=template_id,
|
||||
),
|
||||
on_success=lambda _result: self._mutation_success("处方模板已删除。"),
|
||||
on_error=lambda error: show_toast(self, friendly_error(error), "danger", 4300),
|
||||
on_finished=lambda: self._set_actions_enabled(True),
|
||||
)
|
||||
|
||||
def _mutation_success(self, message: str) -> None:
|
||||
show_toast(self, message, "success")
|
||||
self.refresh()
|
||||
|
||||
def _set_actions_enabled(self, enabled: bool) -> None:
|
||||
self.new_button.setEnabled(enabled)
|
||||
if not enabled:
|
||||
self.view_button.setEnabled(False)
|
||||
self.ai_button.setEnabled(False)
|
||||
self.edit_button.setEnabled(False)
|
||||
self.delete_button.setEnabled(False)
|
||||
else:
|
||||
self._selection_changed()
|
||||
|
||||
def showEvent(self, event: Any) -> None:
|
||||
super().showEvent(event)
|
||||
if self.table.rowCount() == 0 and not self._loading:
|
||||
self.refresh()
|
||||
|
||||
|
||||
def _truthy(value: Any) -> bool:
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() not in {"", "0", "false", "no", "off"}
|
||||
return bool(value)
|
||||
|
||||
|
||||
__all__ = ["PrescriptionLibraryPage", "PrescriptionTemplateDialog"]
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,862 @@
|
||||
"""Shared widgets and safe asynchronous helpers for the UI layer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import traceback
|
||||
from collections.abc import Callable, Iterable, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QObject, QRunnable, Qt, QThreadPool, QTimer, Signal, Slot
|
||||
from PySide6.QtGui import QColor, QPainter, QPaintEvent, QResizeEvent
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractItemView,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QPushButton,
|
||||
QSizePolicy,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from doctor_workstation.core.errors import (
|
||||
ApiHttpError,
|
||||
ApiProtocolError,
|
||||
ApiTimeoutError,
|
||||
ApiTransportError,
|
||||
AuthenticationExpiredError,
|
||||
)
|
||||
|
||||
AuthenticationExpiredHandler = Callable[[AuthenticationExpiredError], bool]
|
||||
_AUTHENTICATION_EXPIRED_HANDLER: AuthenticationExpiredHandler | None = None
|
||||
|
||||
|
||||
def set_authentication_expired_handler(
|
||||
handler: AuthenticationExpiredHandler | None,
|
||||
) -> None:
|
||||
"""Install the application-level expired-session callback.
|
||||
|
||||
The callback returns ``True`` when it consumed the error. Returning
|
||||
``False`` preserves the originating operation's local error handling, as is
|
||||
required when authentication itself fails on the login screen.
|
||||
"""
|
||||
|
||||
global _AUTHENTICATION_EXPIRED_HANDLER
|
||||
_AUTHENTICATION_EXPIRED_HANDLER = handler
|
||||
|
||||
|
||||
def get_value(value: Any, key: str, default: Any = None) -> Any:
|
||||
"""Read a dotted key from mappings, dataclasses, or ordinary objects."""
|
||||
|
||||
current = value
|
||||
for part in key.split("."):
|
||||
if current is None:
|
||||
return default
|
||||
if isinstance(current, Mapping):
|
||||
current = current.get(part, default)
|
||||
else:
|
||||
marker = object()
|
||||
candidate = getattr(current, part, marker)
|
||||
if candidate is marker:
|
||||
raw = getattr(current, "raw", None)
|
||||
candidate = raw.get(part, marker) if isinstance(raw, Mapping) else marker
|
||||
current = default if candidate is marker else candidate
|
||||
if current is default:
|
||||
return default
|
||||
return current
|
||||
|
||||
|
||||
def first_value(value: Any, *keys: str, default: Any = None) -> Any:
|
||||
"""Return the first present, non-empty value from ``keys``."""
|
||||
|
||||
for key in keys:
|
||||
candidate = get_value(value, key, None)
|
||||
if candidate is not None and candidate != "":
|
||||
return candidate
|
||||
return default
|
||||
|
||||
|
||||
def display_text(value: Any, default: str = "—") -> str:
|
||||
if value is None or value == "":
|
||||
return default
|
||||
if isinstance(value, bool):
|
||||
return "是" if value else "否"
|
||||
if isinstance(value, (datetime, date)):
|
||||
return value.strftime("%Y-%m-%d %H:%M" if isinstance(value, datetime) else "%Y-%m-%d")
|
||||
return str(value)
|
||||
|
||||
|
||||
def gender_text(value: Any, default: str = "—") -> str:
|
||||
"""Format the legacy gender codes without exposing numeric API values."""
|
||||
|
||||
normalized = str(value).strip().lower() if value not in (None, "") else ""
|
||||
labels = {
|
||||
"0": "未知",
|
||||
"1": "男",
|
||||
"2": "女",
|
||||
"m": "男",
|
||||
"male": "男",
|
||||
"f": "女",
|
||||
"female": "女",
|
||||
"unknown": "未知",
|
||||
}
|
||||
return labels.get(normalized, display_text(value, default))
|
||||
|
||||
|
||||
def page_items(result: Any) -> list[Any]:
|
||||
"""Extract rows from common PageResult/dict response shapes."""
|
||||
|
||||
if result is None:
|
||||
return []
|
||||
if isinstance(result, (list, tuple)):
|
||||
return list(result)
|
||||
for key in ("items", "lists", "results", "rows", "data"):
|
||||
items = get_value(result, key, None)
|
||||
if isinstance(items, (list, tuple)):
|
||||
return list(items)
|
||||
if key == "data" and items is not None and items is not result:
|
||||
nested = page_items(items)
|
||||
if nested:
|
||||
return nested
|
||||
return []
|
||||
|
||||
|
||||
def page_total(result: Any, fallback: int = 0) -> int:
|
||||
for key in ("total", "count", "total_count", "data.total", "data.count"):
|
||||
value = get_value(result, key, None)
|
||||
if value is not None:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return fallback
|
||||
|
||||
|
||||
def has_permission(permissions: Any, codes: str | Sequence[str], default: bool = True) -> bool:
|
||||
"""Check canonical permissions with exact and resource-wildcard semantics.
|
||||
|
||||
A sequence uses OR semantics, matching the admin client's route guards.
|
||||
Permission names are opaque: ``resource/action`` never aliases
|
||||
``resource.action``.
|
||||
"""
|
||||
|
||||
if permissions is None:
|
||||
return default
|
||||
requested = tuple(
|
||||
code.strip()
|
||||
for code in ((codes,) if isinstance(codes, str) else tuple(codes))
|
||||
if code and code.strip()
|
||||
)
|
||||
if not requested:
|
||||
return True
|
||||
|
||||
for method_name in ("allows", "has", "can", "contains", "has_permission"):
|
||||
method = getattr(permissions, method_name, None)
|
||||
if callable(method):
|
||||
for code in requested:
|
||||
try:
|
||||
if bool(method(code)):
|
||||
return True
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
|
||||
raw = permissions
|
||||
for attr in ("codes", "permissions", "values"):
|
||||
candidate = getattr(permissions, attr, None)
|
||||
if candidate is not None and not callable(candidate):
|
||||
raw = candidate
|
||||
break
|
||||
if isinstance(raw, Mapping):
|
||||
available = {str(key).strip() for key, enabled in raw.items() if enabled}
|
||||
elif isinstance(raw, str):
|
||||
available = {raw}
|
||||
else:
|
||||
try:
|
||||
available = {str(item).strip() for item in raw}
|
||||
except TypeError:
|
||||
return default
|
||||
return any(
|
||||
"*" in available
|
||||
or code in available
|
||||
or any(grant.endswith("/*") and code.startswith(grant[:-1]) for grant in available)
|
||||
for code in requested
|
||||
)
|
||||
|
||||
|
||||
def invoke(repository: Any, method_name: str, /, **kwargs: Any) -> Any:
|
||||
"""Invoke a repository method with keyword filtering for contract tolerance."""
|
||||
|
||||
method = getattr(repository, method_name, None)
|
||||
if method is None and method_name == "save_prescription_template":
|
||||
template = kwargs.get("template") or {}
|
||||
template_id = kwargs.get("template_id", kwargs.get("id"))
|
||||
if template_id is None:
|
||||
creator = (
|
||||
getattr(repository, "create_prescription_template", None)
|
||||
or repository.add_prescription_template
|
||||
)
|
||||
return creator(template=template)
|
||||
updater = (
|
||||
getattr(repository, "update_prescription_template", None)
|
||||
or repository.edit_prescription_template
|
||||
)
|
||||
return updater(template_id, changes=template)
|
||||
|
||||
aliases = {
|
||||
"reception_queue": "list_appointments",
|
||||
"reception_detail": "get_reception",
|
||||
"prescription_library": "list_prescription_templates",
|
||||
"prescriptions": "list_prescriptions",
|
||||
"prescription_detail": "get_prescription",
|
||||
"patients": "list_patients",
|
||||
"consultations": "list_consultations",
|
||||
}
|
||||
resolved_name = method_name
|
||||
if method is None:
|
||||
resolved_name = aliases.get(method_name, method_name)
|
||||
method = getattr(repository, resolved_name, None)
|
||||
if method is None and method_name == "reception_detail":
|
||||
resolved_name = "reception"
|
||||
method = getattr(repository, resolved_name)
|
||||
if method is None:
|
||||
raise AttributeError(f"repository has no method {method_name!r}")
|
||||
|
||||
call_kwargs = dict(kwargs)
|
||||
if resolved_name.startswith("list_") and "page" in call_kwargs and "page_no" not in call_kwargs:
|
||||
call_kwargs["page_no"] = call_kwargs.pop("page")
|
||||
if (
|
||||
resolved_name == "get_prescription"
|
||||
and "id" in call_kwargs
|
||||
and "prescription_id" not in call_kwargs
|
||||
):
|
||||
call_kwargs["prescription_id"] = call_kwargs.pop("id")
|
||||
try:
|
||||
signature = inspect.signature(method)
|
||||
except (TypeError, ValueError):
|
||||
return method(**call_kwargs)
|
||||
parameters = signature.parameters
|
||||
if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in parameters.values()):
|
||||
return method(**call_kwargs)
|
||||
accepted = {
|
||||
name: value
|
||||
for name, value in call_kwargs.items()
|
||||
if name in parameters
|
||||
and parameters[name].kind
|
||||
in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)
|
||||
}
|
||||
if len(parameters) == 1 and not accepted:
|
||||
only = next(iter(parameters.values()))
|
||||
if only.name in {"payload", "data", "query", "filters", "params"}:
|
||||
return method(call_kwargs)
|
||||
return method(**accepted)
|
||||
|
||||
|
||||
class WorkerSignals(QObject):
|
||||
result = Signal(object)
|
||||
error = Signal(object, str)
|
||||
finished = Signal()
|
||||
|
||||
|
||||
class Worker(QRunnable):
|
||||
"""A small QRunnable that marshals results back through Qt signals."""
|
||||
|
||||
def __init__(self, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__()
|
||||
self.function = function
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
self.signals = WorkerSignals()
|
||||
|
||||
@Slot()
|
||||
def run(self) -> None:
|
||||
try:
|
||||
result = self.function(*self.args, **self.kwargs)
|
||||
except Exception as exc: # UI boundary: report domain and transport errors alike.
|
||||
self.signals.error.emit(exc, traceback.format_exc())
|
||||
else:
|
||||
self.signals.result.emit(result)
|
||||
finally:
|
||||
self.signals.finished.emit()
|
||||
|
||||
|
||||
_RUNNING_WORKERS: set[Worker] = set()
|
||||
|
||||
|
||||
def _dispatch_async_error(
|
||||
error: Exception,
|
||||
local_handler: Callable[[Exception], None] | None,
|
||||
) -> None:
|
||||
"""Route session expiry globally before falling back to a page handler."""
|
||||
|
||||
handled = False
|
||||
if isinstance(error, AuthenticationExpiredError):
|
||||
handler = _AUTHENTICATION_EXPIRED_HANDLER
|
||||
if handler is not None:
|
||||
try:
|
||||
handled = bool(handler(error))
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
if not handled and local_handler is not None:
|
||||
local_handler(error)
|
||||
|
||||
|
||||
def run_async(
|
||||
function: Callable[..., Any],
|
||||
*args: Any,
|
||||
on_success: Callable[[Any], None] | None = None,
|
||||
on_error: Callable[[Exception], None] | None = None,
|
||||
on_finished: Callable[[], None] | None = None,
|
||||
pool: QThreadPool | None = None,
|
||||
**kwargs: Any,
|
||||
) -> Worker:
|
||||
"""Run ``function`` off the GUI thread and return its Worker handle."""
|
||||
|
||||
worker = Worker(function, *args, **kwargs)
|
||||
_RUNNING_WORKERS.add(worker)
|
||||
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))
|
||||
if on_finished is not None:
|
||||
worker.signals.finished.connect(on_finished)
|
||||
worker.signals.finished.connect(lambda: _RUNNING_WORKERS.discard(worker))
|
||||
(pool or QThreadPool.globalInstance()).start(worker)
|
||||
return worker
|
||||
|
||||
|
||||
def friendly_error(error: Any) -> str:
|
||||
text = str(error).strip()
|
||||
lowered = text.lower()
|
||||
if "certificate_verify_failed" in lowered or "self-signed certificate" in lowered:
|
||||
return (
|
||||
"服务器证书不受系统信任。若这是可信内网的自签名服务器,请展开“服务器设置”,"
|
||||
"勾选“信任自签名证书(仅内网调试)”后重新登录,设置会自动应用。"
|
||||
)
|
||||
if isinstance(error, AuthenticationExpiredError):
|
||||
return "登录状态已失效,请重新登录。"
|
||||
if isinstance(error, ApiTimeoutError) or "timed out" in lowered or "timeout" in lowered:
|
||||
return "连接服务器超时,请检查网络后重试。"
|
||||
if isinstance(error, ApiProtocolError) or any(
|
||||
marker in lowered
|
||||
for marker in (
|
||||
"api response envelope",
|
||||
"api response is not valid json",
|
||||
"invalid json",
|
||||
)
|
||||
):
|
||||
return "服务器返回的数据格式不正确,请联系管理员检查接口。"
|
||||
if isinstance(error, ApiHttpError):
|
||||
status_code = getattr(error, "status_code", None)
|
||||
suffix = f"(状态码 {status_code})" if status_code else ""
|
||||
return f"服务器请求失败{suffix},请稍后重试。"
|
||||
if isinstance(error, ApiTransportError) or any(
|
||||
marker in lowered
|
||||
for marker in (
|
||||
"connection refused",
|
||||
"connecterror",
|
||||
"connection error",
|
||||
"failed to connect",
|
||||
"getaddrinfo failed",
|
||||
"name or service not known",
|
||||
"network is unreachable",
|
||||
)
|
||||
):
|
||||
return "无法连接服务器,请检查服务器地址与网络。"
|
||||
if any(marker in lowered for marker in ("unauthorized", "forbidden", "permission denied")):
|
||||
return "当前账号无权执行此操作。"
|
||||
if "not found" in lowered:
|
||||
return "未找到所需数据。"
|
||||
if any("\u4e00" <= character <= "\u9fff" for character in text):
|
||||
return text
|
||||
if isinstance(error, TypeError):
|
||||
return "程序执行失败,请重试;若问题持续出现,请联系管理员。"
|
||||
return "操作未完成,请稍后重试。"
|
||||
|
||||
|
||||
class PageHeader(QWidget):
|
||||
"""Reference-design page heading with breadcrumb, copy and actions."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
title: str,
|
||||
subtitle: str = "",
|
||||
parent: QWidget | None = None,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("PageHeader")
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.setSpacing(8)
|
||||
|
||||
breadcrumb = QHBoxLayout()
|
||||
breadcrumb.setContentsMargins(0, 0, 0, 0)
|
||||
breadcrumb.setSpacing(7)
|
||||
home_label = QLabel("首页", self)
|
||||
home_label.setProperty("role", "breadcrumb")
|
||||
breadcrumb.addWidget(home_label)
|
||||
separator = QLabel("›", self)
|
||||
separator.setProperty("role", "breadcrumbSeparator")
|
||||
breadcrumb.addWidget(separator)
|
||||
self.breadcrumb_label = QLabel(title, self)
|
||||
self.breadcrumb_label.setProperty("role", "breadcrumbCurrent")
|
||||
breadcrumb.addWidget(self.breadcrumb_label)
|
||||
breadcrumb.addStretch(1)
|
||||
layout.addLayout(breadcrumb)
|
||||
|
||||
heading = QHBoxLayout()
|
||||
heading.setContentsMargins(0, 0, 0, 0)
|
||||
heading.setSpacing(16)
|
||||
text_layout = QVBoxLayout()
|
||||
text_layout.setSpacing(3)
|
||||
self.title_label = QLabel(title, self)
|
||||
self.title_label.setProperty("role", "pageTitle")
|
||||
text_layout.addWidget(self.title_label)
|
||||
self.subtitle_label = QLabel(subtitle, self)
|
||||
self.subtitle_label.setProperty("role", "muted")
|
||||
self.subtitle_label.setWordWrap(True)
|
||||
self.subtitle_label.setVisible(bool(subtitle))
|
||||
text_layout.addWidget(self.subtitle_label)
|
||||
heading.addLayout(text_layout, 1)
|
||||
self.actions = QHBoxLayout()
|
||||
self.actions.setSpacing(8)
|
||||
heading.addLayout(self.actions)
|
||||
layout.addLayout(heading)
|
||||
|
||||
def add_action(self, widget: QWidget) -> QWidget:
|
||||
self.actions.addWidget(widget)
|
||||
return widget
|
||||
|
||||
def set_subtitle(self, text: str) -> None:
|
||||
self.subtitle_label.setText(text)
|
||||
self.subtitle_label.setVisible(bool(text))
|
||||
|
||||
|
||||
class MetricCard(QFrame):
|
||||
"""Compact dashboard metric used above dense business tables."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
title: str,
|
||||
value: str = "0",
|
||||
*,
|
||||
hint: str = "",
|
||||
kind: str = "accent",
|
||||
glyph: str = "",
|
||||
parent: QWidget | None = None,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("MetricCard")
|
||||
self.setProperty("kind", kind)
|
||||
self.setMinimumHeight(82)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(16, 12, 14, 12)
|
||||
layout.setSpacing(12)
|
||||
copy = QVBoxLayout()
|
||||
copy.setSpacing(3)
|
||||
title_label = QLabel(title, self)
|
||||
title_label.setProperty("role", "metricTitle")
|
||||
copy.addWidget(title_label)
|
||||
self.value_label = QLabel(str(value), self)
|
||||
self.value_label.setProperty("role", "metricValue")
|
||||
copy.addWidget(self.value_label)
|
||||
self.hint_label = QLabel(hint, self)
|
||||
self.hint_label.setProperty("role", "metricHint")
|
||||
self.hint_label.setVisible(bool(hint))
|
||||
copy.addWidget(self.hint_label)
|
||||
layout.addLayout(copy, 1)
|
||||
self.glyph_label = QLabel(glyph, self)
|
||||
self.glyph_label.setObjectName("MetricGlyph")
|
||||
self.glyph_label.setProperty("kind", kind)
|
||||
self.glyph_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.glyph_label.setFixedSize(38, 38)
|
||||
self.glyph_label.setVisible(bool(glyph))
|
||||
layout.addWidget(self.glyph_label)
|
||||
|
||||
def set_value(self, value: Any) -> None:
|
||||
self.value_label.setText(display_text(value, "0"))
|
||||
|
||||
def set_hint(self, text: str) -> None:
|
||||
self.hint_label.setText(text)
|
||||
self.hint_label.setVisible(bool(text))
|
||||
|
||||
|
||||
class StatusBadge(QLabel):
|
||||
def __init__(
|
||||
self, text: str = "", kind: str = "neutral", parent: QWidget | None = None
|
||||
) -> None:
|
||||
super().__init__(text, parent)
|
||||
self.setObjectName("StatusBadge")
|
||||
self.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Fixed)
|
||||
# QSS padding alone is not a reliable minimum on every Windows DPI
|
||||
# scale. Keep enough physical row height so badge text is never
|
||||
# squeezed into the thin coloured strip seen in list item widgets.
|
||||
self.setMinimumHeight(24)
|
||||
self.set_kind(kind)
|
||||
|
||||
def set_kind(self, kind: str) -> None:
|
||||
self.setProperty("kind", kind)
|
||||
self.style().unpolish(self)
|
||||
self.style().polish(self)
|
||||
|
||||
def set_status(self, text: str, kind: str = "neutral") -> None:
|
||||
self.setText(text)
|
||||
self.set_kind(kind)
|
||||
|
||||
|
||||
class EmptyState(QWidget):
|
||||
action_requested = Signal()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
title: str = "暂无数据",
|
||||
description: str = "调整筛选条件后再试试。",
|
||||
action_text: str = "",
|
||||
parent: QWidget | None = None,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("EmptyState")
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(24, 44, 24, 44)
|
||||
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
layout.setSpacing(8)
|
||||
glyph = QLabel("○", self)
|
||||
glyph.setObjectName("EmptyStateGlyph")
|
||||
glyph.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
glyph.setFixedSize(44, 44)
|
||||
layout.addWidget(glyph)
|
||||
title_label = QLabel(title, self)
|
||||
title_label.setProperty("role", "sectionTitle")
|
||||
title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
layout.addWidget(title_label)
|
||||
description_label = QLabel(description, self)
|
||||
description_label.setProperty("role", "muted")
|
||||
description_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
description_label.setWordWrap(True)
|
||||
layout.addWidget(description_label)
|
||||
self.action_button = QPushButton(action_text, self)
|
||||
self.action_button.setProperty("variant", "secondary")
|
||||
self.action_button.setVisible(bool(action_text))
|
||||
self.action_button.clicked.connect(self.action_requested)
|
||||
layout.addWidget(self.action_button, 0, Qt.AlignmentFlag.AlignCenter)
|
||||
|
||||
|
||||
class MessageBanner(QFrame):
|
||||
def __init__(self, text: str = "", kind: str = "info", parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("MessageBanner")
|
||||
self.setProperty("kind", kind)
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(12, 9, 12, 9)
|
||||
layout.setSpacing(9)
|
||||
self.icon = QLabel("i", self)
|
||||
self.icon.setObjectName("MessageBannerIcon")
|
||||
self.icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.icon.setFixedSize(20, 20)
|
||||
self.label = QLabel(text, self)
|
||||
self.label.setObjectName("MessageBannerText")
|
||||
self.label.setWordWrap(True)
|
||||
layout.addWidget(self.icon)
|
||||
layout.addWidget(self.label, 1)
|
||||
self.setVisible(bool(text))
|
||||
|
||||
def show_message(self, text: str, kind: str = "info") -> None:
|
||||
glyphs = {"info": "i", "success": "✓", "warning": "!", "danger": "!"}
|
||||
self.label.setText(text)
|
||||
self.icon.setText(glyphs.get(kind, "i"))
|
||||
self.setProperty("kind", kind)
|
||||
self.style().unpolish(self)
|
||||
self.style().polish(self)
|
||||
self.setVisible(bool(text))
|
||||
|
||||
def clear(self) -> None:
|
||||
self.setVisible(False)
|
||||
self.label.clear()
|
||||
|
||||
|
||||
class Toast(QLabel):
|
||||
def __init__(self, parent: QWidget) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("Toast")
|
||||
self.setWordWrap(True)
|
||||
self.setMaximumWidth(420)
|
||||
self.hide()
|
||||
self._timer = QTimer(self)
|
||||
self._timer.setSingleShot(True)
|
||||
self._timer.timeout.connect(self.hide)
|
||||
|
||||
def show_message(self, text: str, kind: str = "info", duration: int = 2800) -> None:
|
||||
self.setText(text)
|
||||
self.setProperty("kind", kind)
|
||||
self.style().unpolish(self)
|
||||
self.style().polish(self)
|
||||
self.adjustSize()
|
||||
parent = self.parentWidget()
|
||||
if parent is not None:
|
||||
self.move(max(16, parent.width() - self.width() - 24), 20)
|
||||
self.raise_()
|
||||
self.show()
|
||||
self._timer.start(duration)
|
||||
|
||||
|
||||
def show_toast(parent: QWidget, text: str, kind: str = "info", duration: int = 2800) -> None:
|
||||
window = parent.window()
|
||||
toast = getattr(window, "_doctor_workstation_toast", None)
|
||||
if not isinstance(toast, Toast):
|
||||
toast = Toast(window)
|
||||
window._doctor_workstation_toast = toast
|
||||
toast.show_message(text, kind, duration)
|
||||
|
||||
|
||||
class _BusyTrack(QWidget):
|
||||
"""Indeterminate bar painted in-process, without Windows QProgressBar HWNDs.
|
||||
|
||||
``QProgressBar.setRange(0, 0)`` uses the native Vista/Win11 animation, which
|
||||
creates extra untitled windows titled with the application name.
|
||||
"""
|
||||
|
||||
def __init__(self, parent: QWidget) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("BusyOverlayProgress")
|
||||
self.setFixedSize(140, 6)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
|
||||
self._phase = 0.0
|
||||
self._timer = QTimer(self)
|
||||
self._timer.setInterval(32)
|
||||
self._timer.timeout.connect(self._tick)
|
||||
|
||||
def showEvent(self, event: Any) -> None:
|
||||
self._timer.start()
|
||||
super().showEvent(event)
|
||||
|
||||
def hideEvent(self, event: Any) -> None:
|
||||
self._timer.stop()
|
||||
super().hideEvent(event)
|
||||
|
||||
def _tick(self) -> None:
|
||||
self._phase = (self._phase + 0.035) % 1.0
|
||||
self.update()
|
||||
|
||||
def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 - Qt API
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
rect = self.rect()
|
||||
painter.setBrush(QColor("#D8DEEA"))
|
||||
painter.drawRoundedRect(rect, 3, 3)
|
||||
chunk_width = max(36, int(rect.width() * 0.32))
|
||||
span = rect.width() + chunk_width
|
||||
x = int(self._phase * span) - chunk_width
|
||||
painter.setBrush(QColor("#4F63D9"))
|
||||
painter.drawRoundedRect(x, 0, chunk_width, rect.height(), 3, 3)
|
||||
|
||||
|
||||
class BusyOverlay(QFrame):
|
||||
"""Non-blocking visual guard for a card or page while a worker is active."""
|
||||
|
||||
def __init__(self, parent: QWidget, text: str = "正在加载…") -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("BusyOverlay")
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
layout.setSpacing(10)
|
||||
self.label = QLabel(text, self)
|
||||
self.label.setProperty("role", "muted")
|
||||
self.progress = _BusyTrack(self)
|
||||
layout.addWidget(self.label, 0, Qt.AlignmentFlag.AlignCenter)
|
||||
layout.addWidget(self.progress, 0, Qt.AlignmentFlag.AlignCenter)
|
||||
self.hide()
|
||||
|
||||
def set_message(self, text: str) -> None:
|
||||
self.label.setText(text)
|
||||
|
||||
def showEvent(self, event: Any) -> None:
|
||||
parent = self.parentWidget()
|
||||
if parent is not None:
|
||||
self.setGeometry(parent.rect())
|
||||
self.raise_()
|
||||
super().showEvent(event)
|
||||
|
||||
|
||||
class OverlayHost(QWidget):
|
||||
"""Widget base that automatically sizes a BusyOverlay child."""
|
||||
|
||||
def resizeEvent(self, event: QResizeEvent) -> None:
|
||||
overlay = getattr(self, "busy_overlay", None)
|
||||
if isinstance(overlay, BusyOverlay):
|
||||
overlay.setGeometry(self.rect())
|
||||
super().resizeEvent(event)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TableColumn:
|
||||
key: str
|
||||
title: str
|
||||
width: int = 0
|
||||
formatter: Callable[[Any, Any], str] | None = None
|
||||
alignment: Qt.AlignmentFlag = Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
|
||||
|
||||
|
||||
class SortableTable(QTableWidget):
|
||||
"""A QTableWidget that safely retains the source object after sorting."""
|
||||
|
||||
def __init__(self, columns: Sequence[TableColumn], parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.columns = list(columns)
|
||||
self.setColumnCount(len(self.columns))
|
||||
self.setHorizontalHeaderLabels([column.title for column in self.columns])
|
||||
self.setAlternatingRowColors(True)
|
||||
self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
|
||||
self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
|
||||
self.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.setSortingEnabled(True)
|
||||
self.verticalHeader().setVisible(False)
|
||||
self.horizontalHeader().setStretchLastSection(True)
|
||||
for index, column in enumerate(self.columns):
|
||||
if column.width:
|
||||
self.setColumnWidth(index, column.width)
|
||||
|
||||
def set_rows(self, rows: Iterable[Any]) -> None:
|
||||
selected_id = first_value(self.current_data(), "id", "appointment_id", default=None)
|
||||
self.setSortingEnabled(False)
|
||||
self.clearContents()
|
||||
materialized = list(rows)
|
||||
self.setRowCount(len(materialized))
|
||||
row_to_select = -1
|
||||
for row_index, row in enumerate(materialized):
|
||||
row_id = first_value(row, "id", "appointment_id", default=None)
|
||||
if selected_id is not None and row_id == selected_id:
|
||||
row_to_select = row_index
|
||||
for column_index, column in enumerate(self.columns):
|
||||
raw = get_value(row, column.key, None)
|
||||
text = column.formatter(raw, row) if column.formatter else display_text(raw)
|
||||
item = QTableWidgetItem(text)
|
||||
item.setTextAlignment(column.alignment)
|
||||
item.setData(Qt.ItemDataRole.UserRole, row)
|
||||
item.setToolTip(text if "\n" in text or len(text) > 18 else "")
|
||||
self.setItem(row_index, column_index, item)
|
||||
self.setSortingEnabled(True)
|
||||
if row_to_select >= 0:
|
||||
self.selectRow(row_to_select)
|
||||
|
||||
def current_data(self) -> Any:
|
||||
row = self.currentRow()
|
||||
if row < 0:
|
||||
return None
|
||||
item = self.item(row, 0)
|
||||
return item.data(Qt.ItemDataRole.UserRole) if item is not None else None
|
||||
|
||||
|
||||
class Pager(QWidget):
|
||||
page_changed = Signal(int)
|
||||
|
||||
def __init__(self, page_size: int = 20, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("Pager")
|
||||
self.page = 1
|
||||
self.page_size = page_size
|
||||
self.total = 0
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(0, 4, 0, 0)
|
||||
self.summary = QLabel("共 0 条")
|
||||
self.summary.setProperty("role", "muted")
|
||||
layout.addWidget(self.summary)
|
||||
layout.addStretch(1)
|
||||
self.previous = QPushButton("上一页")
|
||||
self.previous.setProperty("variant", "ghost")
|
||||
self.previous.clicked.connect(lambda: self._request(self.page - 1))
|
||||
layout.addWidget(self.previous)
|
||||
self.page_label = QLabel("1 / 1")
|
||||
self.page_label.setObjectName("PagerActive")
|
||||
self.page_label.setMinimumWidth(58)
|
||||
self.page_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
layout.addWidget(self.page_label)
|
||||
self.next = QPushButton("下一页")
|
||||
self.next.setProperty("variant", "ghost")
|
||||
self.next.clicked.connect(lambda: self._request(self.page + 1))
|
||||
layout.addWidget(self.next)
|
||||
self.update_state(1, 0)
|
||||
|
||||
@property
|
||||
def page_count(self) -> int:
|
||||
return max(1, (self.total + self.page_size - 1) // self.page_size)
|
||||
|
||||
def update_state(self, page: int, total: int) -> None:
|
||||
self.page = max(1, page)
|
||||
self.total = max(0, total)
|
||||
self.summary.setText(f"共 {self.total} 条")
|
||||
self.page_label.setText(f"{self.page} / {self.page_count}")
|
||||
self.previous.setEnabled(self.page > 1)
|
||||
self.next.setEnabled(self.page < self.page_count)
|
||||
|
||||
def _request(self, page: int) -> None:
|
||||
if 1 <= page <= self.page_count and page != self.page:
|
||||
self.page_changed.emit(page)
|
||||
|
||||
|
||||
def card_layout(card: QFrame, margins: int = 18, spacing: int = 12) -> QVBoxLayout:
|
||||
layout = QVBoxLayout(card)
|
||||
layout.setContentsMargins(margins, margins, margins, margins)
|
||||
layout.setSpacing(spacing)
|
||||
return layout
|
||||
|
||||
|
||||
def section_title(text: str, trailing: QWidget | None = None) -> QWidget:
|
||||
container = QWidget()
|
||||
layout = QHBoxLayout(container)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
title = QLabel(text)
|
||||
title.setProperty("role", "sectionTitle")
|
||||
layout.addWidget(title)
|
||||
layout.addStretch(1)
|
||||
if trailing is not None:
|
||||
layout.addWidget(trailing)
|
||||
return container
|
||||
|
||||
|
||||
def clear_layout(layout: QVBoxLayout | QHBoxLayout) -> None:
|
||||
while layout.count():
|
||||
item = layout.takeAt(0)
|
||||
widget = item.widget()
|
||||
child_layout = item.layout()
|
||||
if widget is not None:
|
||||
widget.deleteLater()
|
||||
elif child_layout is not None:
|
||||
clear_layout(child_layout) # type: ignore[arg-type]
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BusyOverlay",
|
||||
"EmptyState",
|
||||
"MessageBanner",
|
||||
"MetricCard",
|
||||
"OverlayHost",
|
||||
"PageHeader",
|
||||
"Pager",
|
||||
"SortableTable",
|
||||
"StatusBadge",
|
||||
"TableColumn",
|
||||
"Toast",
|
||||
"Worker",
|
||||
"card_layout",
|
||||
"clear_layout",
|
||||
"display_text",
|
||||
"first_value",
|
||||
"friendly_error",
|
||||
"get_value",
|
||||
"has_permission",
|
||||
"invoke",
|
||||
"page_items",
|
||||
"page_total",
|
||||
"run_async",
|
||||
"section_title",
|
||||
"set_authentication_expired_handler",
|
||||
"show_toast",
|
||||
]
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Optional video-call integration for the doctor workstation."""
|
||||
|
||||
from .launcher import (
|
||||
BackendMode,
|
||||
VideoCallLauncher,
|
||||
VideoCallRequest,
|
||||
VideoTicketError,
|
||||
launch_video_call,
|
||||
normalize_backend_ticket,
|
||||
require_supported_backend,
|
||||
)
|
||||
from .lifecycle import OrderedCallLifecycle
|
||||
|
||||
__all__ = [
|
||||
"BackendMode",
|
||||
"OrderedCallLifecycle",
|
||||
"VideoCallLauncher",
|
||||
"VideoCallRequest",
|
||||
"VideoTicketError",
|
||||
"launch_video_call",
|
||||
"normalize_backend_ticket",
|
||||
"require_supported_backend",
|
||||
]
|
||||
@@ -0,0 +1,430 @@
|
||||
"""Pure-Python contract and launcher for the optional video companion.
|
||||
|
||||
The backend is the only authority that may issue ``userSig``. This module
|
||||
normalizes that short-lived ticket and deliberately keeps Qt imports out of the
|
||||
contract layer so it remains importable in core-only installations and tests.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
class VideoTicketError(ValueError):
|
||||
"""Raised when a backend video ticket is incomplete or unsafe."""
|
||||
|
||||
|
||||
class BackendMode(StrEnum):
|
||||
"""Supported rendering backends for a video call."""
|
||||
|
||||
EMBEDDED = "embedded"
|
||||
BROWSER = "browser"
|
||||
|
||||
@classmethod
|
||||
def parse(cls, value: BackendMode | str) -> BackendMode:
|
||||
if isinstance(value, cls):
|
||||
return value
|
||||
try:
|
||||
return cls(str(value).strip().lower())
|
||||
except ValueError as exc:
|
||||
raise VideoTicketError("backend mode must be 'embedded' or 'browser'") from exc
|
||||
|
||||
|
||||
def require_supported_backend(value: BackendMode | str) -> BackendMode:
|
||||
"""Reject browser launch until a server-issued one-time handoff exists."""
|
||||
|
||||
mode = BackendMode.parse(value)
|
||||
if mode is BackendMode.BROWSER:
|
||||
raise VideoTicketError(
|
||||
"browser video mode is disabled until a server-issued one-time handoff is available"
|
||||
)
|
||||
return mode
|
||||
|
||||
|
||||
Identifier = int | str
|
||||
|
||||
|
||||
def _identifier(value: Any, field_name: str) -> Identifier:
|
||||
if isinstance(value, bool) or value is None:
|
||||
raise VideoTicketError(f"{field_name} must be a non-empty identifier")
|
||||
if isinstance(value, int):
|
||||
if value <= 0:
|
||||
raise VideoTicketError(f"{field_name} must be a positive identifier")
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
cleaned = value.strip()
|
||||
if not cleaned:
|
||||
raise VideoTicketError(f"{field_name} must be a non-empty identifier")
|
||||
return cleaned
|
||||
raise VideoTicketError(f"{field_name} must be a string or integer")
|
||||
|
||||
|
||||
def _non_empty_string(value: Any, field_name: str) -> str:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise VideoTicketError(f"{field_name} must be a non-empty string")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _sdk_app_id(value: Any, field_name: str = "SDKAppID") -> int:
|
||||
if isinstance(value, bool):
|
||||
raise VideoTicketError(f"{field_name} must be a positive integer")
|
||||
try:
|
||||
parsed = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise VideoTicketError(f"{field_name} must be a positive integer") from exc
|
||||
if parsed <= 0 or str(value).strip() != str(parsed):
|
||||
raise VideoTicketError(f"{field_name} must be a positive integer")
|
||||
return parsed
|
||||
|
||||
|
||||
def _normalized_key(key: Any) -> str:
|
||||
return "".join(character for character in str(key).lower() if character.isalnum())
|
||||
|
||||
|
||||
_FORBIDDEN_SECRET_KEYS = {"sdksecret", "sdksecretkey", "secretkey"}
|
||||
|
||||
|
||||
def _reject_server_secrets(payload: Mapping[str, Any]) -> None:
|
||||
for key in payload:
|
||||
if _normalized_key(key) in _FORBIDDEN_SECRET_KEYS:
|
||||
raise VideoTicketError("backend ticket contains forbidden server-side secret material")
|
||||
|
||||
|
||||
def _contains_ticket_fields(payload: Mapping[str, Any]) -> bool:
|
||||
keys = {_normalized_key(key) for key in payload}
|
||||
return bool(keys & {"sdkappid", "userid", "usersig", "targetuserid", "patientuserid"})
|
||||
|
||||
|
||||
def _ticket_payload(ticket: Mapping[str, Any]) -> Mapping[str, Any]:
|
||||
_reject_server_secrets(ticket)
|
||||
if _contains_ticket_fields(ticket):
|
||||
return ticket
|
||||
|
||||
for envelope_key in ("data", "result", "ticket"):
|
||||
nested = ticket.get(envelope_key)
|
||||
if isinstance(nested, Mapping):
|
||||
_reject_server_secrets(nested)
|
||||
if _contains_ticket_fields(nested):
|
||||
return nested
|
||||
return ticket
|
||||
|
||||
|
||||
def _ticket_mapping(ticket: Any) -> Mapping[str, Any]:
|
||||
"""Adapt the repository's CallTicket model without importing core models."""
|
||||
|
||||
if isinstance(ticket, Mapping):
|
||||
return ticket
|
||||
|
||||
raw = getattr(ticket, "raw", None)
|
||||
if isinstance(raw, Mapping):
|
||||
_reject_server_secrets(raw)
|
||||
|
||||
attribute_aliases = {
|
||||
"sdkAppId": "sdk_app_id",
|
||||
"userId": "user_id",
|
||||
"userSig": "user_sig",
|
||||
"patientUserId": "patient_user_id",
|
||||
"diagnosisId": "diagnosis_id",
|
||||
"patientId": "patient_id",
|
||||
"callRecordId": "call_record_id",
|
||||
}
|
||||
adapted = {
|
||||
json_name: getattr(ticket, attribute_name)
|
||||
for json_name, attribute_name in attribute_aliases.items()
|
||||
if hasattr(ticket, attribute_name)
|
||||
}
|
||||
if adapted:
|
||||
return adapted
|
||||
raise VideoTicketError("backend ticket must be a mapping or call-ticket object")
|
||||
|
||||
|
||||
def _read_aliases(
|
||||
payload: Mapping[str, Any],
|
||||
aliases: tuple[str, ...],
|
||||
field_name: str,
|
||||
converter: Callable[[Any, str], Any],
|
||||
*,
|
||||
required: bool = True,
|
||||
) -> Any:
|
||||
converted: list[Any] = []
|
||||
for alias in aliases:
|
||||
if alias in payload and payload[alias] is not None:
|
||||
converted.append(converter(payload[alias], field_name))
|
||||
|
||||
if not converted:
|
||||
if required:
|
||||
raise VideoTicketError(f"backend ticket is missing {field_name}")
|
||||
return None
|
||||
if any(value != converted[0] and str(value) != str(converted[0]) for value in converted[1:]):
|
||||
raise VideoTicketError(f"backend ticket has conflicting {field_name} aliases")
|
||||
return converted[0]
|
||||
|
||||
|
||||
def _merge_identifier(
|
||||
payload_value: Identifier | None,
|
||||
explicit_value: Any,
|
||||
field_name: str,
|
||||
) -> Identifier:
|
||||
if explicit_value is None:
|
||||
if payload_value is None:
|
||||
raise VideoTicketError(f"backend ticket is missing {field_name}")
|
||||
return payload_value
|
||||
normalized = _identifier(explicit_value, field_name)
|
||||
if (
|
||||
payload_value is not None
|
||||
and payload_value != normalized
|
||||
and str(payload_value) != str(normalized)
|
||||
):
|
||||
raise VideoTicketError(f"backend ticket conflicts with requested {field_name}")
|
||||
return normalized
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class VideoCallRequest:
|
||||
"""Validated data required to start one doctor-to-patient video call.
|
||||
|
||||
``user_sig`` is excluded from ``repr``. Use :meth:`safe_log_context` for
|
||||
structured logs; never serialize the dataclass itself into diagnostics.
|
||||
"""
|
||||
|
||||
sdk_app_id: int
|
||||
user_id: str
|
||||
user_sig: str = field(repr=False)
|
||||
target_user_id: str
|
||||
diagnosis_id: Identifier
|
||||
patient_id: Identifier | None = None
|
||||
call_record_id: Identifier | None = None
|
||||
backend_mode: BackendMode = BackendMode.EMBEDDED
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "sdk_app_id", _sdk_app_id(self.sdk_app_id))
|
||||
object.__setattr__(self, "user_id", _non_empty_string(self.user_id, "userID"))
|
||||
object.__setattr__(self, "user_sig", _non_empty_string(self.user_sig, "userSig"))
|
||||
object.__setattr__(
|
||||
self,
|
||||
"target_user_id",
|
||||
_non_empty_string(self.target_user_id, "targetUserId"),
|
||||
)
|
||||
object.__setattr__(
|
||||
self,
|
||||
"diagnosis_id",
|
||||
_identifier(self.diagnosis_id, "diagnosisId"),
|
||||
)
|
||||
if self.patient_id is not None:
|
||||
object.__setattr__(
|
||||
self,
|
||||
"patient_id",
|
||||
_identifier(self.patient_id, "patientId"),
|
||||
)
|
||||
if self.call_record_id is not None:
|
||||
object.__setattr__(
|
||||
self,
|
||||
"call_record_id",
|
||||
_identifier(self.call_record_id, "callRecordId"),
|
||||
)
|
||||
object.__setattr__(self, "backend_mode", BackendMode.parse(self.backend_mode))
|
||||
|
||||
@classmethod
|
||||
def from_backend_ticket(
|
||||
cls,
|
||||
ticket: Any,
|
||||
*,
|
||||
diagnosis_id: Any = None,
|
||||
patient_id: Any = None,
|
||||
backend_mode: BackendMode | str = BackendMode.EMBEDDED,
|
||||
) -> VideoCallRequest:
|
||||
return normalize_backend_ticket(
|
||||
ticket,
|
||||
diagnosis_id=diagnosis_id,
|
||||
patient_id=patient_id,
|
||||
backend_mode=backend_mode,
|
||||
)
|
||||
|
||||
def to_web_config(self) -> dict[str, Any]:
|
||||
"""Return the canonical JavaScript bridge payload.
|
||||
|
||||
The returned mapping contains the short-lived credential and therefore
|
||||
must only be passed in memory to the trusted companion page.
|
||||
"""
|
||||
|
||||
return {
|
||||
"SDKAppID": self.sdk_app_id,
|
||||
"userID": self.user_id,
|
||||
"userSig": self.user_sig,
|
||||
"targetUserId": self.target_user_id,
|
||||
"diagnosisId": self.diagnosis_id,
|
||||
}
|
||||
|
||||
def safe_log_context(self) -> dict[str, Any]:
|
||||
"""Return non-secret call metadata suitable for structured logging."""
|
||||
|
||||
return {
|
||||
"diagnosis_id": self.diagnosis_id,
|
||||
"patient_id": self.patient_id,
|
||||
"call_record_id": self.call_record_id,
|
||||
"backend_mode": self.backend_mode.value,
|
||||
}
|
||||
|
||||
|
||||
def normalize_backend_ticket(
|
||||
ticket: Any,
|
||||
*,
|
||||
diagnosis_id: Any = None,
|
||||
patient_id: Any = None,
|
||||
backend_mode: BackendMode | str = BackendMode.EMBEDDED,
|
||||
) -> VideoCallRequest:
|
||||
"""Normalize backend camel-case aliases into a validated call request."""
|
||||
|
||||
payload = _ticket_payload(_ticket_mapping(ticket))
|
||||
payload_diagnosis = _read_aliases(
|
||||
payload,
|
||||
("diagnosisId", "diagnosis_id"),
|
||||
"diagnosisId",
|
||||
_identifier,
|
||||
required=False,
|
||||
)
|
||||
payload_patient = _read_aliases(
|
||||
payload,
|
||||
("patientId", "patient_id"),
|
||||
"patientId",
|
||||
_identifier,
|
||||
required=False,
|
||||
)
|
||||
payload_call_record = _read_aliases(
|
||||
payload,
|
||||
("callRecordId", "call_record_id"),
|
||||
"callRecordId",
|
||||
_identifier,
|
||||
required=False,
|
||||
)
|
||||
|
||||
normalized_diagnosis = _merge_identifier(
|
||||
payload_diagnosis,
|
||||
diagnosis_id,
|
||||
"diagnosisId",
|
||||
)
|
||||
if patient_id is not None:
|
||||
normalized_patient = _merge_identifier(payload_patient, patient_id, "patientId")
|
||||
else:
|
||||
normalized_patient = payload_patient
|
||||
|
||||
return VideoCallRequest(
|
||||
sdk_app_id=_read_aliases(
|
||||
payload,
|
||||
("SDKAppID", "sdkAppId", "sdkAppID"),
|
||||
"SDKAppID",
|
||||
_sdk_app_id,
|
||||
),
|
||||
user_id=_read_aliases(
|
||||
payload,
|
||||
("userID", "userId"),
|
||||
"userID",
|
||||
_non_empty_string,
|
||||
),
|
||||
user_sig=_read_aliases(
|
||||
payload,
|
||||
("userSig", "user_sig"),
|
||||
"userSig",
|
||||
_non_empty_string,
|
||||
),
|
||||
target_user_id=_read_aliases(
|
||||
payload,
|
||||
("targetUserId", "patientUserId"),
|
||||
"targetUserId",
|
||||
_non_empty_string,
|
||||
),
|
||||
diagnosis_id=normalized_diagnosis,
|
||||
patient_id=normalized_patient,
|
||||
call_record_id=payload_call_record,
|
||||
backend_mode=BackendMode.parse(backend_mode),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class VideoCallLauncher:
|
||||
"""Small composition root that defers the optional Qt import until launch."""
|
||||
|
||||
repository: Any
|
||||
backend_mode: BackendMode | str = BackendMode.EMBEDDED
|
||||
local_dist: str | Path | None = None
|
||||
remote_url: str | None = None
|
||||
logger: Any = None
|
||||
browser_opener: Callable[[str], bool] | None = None
|
||||
|
||||
def prepare(
|
||||
self,
|
||||
ticket: Any,
|
||||
*,
|
||||
diagnosis_id: Any = None,
|
||||
patient_id: Any = None,
|
||||
) -> VideoCallRequest:
|
||||
require_supported_backend(self.backend_mode)
|
||||
return normalize_backend_ticket(
|
||||
ticket,
|
||||
diagnosis_id=diagnosis_id,
|
||||
patient_id=patient_id,
|
||||
backend_mode=self.backend_mode,
|
||||
)
|
||||
|
||||
def launch(
|
||||
self,
|
||||
ticket: Any,
|
||||
*,
|
||||
diagnosis_id: Any = None,
|
||||
patient_id: Any = None,
|
||||
open_im: bool = False,
|
||||
patient_name: str = "患者",
|
||||
) -> Any:
|
||||
request = self.prepare(
|
||||
ticket,
|
||||
diagnosis_id=diagnosis_id,
|
||||
patient_id=patient_id,
|
||||
)
|
||||
from .window import open_video_call
|
||||
|
||||
return open_video_call(
|
||||
request,
|
||||
repository=self.repository,
|
||||
local_dist=self.local_dist,
|
||||
remote_url=self.remote_url,
|
||||
logger=self.logger,
|
||||
browser_opener=self.browser_opener,
|
||||
open_im=open_im,
|
||||
patient_name=patient_name,
|
||||
)
|
||||
|
||||
|
||||
def launch_video_call(
|
||||
ticket: Any,
|
||||
*,
|
||||
repository: Any,
|
||||
diagnosis_id: Any = None,
|
||||
patient_id: Any = None,
|
||||
backend_mode: BackendMode | str = BackendMode.EMBEDDED,
|
||||
local_dist: str | Path | None = None,
|
||||
remote_url: str | None = None,
|
||||
logger: Any = None,
|
||||
browser_opener: Callable[[str], bool] | None = None,
|
||||
open_im: bool = False,
|
||||
patient_name: str = "患者",
|
||||
) -> Any:
|
||||
"""Normalize a ticket and open a call with the requested backend."""
|
||||
|
||||
return VideoCallLauncher(
|
||||
repository=repository,
|
||||
backend_mode=backend_mode,
|
||||
local_dist=local_dist,
|
||||
remote_url=remote_url,
|
||||
logger=logger,
|
||||
browser_opener=browser_opener,
|
||||
).launch(
|
||||
ticket,
|
||||
diagnosis_id=diagnosis_id,
|
||||
patient_id=patient_id,
|
||||
open_im=open_im,
|
||||
patient_name=patient_name,
|
||||
)
|
||||
@@ -0,0 +1,590 @@
|
||||
"""Ordered, non-blocking backend lifecycle writes for one video call.
|
||||
|
||||
The repository uses synchronous HTTP. A dedicated daemon worker keeps
|
||||
``start_call -> bind_call_room -> end_call`` ordered without ever blocking the
|
||||
Qt GUI thread. Only non-secret call metadata is logged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import inspect
|
||||
import logging
|
||||
import queue
|
||||
import threading
|
||||
from collections.abc import Callable, Mapping
|
||||
from concurrent.futures import Future
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, TypeVar
|
||||
|
||||
from .launcher import VideoCallRequest
|
||||
|
||||
ResultT = TypeVar("ResultT")
|
||||
|
||||
|
||||
def _settled_future(value: ResultT) -> Future[ResultT]:
|
||||
future: Future[ResultT] = Future()
|
||||
future.set_result(value)
|
||||
return future
|
||||
|
||||
|
||||
def _resolve_result(result: Any) -> Any:
|
||||
if inspect.isawaitable(result):
|
||||
return asyncio.run(result)
|
||||
return result
|
||||
|
||||
|
||||
def _call_repository_method(method: Callable[..., Any], payload: Mapping[str, Any]) -> Any:
|
||||
"""Invoke common repository signatures with a non-secret payload only."""
|
||||
|
||||
try:
|
||||
signature = inspect.signature(method)
|
||||
except (TypeError, ValueError):
|
||||
return _resolve_result(method(**payload))
|
||||
|
||||
parameters = list(signature.parameters.values())
|
||||
if any(parameter.kind is inspect.Parameter.VAR_KEYWORD for parameter in parameters):
|
||||
return _resolve_result(method(**payload))
|
||||
|
||||
keyword_names = {
|
||||
parameter.name
|
||||
for parameter in parameters
|
||||
if parameter.kind
|
||||
in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)
|
||||
}
|
||||
accepted = {key: value for key, value in payload.items() if key in keyword_names}
|
||||
required = [
|
||||
parameter
|
||||
for parameter in parameters
|
||||
if parameter.default is inspect.Parameter.empty
|
||||
and parameter.kind
|
||||
in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)
|
||||
]
|
||||
|
||||
if len(parameters) == 1 and not accepted:
|
||||
result = method(dict(payload))
|
||||
elif any(parameter.kind is inspect.Parameter.POSITIONAL_ONLY for parameter in required):
|
||||
missing = [parameter.name for parameter in required if parameter.name not in payload]
|
||||
if missing:
|
||||
raise TypeError("repository method requires unsupported positional parameters")
|
||||
ordered = [payload[parameter.name] for parameter in required]
|
||||
result = method(*ordered, **accepted)
|
||||
else:
|
||||
result = method(**accepted)
|
||||
return _resolve_result(result)
|
||||
|
||||
|
||||
def _mapping_candidate(value: Any) -> Mapping[str, Any] | None:
|
||||
if isinstance(value, Mapping):
|
||||
return value
|
||||
for attribute in ("raw", "data"):
|
||||
candidate = getattr(value, attribute, None)
|
||||
if isinstance(candidate, Mapping):
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def _extract_call_record_id(result: Any) -> int | str | None:
|
||||
"""Read a positive call-record identity from common backend envelopes."""
|
||||
|
||||
pending = [result]
|
||||
visited: set[int] = set()
|
||||
while pending:
|
||||
candidate = pending.pop(0)
|
||||
mapping = _mapping_candidate(candidate)
|
||||
if mapping is None or id(mapping) in visited:
|
||||
continue
|
||||
visited.add(id(mapping))
|
||||
for key in ("call_record_id", "callRecordId", "id"):
|
||||
value = mapping.get(key)
|
||||
if isinstance(value, bool) or value is None:
|
||||
continue
|
||||
if isinstance(value, int) and value > 0:
|
||||
return value
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
for key in ("data", "result", "record", "call_record", "callRecord"):
|
||||
nested = mapping.get(key)
|
||||
if isinstance(nested, Mapping):
|
||||
pending.append(nested)
|
||||
return None
|
||||
|
||||
|
||||
def _clean_transcript_segment(segment: Mapping[str, Any], session_id: str) -> dict[str, Any]:
|
||||
segment_id = str(segment.get("segment_id", segment.get("segmentId", ""))).strip()
|
||||
text = str(segment.get("text", segment.get("sourceText", ""))).strip()
|
||||
speaker_user_id = str(
|
||||
segment.get("speaker_user_id", segment.get("speakerUserId", ""))
|
||||
).strip()
|
||||
speaker_role = str(segment.get("speaker_role", segment.get("speakerRole", "unknown"))).strip()
|
||||
if not segment_id or len(segment_id) > 160:
|
||||
raise ValueError("transcript segment_id must contain 1 to 160 characters")
|
||||
if not text or len(text) > 4_000:
|
||||
raise ValueError("transcript text must contain 1 to 4000 characters")
|
||||
if len(speaker_user_id) > 160:
|
||||
raise ValueError("transcript speaker_user_id is too long")
|
||||
if speaker_role not in {"doctor", "patient", "unknown"}:
|
||||
speaker_role = "unknown"
|
||||
try:
|
||||
timestamp = int(segment.get("timestamp") or 0)
|
||||
except (TypeError, ValueError):
|
||||
timestamp = 0
|
||||
return {
|
||||
"segment_id": segment_id,
|
||||
"transcription_session_id": session_id,
|
||||
"speaker_user_id": speaker_user_id,
|
||||
"speaker_role": speaker_role,
|
||||
"timestamp": max(timestamp, 0),
|
||||
"text": text,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _WorkItem:
|
||||
operation: str
|
||||
callback: Callable[[], Any]
|
||||
future: Future[Any]
|
||||
|
||||
|
||||
class _OrderedDaemonWorker:
|
||||
"""A minimal FIFO executor with timeout-aware idle observation."""
|
||||
|
||||
def __init__(self, logger: logging.Logger, log_context: Mapping[str, Any]) -> None:
|
||||
self._logger = logger
|
||||
self._log_context = dict(log_context)
|
||||
self._queue: queue.Queue[_WorkItem | None] = queue.Queue()
|
||||
self._lock = threading.Lock()
|
||||
self._idle = threading.Event()
|
||||
self._idle.set()
|
||||
self._pending = 0
|
||||
self._stopping = False
|
||||
self._thread = threading.Thread(
|
||||
target=self._run,
|
||||
name="video-call-lifecycle",
|
||||
daemon=True,
|
||||
)
|
||||
self._thread.start()
|
||||
|
||||
@property
|
||||
def is_daemon(self) -> bool:
|
||||
return self._thread.daemon
|
||||
|
||||
def submit(self, operation: str, callback: Callable[[], ResultT]) -> Future[ResultT]:
|
||||
with self._lock:
|
||||
if self._stopping:
|
||||
raise RuntimeError("video lifecycle worker is stopping")
|
||||
future: Future[ResultT] = Future()
|
||||
self._pending += 1
|
||||
self._idle.clear()
|
||||
self._queue.put(_WorkItem(operation, callback, future))
|
||||
return future
|
||||
|
||||
def stop_when_idle(self) -> None:
|
||||
with self._lock:
|
||||
if self._stopping:
|
||||
return
|
||||
self._stopping = True
|
||||
self._queue.put(None)
|
||||
|
||||
def wait(self, timeout: float = 0.25) -> bool:
|
||||
bounded = max(0.0, min(float(timeout), 5.0))
|
||||
return self._idle.wait(bounded)
|
||||
|
||||
def _run(self) -> None:
|
||||
while True:
|
||||
item = self._queue.get()
|
||||
if item is None:
|
||||
self._queue.task_done()
|
||||
return
|
||||
try:
|
||||
if item.future.set_running_or_notify_cancel():
|
||||
try:
|
||||
item.future.set_result(item.callback())
|
||||
except BaseException as error:
|
||||
item.future.set_exception(error)
|
||||
self._logger.error(
|
||||
"video lifecycle operation failed",
|
||||
extra={
|
||||
"video_call": self._log_context,
|
||||
"operation": item.operation,
|
||||
"error_type": type(error).__name__,
|
||||
},
|
||||
)
|
||||
finally:
|
||||
with self._lock:
|
||||
self._pending -= 1
|
||||
if self._pending == 0:
|
||||
self._idle.set()
|
||||
self._queue.task_done()
|
||||
|
||||
|
||||
class OrderedCallLifecycle:
|
||||
"""Idempotent lifecycle state machine backed by one FIFO daemon worker."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
request: VideoCallRequest,
|
||||
repository: Any,
|
||||
logger: logging.Logger,
|
||||
) -> None:
|
||||
if repository is None:
|
||||
raise ValueError("a video call repository is required")
|
||||
self.request = request
|
||||
self.repository = repository
|
||||
self.logger = logger
|
||||
self.started = False
|
||||
self.ended = False
|
||||
self.call_record_id: int | str | None = request.call_record_id
|
||||
self.bound_room_id: str | None = None
|
||||
self._claimed_room_id: str | None = None
|
||||
self._start_future: Future[bool] | None = None
|
||||
self._bind_future: Future[bool] | None = None
|
||||
self._end_future: Future[bool] | None = None
|
||||
self._transcription_start_future: Future[bool] | None = None
|
||||
self._transcription_finish_future: Future[bool] | None = None
|
||||
self._transcription_session_id: str | None = None
|
||||
self._transcription_active = False
|
||||
self._segment_futures: dict[str, Future[bool]] = {}
|
||||
self._lock = threading.RLock()
|
||||
self._worker = _OrderedDaemonWorker(logger, request.safe_log_context())
|
||||
|
||||
@property
|
||||
def worker_is_daemon(self) -> bool:
|
||||
return self._worker.is_daemon
|
||||
|
||||
@property
|
||||
def transcription_session_id(self) -> str | None:
|
||||
return self._transcription_session_id
|
||||
|
||||
def start(self) -> Future[bool]:
|
||||
with self._lock:
|
||||
if self._start_future is not None:
|
||||
return self._start_future
|
||||
method = getattr(self.repository, "start_call", None)
|
||||
if not callable(method):
|
||||
raise ValueError("video repository does not implement start_call")
|
||||
payload: dict[str, Any] = {
|
||||
"diagnosis_id": self.request.diagnosis_id,
|
||||
"call_type": 2,
|
||||
}
|
||||
if self.request.patient_id is not None:
|
||||
payload["patient_id"] = self.request.patient_id
|
||||
|
||||
def operation() -> bool:
|
||||
result = _call_repository_method(method, payload)
|
||||
record_id = _extract_call_record_id(result)
|
||||
if record_id is None:
|
||||
raise ValueError("startCall response did not include the current call_record_id")
|
||||
with self._lock:
|
||||
self.started = True
|
||||
self.call_record_id = record_id
|
||||
self.logger.info(
|
||||
"video call record started",
|
||||
extra={"video_call": self.request.safe_log_context()},
|
||||
)
|
||||
return True
|
||||
|
||||
self._start_future = self._worker.submit("start", operation)
|
||||
return self._start_future
|
||||
|
||||
def bind_room(self, room_id: Any) -> Future[bool]:
|
||||
cleaned = str(room_id or "").strip()
|
||||
if not cleaned or cleaned == "0":
|
||||
return _settled_future(False)
|
||||
|
||||
with self._lock:
|
||||
if self._end_future is not None:
|
||||
return _settled_future(False)
|
||||
if self.bound_room_id:
|
||||
if self.bound_room_id != cleaned:
|
||||
self.logger.warning(
|
||||
"ignoring a changed TRTC room identifier",
|
||||
extra={"video_call": self.request.safe_log_context()},
|
||||
)
|
||||
return _settled_future(self.bound_room_id == cleaned)
|
||||
if self._claimed_room_id:
|
||||
if self._claimed_room_id != cleaned:
|
||||
self.logger.warning(
|
||||
"ignoring a changed TRTC room identifier",
|
||||
extra={"video_call": self.request.safe_log_context()},
|
||||
)
|
||||
return _settled_future(False)
|
||||
return self._bind_future or _settled_future(False)
|
||||
if self._start_future is None:
|
||||
self.start()
|
||||
self._claimed_room_id = cleaned
|
||||
method = getattr(self.repository, "bind_call_room", None)
|
||||
|
||||
def operation() -> bool:
|
||||
with self._lock:
|
||||
started = self.started
|
||||
if not started:
|
||||
return False
|
||||
if not callable(method):
|
||||
self.logger.warning(
|
||||
"video repository does not implement bind_call_room",
|
||||
extra={"video_call": self.request.safe_log_context()},
|
||||
)
|
||||
return False
|
||||
_call_repository_method(
|
||||
method,
|
||||
{"diagnosis_id": self.request.diagnosis_id, "room_id": cleaned},
|
||||
)
|
||||
with self._lock:
|
||||
self.bound_room_id = cleaned
|
||||
self.logger.info(
|
||||
"TRTC room bound to video call record",
|
||||
extra={"video_call": self.request.safe_log_context()},
|
||||
)
|
||||
return True
|
||||
|
||||
self._bind_future = self._worker.submit("bind", operation)
|
||||
return self._bind_future
|
||||
|
||||
def save_screenshot(self, content: bytes, filename: str) -> Future[str]:
|
||||
"""Upload one video frame and append it to the diagnosis doctor notes."""
|
||||
|
||||
if not content:
|
||||
raise ValueError("screenshot content must not be empty")
|
||||
if len(content) > 10 * 1024 * 1024:
|
||||
raise ValueError("screenshot content exceeds 10 MB")
|
||||
clean_name = str(filename or "callshot.jpg").strip() or "callshot.jpg"
|
||||
with self._lock:
|
||||
if self._end_future is not None:
|
||||
raise RuntimeError("video call has already ended")
|
||||
upload = getattr(self.repository, "upload_material_bytes", None)
|
||||
add_note = getattr(self.repository, "add_doctor_note", None)
|
||||
if not callable(upload) or not callable(add_note):
|
||||
raise ValueError("video repository does not implement screenshot storage")
|
||||
|
||||
def operation() -> str:
|
||||
reference = str(
|
||||
_call_repository_method(
|
||||
upload,
|
||||
{
|
||||
"content": content,
|
||||
"filename": clean_name,
|
||||
"material_type": "image",
|
||||
"cid": 0,
|
||||
},
|
||||
)
|
||||
or ""
|
||||
).strip()
|
||||
if not reference:
|
||||
raise ValueError("screenshot upload returned no server reference")
|
||||
_call_repository_method(
|
||||
add_note,
|
||||
{
|
||||
"diagnosis_id": self.request.diagnosis_id,
|
||||
"content": "",
|
||||
"tongue_images": [reference],
|
||||
},
|
||||
)
|
||||
self.logger.info(
|
||||
"video screenshot stored in doctor notes",
|
||||
extra={"video_call": self.request.safe_log_context()},
|
||||
)
|
||||
return reference
|
||||
|
||||
return self._worker.submit("screenshot", operation)
|
||||
|
||||
def start_transcription(self, session_id: str, *, language: str = "zh-CN") -> Future[bool]:
|
||||
"""Start persisted realtime transcription for this exact call record."""
|
||||
|
||||
clean_session = str(session_id or "").strip()
|
||||
clean_language = str(language or "zh-CN").strip()[:32] or "zh-CN"
|
||||
if not clean_session or len(clean_session) > 128:
|
||||
raise ValueError("transcription session id must contain 1 to 128 characters")
|
||||
with self._lock:
|
||||
if self._end_future is not None:
|
||||
raise RuntimeError("video call has already ended")
|
||||
if self._transcription_start_future is not None:
|
||||
if self._transcription_session_id != clean_session:
|
||||
raise RuntimeError("another transcription session already exists")
|
||||
return self._transcription_start_future
|
||||
if self._start_future is None:
|
||||
self.start()
|
||||
method = getattr(self.repository, "start_call_transcription", None)
|
||||
if not callable(method):
|
||||
raise ValueError("video repository does not implement call transcription storage")
|
||||
self._transcription_session_id = clean_session
|
||||
|
||||
def operation() -> bool:
|
||||
with self._lock:
|
||||
started = self.started
|
||||
record_id = self.call_record_id
|
||||
if not started:
|
||||
return False
|
||||
if record_id is None:
|
||||
raise ValueError("server did not return the current call_record_id")
|
||||
_call_repository_method(
|
||||
method,
|
||||
{
|
||||
"diagnosis_id": self.request.diagnosis_id,
|
||||
"call_record_id": record_id,
|
||||
"transcription_session_id": clean_session,
|
||||
"language": clean_language,
|
||||
},
|
||||
)
|
||||
with self._lock:
|
||||
self._transcription_active = True
|
||||
self.logger.info(
|
||||
"video call transcription started",
|
||||
extra={"video_call": self.request.safe_log_context()},
|
||||
)
|
||||
return True
|
||||
|
||||
self._transcription_start_future = self._worker.submit(
|
||||
"transcription-start", operation
|
||||
)
|
||||
return self._transcription_start_future
|
||||
|
||||
def save_transcript_segment(self, segment: Mapping[str, Any]) -> Future[bool]:
|
||||
"""Upsert one completed, bounded transcript segment without logging its text."""
|
||||
|
||||
with self._lock:
|
||||
session_id = self._transcription_session_id
|
||||
if not session_id or self._transcription_start_future is None:
|
||||
raise RuntimeError("call transcription has not started")
|
||||
if self._transcription_finish_future is not None:
|
||||
raise RuntimeError("call transcription has already stopped")
|
||||
cleaned = _clean_transcript_segment(segment, session_id)
|
||||
segment_id = cleaned["segment_id"]
|
||||
existing = self._segment_futures.get(segment_id)
|
||||
if existing is not None:
|
||||
return existing
|
||||
method = getattr(self.repository, "upsert_call_transcript_segments", None)
|
||||
if not callable(method):
|
||||
raise ValueError("video repository does not implement transcript segment storage")
|
||||
|
||||
def operation() -> bool:
|
||||
with self._lock:
|
||||
active = self._transcription_active
|
||||
record_id = self.call_record_id
|
||||
if not active:
|
||||
return False
|
||||
if record_id is None:
|
||||
raise ValueError("server did not return the current call_record_id")
|
||||
_call_repository_method(
|
||||
method,
|
||||
{
|
||||
"diagnosis_id": self.request.diagnosis_id,
|
||||
"call_record_id": record_id,
|
||||
"transcription_session_id": session_id,
|
||||
"segments": [cleaned],
|
||||
},
|
||||
)
|
||||
return True
|
||||
|
||||
future = self._worker.submit("transcription-segment", operation)
|
||||
self._segment_futures[segment_id] = future
|
||||
|
||||
def release_failed(completed: Future[bool]) -> None:
|
||||
if completed.cancelled() or completed.exception() is not None:
|
||||
with self._lock:
|
||||
if self._segment_futures.get(segment_id) is completed:
|
||||
self._segment_futures.pop(segment_id, None)
|
||||
|
||||
future.add_done_callback(release_failed)
|
||||
return future
|
||||
|
||||
def finish_transcription(self, *, status: str = "completed") -> Future[bool]:
|
||||
"""Flush and finalize the current transcript exactly once."""
|
||||
|
||||
clean_status = str(status or "completed").strip().lower()
|
||||
if clean_status not in {"completed", "partial", "failed"}:
|
||||
raise ValueError("transcription status is invalid")
|
||||
with self._lock:
|
||||
if self._transcription_finish_future is not None:
|
||||
return self._transcription_finish_future
|
||||
if self._transcription_start_future is None or not self._transcription_session_id:
|
||||
return _settled_future(False)
|
||||
method = getattr(self.repository, "finish_call_transcription", None)
|
||||
if not callable(method):
|
||||
raise ValueError("video repository does not implement transcription finalization")
|
||||
session_id = self._transcription_session_id
|
||||
|
||||
def operation() -> bool:
|
||||
with self._lock:
|
||||
active = self._transcription_active
|
||||
record_id = self.call_record_id
|
||||
expected_count = len(self._segment_futures)
|
||||
if not active:
|
||||
return False
|
||||
if record_id is None:
|
||||
raise ValueError("server did not return the current call_record_id")
|
||||
_call_repository_method(
|
||||
method,
|
||||
{
|
||||
"diagnosis_id": self.request.diagnosis_id,
|
||||
"call_record_id": record_id,
|
||||
"transcription_session_id": session_id,
|
||||
"expected_segment_count": expected_count,
|
||||
"status": clean_status,
|
||||
},
|
||||
)
|
||||
with self._lock:
|
||||
self._transcription_active = False
|
||||
self.logger.info(
|
||||
"video call transcription finalized",
|
||||
extra={
|
||||
"video_call": self.request.safe_log_context(),
|
||||
"transcription_status": clean_status,
|
||||
"segment_count": expected_count,
|
||||
},
|
||||
)
|
||||
return True
|
||||
|
||||
self._transcription_finish_future = self._worker.submit(
|
||||
"transcription-finish", operation
|
||||
)
|
||||
return self._transcription_finish_future
|
||||
|
||||
def end(self, reason: str) -> Future[bool]:
|
||||
with self._lock:
|
||||
if self._end_future is not None:
|
||||
return self._end_future
|
||||
if (
|
||||
self._transcription_start_future is not None
|
||||
and self._transcription_finish_future is None
|
||||
):
|
||||
self.finish_transcription(status="partial")
|
||||
method = getattr(self.repository, "end_call", None)
|
||||
|
||||
def operation() -> bool:
|
||||
with self._lock:
|
||||
started = self.started
|
||||
if not started:
|
||||
with self._lock:
|
||||
self.ended = True
|
||||
return False
|
||||
if not callable(method):
|
||||
raise ValueError("video repository does not implement end_call")
|
||||
_call_repository_method(
|
||||
method,
|
||||
{"diagnosis_id": self.request.diagnosis_id},
|
||||
)
|
||||
with self._lock:
|
||||
self.ended = True
|
||||
self.logger.info(
|
||||
"video call record ended",
|
||||
extra={
|
||||
"video_call": {
|
||||
**self.request.safe_log_context(),
|
||||
"reason": str(reason)[:80],
|
||||
}
|
||||
},
|
||||
)
|
||||
return True
|
||||
|
||||
self._end_future = self._worker.submit("end", operation)
|
||||
self._end_future.add_done_callback(lambda _future: self._worker.stop_when_idle())
|
||||
return self._end_future
|
||||
|
||||
def wait(self, timeout: float = 0.25) -> bool:
|
||||
"""Wait for queued writes for at most five seconds; never waits indefinitely."""
|
||||
|
||||
return self._worker.wait(timeout)
|
||||
|
||||
|
||||
__all__ = ["OrderedCallLifecycle"]
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Pure-Python trust policy for the embedded video companion document."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
from urllib.request import url2pathname
|
||||
|
||||
|
||||
class TrustedDocumentError(ValueError):
|
||||
"""Raised when a companion location cannot form a safe allowlist."""
|
||||
|
||||
|
||||
def _normalized_host(host: str | None) -> str:
|
||||
if not host:
|
||||
return ""
|
||||
try:
|
||||
return host.encode("idna").decode("ascii").lower()
|
||||
except UnicodeError:
|
||||
return host.lower()
|
||||
|
||||
|
||||
def _normalized_file_path(value: str) -> str | None:
|
||||
parsed = urlsplit(value)
|
||||
if parsed.scheme.lower() != "file" or parsed.netloc not in {"", "localhost"}:
|
||||
return None
|
||||
path = Path(url2pathname(unquote(parsed.path))).resolve()
|
||||
rendered = str(path)
|
||||
return rendered.casefold() if os.name == "nt" else rendered
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TrustedDocumentPolicy:
|
||||
"""Exact main-document allowlist plus origin matching for media grants."""
|
||||
|
||||
scheme: str
|
||||
host: str
|
||||
port: int | None
|
||||
path: str
|
||||
query: str
|
||||
local_path: str | None = None
|
||||
|
||||
@classmethod
|
||||
def from_url(cls, url: str, *, is_local: bool) -> TrustedDocumentPolicy:
|
||||
parsed = urlsplit(url)
|
||||
scheme = parsed.scheme.lower()
|
||||
if is_local:
|
||||
local_path = _normalized_file_path(url)
|
||||
if local_path is None:
|
||||
raise TrustedDocumentError("local video companion must be a file URL")
|
||||
return cls("file", "", None, parsed.path, parsed.query, local_path)
|
||||
if scheme != "https" or not parsed.hostname:
|
||||
raise TrustedDocumentError("remote embedded video companion must use HTTPS")
|
||||
if parsed.username or parsed.password:
|
||||
raise TrustedDocumentError("remote embedded video companion must not use credentials")
|
||||
try:
|
||||
port = parsed.port or 443
|
||||
except ValueError as error:
|
||||
raise TrustedDocumentError(
|
||||
"remote embedded video companion has an invalid port"
|
||||
) from error
|
||||
return cls(
|
||||
"https",
|
||||
_normalized_host(parsed.hostname),
|
||||
port,
|
||||
parsed.path or "/",
|
||||
parsed.query,
|
||||
)
|
||||
|
||||
def allows_main_document(self, candidate: str) -> bool:
|
||||
"""Allow only the configured file or HTTPS document, including its query."""
|
||||
|
||||
parsed = urlsplit(candidate)
|
||||
if self.scheme == "file":
|
||||
return (
|
||||
parsed.query == self.query and _normalized_file_path(candidate) == self.local_path
|
||||
)
|
||||
try:
|
||||
port = parsed.port or (443 if parsed.scheme.lower() == "https" else None)
|
||||
except ValueError:
|
||||
return False
|
||||
return (
|
||||
parsed.scheme.lower() == self.scheme
|
||||
and _normalized_host(parsed.hostname) == self.host
|
||||
and port == self.port
|
||||
and (parsed.path or "/") == self.path
|
||||
and parsed.query == self.query
|
||||
)
|
||||
|
||||
def allows_origin(self, candidate: str) -> bool:
|
||||
"""Match only the origin that supplied the trusted main document."""
|
||||
|
||||
parsed = urlsplit(candidate)
|
||||
if self.scheme == "file":
|
||||
return parsed.scheme.lower() == "file" and parsed.netloc in {"", "localhost"}
|
||||
try:
|
||||
port = parsed.port or (443 if parsed.scheme.lower() == "https" else None)
|
||||
except ValueError:
|
||||
return False
|
||||
return (
|
||||
parsed.scheme.lower() == self.scheme
|
||||
and _normalized_host(parsed.hostname) == self.host
|
||||
and port == self.port
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["TrustedDocumentError", "TrustedDocumentPolicy"]
|
||||
@@ -0,0 +1,837 @@
|
||||
"""Hardened QtWebEngine host for the video companion.
|
||||
|
||||
Browser launch is intentionally disabled until the backend provides a
|
||||
single-use handoff ticket. PySide6 remains optional at import time, while an
|
||||
actual call requires an isolated QtWebEngine profile and an active QApplication.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from collections.abc import Callable, Mapping
|
||||
from concurrent.futures import Future
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qsl, urlsplit
|
||||
|
||||
from .launcher import (
|
||||
VideoCallRequest,
|
||||
VideoTicketError,
|
||||
require_supported_backend,
|
||||
)
|
||||
from .lifecycle import OrderedCallLifecycle
|
||||
from .security import TrustedDocumentError, TrustedDocumentPolicy
|
||||
|
||||
try: # Optional by design: core-only builds must still import this module.
|
||||
from PySide6.QtCore import QObject, Qt, QUrl, Signal, Slot
|
||||
from PySide6.QtWebChannel import QWebChannel
|
||||
from PySide6.QtWebEngineCore import (
|
||||
QWebEnginePage,
|
||||
QWebEngineProfile,
|
||||
QWebEngineSettings,
|
||||
)
|
||||
from PySide6.QtWebEngineWidgets import QWebEngineView
|
||||
from PySide6.QtWidgets import QApplication, QMainWindow
|
||||
except (ImportError, OSError) as _qt_import_error: # pragma: no cover - no Qt runtime.
|
||||
QObject = Qt = QUrl = Signal = Slot = None # type: ignore[assignment]
|
||||
QWebChannel = QWebEnginePage = QWebEngineProfile = None # type: ignore[assignment]
|
||||
QWebEngineSettings = QWebEngineView = None # type: ignore[assignment]
|
||||
QApplication = QMainWindow = None # type: ignore[assignment]
|
||||
_WEBENGINE_IMPORT_ERROR: Exception | None = _qt_import_error
|
||||
else: # pragma: no cover - requires a GUI runtime.
|
||||
_WEBENGINE_IMPORT_ERROR = None
|
||||
|
||||
|
||||
WEBENGINE_AVAILABLE = _WEBENGINE_IMPORT_ERROR is None
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_SENSITIVE_QUERY_KEYS = {"usersig", "sdksecret", "sdksecretkey", "secretkey"}
|
||||
|
||||
|
||||
class VideoWindowError(RuntimeError):
|
||||
"""Raised when the trusted embedded companion cannot be opened."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CompanionLocation:
|
||||
url: str
|
||||
is_local: bool
|
||||
|
||||
|
||||
def _validate_remote_url(value: str) -> str:
|
||||
parsed = urlsplit(value)
|
||||
if parsed.scheme.lower() != "https" or not parsed.hostname:
|
||||
raise VideoWindowError("remote video companion URL must use HTTPS")
|
||||
if parsed.username or parsed.password:
|
||||
raise VideoWindowError("remote video companion URL must not contain credentials")
|
||||
url_parameter_keys = {
|
||||
"".join(character for character in key.lower() if character.isalnum())
|
||||
for key, _ in (*parse_qsl(parsed.query), *parse_qsl(parsed.fragment))
|
||||
}
|
||||
if url_parameter_keys & _SENSITIVE_QUERY_KEYS:
|
||||
raise VideoWindowError("remote video companion URL must not contain RTC credentials")
|
||||
return value
|
||||
|
||||
|
||||
def _candidate_index(local_dist: str | Path) -> Path:
|
||||
candidate = Path(local_dist).expanduser().resolve()
|
||||
return candidate if candidate.name.lower() == "index.html" else candidate / "index.html"
|
||||
|
||||
|
||||
def _default_local_indexes() -> tuple[Path, ...]:
|
||||
candidates: list[Path] = []
|
||||
bundle_root = getattr(sys, "_MEIPASS", None)
|
||||
if bundle_root:
|
||||
candidates.append(Path(bundle_root) / "video_companion_dist" / "index.html")
|
||||
project_root = Path(__file__).resolve().parents[3]
|
||||
candidates.append(project_root / "video_companion" / "dist" / "index.html")
|
||||
return tuple(candidates)
|
||||
|
||||
|
||||
def resolve_companion_location(
|
||||
*,
|
||||
local_dist: str | Path | None = None,
|
||||
remote_url: str | None = None,
|
||||
) -> CompanionLocation:
|
||||
"""Resolve the trusted document used inside QtWebEngine."""
|
||||
|
||||
indexes = (
|
||||
(_candidate_index(local_dist),) if local_dist is not None else _default_local_indexes()
|
||||
)
|
||||
for index in indexes:
|
||||
if index.is_file():
|
||||
return CompanionLocation(index.as_uri(), is_local=True)
|
||||
if remote_url:
|
||||
return CompanionLocation(_validate_remote_url(remote_url), is_local=False)
|
||||
raise VideoWindowError(
|
||||
"video companion is unavailable: build video_companion/dist or configure an HTTPS URL"
|
||||
)
|
||||
|
||||
|
||||
def webengine_unavailable_reason() -> str | None:
|
||||
"""Return a non-sensitive diagnostic reason without importing Qt again."""
|
||||
|
||||
if _WEBENGINE_IMPORT_ERROR is None:
|
||||
return None
|
||||
return f"{type(_WEBENGINE_IMPORT_ERROR).__name__}: QtWebEngine is not installed"
|
||||
|
||||
|
||||
if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration test.
|
||||
|
||||
class _RestrictedWebEnginePage(QWebEnginePage): # type: ignore[misc, valid-type]
|
||||
def __init__(
|
||||
self,
|
||||
profile: Any,
|
||||
policy: TrustedDocumentPolicy,
|
||||
logger: logging.Logger,
|
||||
parent: Any,
|
||||
) -> None:
|
||||
super().__init__(profile, parent)
|
||||
self._policy = policy
|
||||
self._logger = logger
|
||||
self._shutting_down = False
|
||||
|
||||
def begin_shutdown(self) -> None:
|
||||
self._shutting_down = True
|
||||
|
||||
def acceptNavigationRequest(
|
||||
self,
|
||||
url: Any,
|
||||
navigation_type: Any,
|
||||
is_main_frame: bool,
|
||||
) -> bool:
|
||||
del navigation_type
|
||||
if not is_main_frame:
|
||||
return True
|
||||
rendered = url.toString()
|
||||
if self._shutting_down and rendered == "about:blank":
|
||||
return True
|
||||
if self._policy.allows_main_document(rendered):
|
||||
return True
|
||||
self._logger.warning(
|
||||
"blocked video companion main-document navigation",
|
||||
extra={
|
||||
"target_scheme": url.scheme(),
|
||||
"target_host": url.host(),
|
||||
},
|
||||
)
|
||||
return False
|
||||
|
||||
def createWindow(self, window_type: Any) -> Any:
|
||||
del window_type
|
||||
self._logger.warning("blocked video companion popup window")
|
||||
return None
|
||||
|
||||
class _QtVideoBridge(QObject): # type: ignore[misc, valid-type]
|
||||
def __init__(self, callback: Callable[[Mapping[str, Any]], None]) -> None:
|
||||
super().__init__()
|
||||
self._callback = callback
|
||||
|
||||
@Slot(str) # type: ignore[misc]
|
||||
def notify(self, payload: str) -> None:
|
||||
if not isinstance(payload, str) or len(payload) > 16_384:
|
||||
return
|
||||
try:
|
||||
message = json.loads(payload)
|
||||
except (TypeError, ValueError):
|
||||
return
|
||||
if isinstance(message, Mapping) and message.get("source") == "doctor-call":
|
||||
self._callback(message)
|
||||
|
||||
@Slot(str) # type: ignore[misc]
|
||||
def saveScreenshot(self, data_url: str) -> None: # noqa: N802 - Qt bridge API
|
||||
"""Forward one bounded JPEG data URL to the trusted desktop host."""
|
||||
|
||||
if not isinstance(data_url, str) or len(data_url) > 14 * 1024 * 1024:
|
||||
self._callback(
|
||||
{
|
||||
"source": "doctor-call",
|
||||
"event": "screenshot-invalid",
|
||||
"message": "截屏图片过大,无法保存。",
|
||||
}
|
||||
)
|
||||
return
|
||||
self._callback(
|
||||
{
|
||||
"source": "doctor-call",
|
||||
"event": "screenshot",
|
||||
"dataUrl": data_url,
|
||||
}
|
||||
)
|
||||
|
||||
class _EmbeddedVideoWindow(QMainWindow): # type: ignore[misc, valid-type]
|
||||
status_changed = Signal(str) # type: ignore[misc]
|
||||
call_ended = Signal(str) # type: ignore[misc]
|
||||
call_error = Signal(str) # type: ignore[misc]
|
||||
_start_completed = Signal(bool) # type: ignore[misc]
|
||||
_screenshot_completed = Signal(bool, str) # type: ignore[misc]
|
||||
_transcription_completed = Signal(str, str, str, bool, str) # type: ignore[misc]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
request: VideoCallRequest,
|
||||
location: CompanionLocation,
|
||||
lifecycle: OrderedCallLifecycle,
|
||||
*,
|
||||
logger: logging.Logger,
|
||||
lifecycle_factory: Callable[[], OrderedCallLifecycle],
|
||||
open_im: bool = False,
|
||||
patient_name: str = "患者",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.request = request
|
||||
self.location = location
|
||||
self.lifecycle = lifecycle
|
||||
self._lifecycle_factory = lifecycle_factory
|
||||
self._lifecycles = [lifecycle]
|
||||
self.logger = logger
|
||||
self.open_im = bool(open_im)
|
||||
self.patient_name = str(patient_name or "患者").strip() or "患者"
|
||||
try:
|
||||
self._policy = TrustedDocumentPolicy.from_url(
|
||||
location.url,
|
||||
is_local=location.is_local,
|
||||
)
|
||||
except TrustedDocumentError as error:
|
||||
raise VideoWindowError(str(error)) from error
|
||||
self._injected = False
|
||||
self._media_active = False
|
||||
self._closing = False
|
||||
self._companion_ended = False
|
||||
self._released = False
|
||||
self._close_reason = "window-closed"
|
||||
self._call_cycle_closed = False
|
||||
self._start_requested = False
|
||||
self._legacy_grants: list[tuple[Any, Any]] = []
|
||||
self._permission_grants: list[Any] = []
|
||||
|
||||
self.setWindowTitle(
|
||||
f"与 {self.patient_name} IM 问诊" if self.open_im else "视频面诊"
|
||||
)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True)
|
||||
self.resize(1120, 760)
|
||||
self.setMinimumSize(760, 520)
|
||||
|
||||
self._profile = QWebEngineProfile(self)
|
||||
if not self._profile.isOffTheRecord():
|
||||
raise VideoWindowError("video WebEngine profile must be off-the-record")
|
||||
profile_policy = QWebEngineProfile.PersistentCookiesPolicy
|
||||
cache_type = QWebEngineProfile.HttpCacheType
|
||||
self._profile.setPersistentCookiesPolicy(profile_policy.NoPersistentCookies)
|
||||
self._profile.setHttpCacheType(cache_type.MemoryHttpCache)
|
||||
self._profile.downloadRequested.connect(self._deny_download)
|
||||
|
||||
self.web_view = QWebEngineView(self)
|
||||
self._page = _RestrictedWebEnginePage(
|
||||
self._profile,
|
||||
self._policy,
|
||||
self.logger,
|
||||
self.web_view,
|
||||
)
|
||||
self.web_view.setPage(self._page)
|
||||
self.setCentralWidget(self.web_view)
|
||||
|
||||
self._configure_settings(self._page.settings())
|
||||
self._bridge = _QtVideoBridge(self._handle_bridge_message)
|
||||
self._channel = QWebChannel(self._page)
|
||||
self._channel.registerObject("qtVideoBridge", self._bridge)
|
||||
self._page.setWebChannel(self._channel)
|
||||
self._connect_permissions()
|
||||
|
||||
self._start_completed.connect(self._on_lifecycle_started)
|
||||
self._screenshot_completed.connect(self._on_screenshot_completed)
|
||||
self._transcription_completed.connect(self._on_transcription_completed)
|
||||
self.web_view.loadFinished.connect(self._on_load_finished)
|
||||
self.web_view.setUrl(QUrl(self.location.url))
|
||||
|
||||
def _configure_settings(self, settings: Any) -> None:
|
||||
attributes = getattr(QWebEngineSettings, "WebAttribute", QWebEngineSettings)
|
||||
values = (
|
||||
("LocalContentCanAccessRemoteUrls", self.location.is_local),
|
||||
("PlaybackRequiresUserGesture", False),
|
||||
("JavascriptCanOpenWindows", False),
|
||||
("AllowRunningInsecureContent", False),
|
||||
)
|
||||
for name, enabled in values:
|
||||
attribute = getattr(attributes, name, None)
|
||||
if attribute is not None:
|
||||
settings.setAttribute(attribute, enabled)
|
||||
|
||||
def _connect_permissions(self) -> None:
|
||||
if hasattr(self._page, "featurePermissionRequested"):
|
||||
self._page.featurePermissionRequested.connect(self._grant_legacy_media_permission)
|
||||
if hasattr(self._page, "permissionRequested"):
|
||||
self._page.permissionRequested.connect(self._grant_media_permission)
|
||||
|
||||
def _permission_context_is_trusted(self, origin: Any) -> bool:
|
||||
if self._closing or self._released or not self._media_active:
|
||||
return False
|
||||
if not self._policy.allows_main_document(self._page.url().toString()):
|
||||
return False
|
||||
return self._policy.allows_origin(origin.toString())
|
||||
|
||||
def _grant_legacy_media_permission(self, origin: Any, feature: Any) -> None:
|
||||
features = QWebEnginePage.Feature
|
||||
allowed = {
|
||||
features.MediaAudioCapture,
|
||||
features.MediaVideoCapture,
|
||||
features.MediaAudioVideoCapture,
|
||||
}
|
||||
policies = QWebEnginePage.PermissionPolicy
|
||||
trusted = self._permission_context_is_trusted(origin) and feature in allowed
|
||||
policy = (
|
||||
policies.PermissionGrantedByUser if trusted else policies.PermissionDeniedByUser
|
||||
)
|
||||
self._page.setFeaturePermission(origin, feature, policy)
|
||||
if trusted:
|
||||
self._legacy_grants.append((origin, feature))
|
||||
|
||||
def _grant_media_permission(self, permission: Any) -> None:
|
||||
permission_type = permission.permissionType()
|
||||
allowed_names = {
|
||||
"MediaAudioCapture",
|
||||
"MediaVideoCapture",
|
||||
"MediaAudioVideoCapture",
|
||||
}
|
||||
trusted = (
|
||||
permission.isValid()
|
||||
and permission_type.name in allowed_names
|
||||
and self._permission_context_is_trusted(permission.origin())
|
||||
)
|
||||
if trusted:
|
||||
permission.grant()
|
||||
self._permission_grants.append(permission)
|
||||
else:
|
||||
permission.deny()
|
||||
|
||||
def _deny_download(self, download: Any) -> None:
|
||||
download.cancel()
|
||||
|
||||
def _on_load_finished(self, succeeded: bool) -> None:
|
||||
if self._closing:
|
||||
return
|
||||
if not succeeded:
|
||||
self.logger.error(
|
||||
"embedded video companion failed to load",
|
||||
extra={"video_call": self.request.safe_log_context()},
|
||||
)
|
||||
self._close_reason = "page-load-failed"
|
||||
self.close()
|
||||
return
|
||||
|
||||
self._media_active = True
|
||||
config = {
|
||||
**self.request.to_web_config(),
|
||||
"patientName": self.patient_name,
|
||||
"mode": "chat" if self.open_im else "video",
|
||||
}
|
||||
config_json = json.dumps(config, ensure_ascii=True, separators=(",", ":"))
|
||||
script = f"""
|
||||
(() => {{
|
||||
if (!window.doctorConsultation
|
||||
|| typeof window.doctorConsultation.open !== 'function') {{
|
||||
return false;
|
||||
}}
|
||||
void window.doctorConsultation.open({config_json}).catch(() => undefined);
|
||||
return true;
|
||||
}})()
|
||||
"""
|
||||
self._page.runJavaScript(script, self._after_injection)
|
||||
|
||||
def _notify_start_completed(self, future: Future[bool]) -> None:
|
||||
try:
|
||||
succeeded = bool(future.result())
|
||||
except Exception:
|
||||
succeeded = False
|
||||
with suppress(RuntimeError):
|
||||
self._start_completed.emit(succeeded)
|
||||
|
||||
def _on_lifecycle_started(self, succeeded: bool) -> None:
|
||||
if self._closing:
|
||||
return
|
||||
if not succeeded:
|
||||
self._start_requested = False
|
||||
self._call_cycle_closed = True
|
||||
self._page.runJavaScript(
|
||||
"window.doctorConsultation?.hostCallReady?.(false, "
|
||||
'"通话记录创建失败,请稍后重试。");'
|
||||
)
|
||||
return
|
||||
self._page.runJavaScript(
|
||||
"window.doctorConsultation?.hostCallReady?.(true, '');"
|
||||
)
|
||||
|
||||
def _after_injection(self, result: Any) -> None:
|
||||
self._injected = result is not False
|
||||
if not self._injected:
|
||||
self._close_reason = "bridge-api-missing"
|
||||
self.close()
|
||||
|
||||
def _handle_bridge_message(self, message: Mapping[str, Any]) -> None:
|
||||
if self._closing:
|
||||
return
|
||||
event = str(message.get("event", ""))
|
||||
if event == "call-start-request":
|
||||
self._start_call_cycle()
|
||||
return
|
||||
if event == "screenshot":
|
||||
self._save_screenshot(str(message.get("dataUrl") or ""))
|
||||
return
|
||||
if event == "screenshot-invalid":
|
||||
self._on_screenshot_completed(
|
||||
False,
|
||||
str(message.get("message") or "截屏图片无效。")[:200],
|
||||
)
|
||||
return
|
||||
if event == "transcription-start-request":
|
||||
self._start_transcription(
|
||||
str(message.get("sessionId") or ""),
|
||||
str(message.get("language") or "zh-CN"),
|
||||
)
|
||||
return
|
||||
if event == "transcription-segment":
|
||||
self._save_transcript_segment(message)
|
||||
return
|
||||
if event == "transcription-stop":
|
||||
self._finish_transcription(
|
||||
str(message.get("sessionId") or ""),
|
||||
str(message.get("status") or "completed"),
|
||||
)
|
||||
return
|
||||
room_id = message.get("roomId", message.get("room_id"))
|
||||
if room_id not in (None, ""):
|
||||
self.lifecycle.bind_room(room_id)
|
||||
if event == "room":
|
||||
return
|
||||
if event == "status":
|
||||
status = str(message.get("status", "unknown"))[:80]
|
||||
self.status_changed.emit(status)
|
||||
elif event == "hangup":
|
||||
status = str(message.get("status", "ended"))[:80]
|
||||
self.call_ended.emit(status)
|
||||
self.lifecycle.end(f"companion-{status}")
|
||||
self._call_cycle_closed = True
|
||||
self._start_requested = False
|
||||
if not self.open_im:
|
||||
self._close_from_companion("companion-hangup")
|
||||
elif event == "error":
|
||||
message_text = str(message.get("message", "视频通话错误"))[:400]
|
||||
self.call_error.emit(message_text)
|
||||
if self._start_requested:
|
||||
self.lifecycle.end("companion-error")
|
||||
self._call_cycle_closed = True
|
||||
self._start_requested = False
|
||||
if not self.open_im:
|
||||
self._close_from_companion("companion-error")
|
||||
|
||||
def _start_call_cycle(self) -> None:
|
||||
if self._closing or self._start_requested:
|
||||
return
|
||||
if self._call_cycle_closed:
|
||||
self.lifecycle = self._lifecycle_factory()
|
||||
self._lifecycles.append(self.lifecycle)
|
||||
self._call_cycle_closed = False
|
||||
self._start_requested = True
|
||||
try:
|
||||
future = self.lifecycle.start()
|
||||
except Exception:
|
||||
self._start_requested = False
|
||||
self._on_lifecycle_started(False)
|
||||
return
|
||||
future.add_done_callback(self._notify_start_completed)
|
||||
|
||||
def _save_screenshot(self, data_url: str) -> None:
|
||||
prefix = "data:image/jpeg;base64,"
|
||||
if not data_url.startswith(prefix):
|
||||
self._on_screenshot_completed(False, "截屏图片格式不正确。")
|
||||
return
|
||||
try:
|
||||
content = base64.b64decode(data_url[len(prefix) :], validate=True)
|
||||
except (ValueError, binascii.Error):
|
||||
self._on_screenshot_completed(False, "截屏图片解析失败。")
|
||||
return
|
||||
try:
|
||||
future = self.lifecycle.save_screenshot(
|
||||
content,
|
||||
f"callshot-{self.request.diagnosis_id}.jpg",
|
||||
)
|
||||
except Exception as error:
|
||||
self._on_screenshot_completed(False, str(error)[:200])
|
||||
return
|
||||
future.add_done_callback(self._notify_screenshot_completed)
|
||||
|
||||
def _notify_screenshot_completed(self, future: Future[str]) -> None:
|
||||
try:
|
||||
future.result()
|
||||
except Exception as error:
|
||||
succeeded = False
|
||||
message = str(error)[:200] or "截屏保存失败。"
|
||||
else:
|
||||
succeeded = True
|
||||
message = "截屏已保存到患者信息。"
|
||||
with suppress(RuntimeError):
|
||||
self._screenshot_completed.emit(succeeded, message)
|
||||
|
||||
def _on_screenshot_completed(self, succeeded: bool, message: str) -> None:
|
||||
payload = json.dumps(str(message)[:200], ensure_ascii=True)
|
||||
state = "true" if succeeded else "false"
|
||||
self._page.runJavaScript(
|
||||
f"window.doctorConsultation?.screenshotResult?.({state}, {payload});"
|
||||
)
|
||||
|
||||
def _notify_transcription_completed(
|
||||
self,
|
||||
operation: str,
|
||||
session_id: str,
|
||||
segment_id: str,
|
||||
future: Future[bool],
|
||||
) -> None:
|
||||
try:
|
||||
succeeded = bool(future.result())
|
||||
except Exception as error:
|
||||
succeeded = False
|
||||
message = str(error)[:200] or "录音文字保存失败。"
|
||||
else:
|
||||
message = {
|
||||
"start": "录音文字存储已准备。",
|
||||
"segment": "",
|
||||
"stop": "本次面诊对话文字已保存。",
|
||||
}.get(operation, "")
|
||||
with suppress(RuntimeError):
|
||||
self._transcription_completed.emit(
|
||||
operation, session_id, segment_id, succeeded, message
|
||||
)
|
||||
|
||||
def _on_transcription_completed(
|
||||
self,
|
||||
operation: str,
|
||||
session_id: str,
|
||||
segment_id: str,
|
||||
succeeded: bool,
|
||||
message: str,
|
||||
) -> None:
|
||||
payload = json.dumps(str(message)[:200], ensure_ascii=True)
|
||||
state = "true" if succeeded else "false"
|
||||
self._page.runJavaScript(
|
||||
"window.doctorConsultation?.transcriptionResult?.("
|
||||
f"{json.dumps(operation)}, {json.dumps(session_id)}, "
|
||||
f"{json.dumps(segment_id)}, {state}, {payload});"
|
||||
)
|
||||
|
||||
def _start_transcription(self, session_id: str, language: str) -> None:
|
||||
try:
|
||||
future = self.lifecycle.start_transcription(session_id, language=language)
|
||||
except Exception as error:
|
||||
self._on_transcription_completed(
|
||||
"start", session_id, "", False, str(error)[:200]
|
||||
)
|
||||
return
|
||||
future.add_done_callback(
|
||||
lambda completed: self._notify_transcription_completed(
|
||||
"start", session_id, "", completed
|
||||
)
|
||||
)
|
||||
|
||||
def _save_transcript_segment(self, message: Mapping[str, Any]) -> None:
|
||||
session_id = str(message.get("sessionId") or "").strip()
|
||||
segment = message.get("segment")
|
||||
segment_id = (
|
||||
str(segment.get("segment_id") or segment.get("segmentId") or "").strip()
|
||||
if isinstance(segment, Mapping)
|
||||
else ""
|
||||
)
|
||||
if not isinstance(segment, Mapping):
|
||||
self._on_transcription_completed(
|
||||
"segment", session_id, segment_id, False, "录音文字片段无效。"
|
||||
)
|
||||
return
|
||||
if session_id != str(self.lifecycle.transcription_session_id or ""):
|
||||
self._on_transcription_completed(
|
||||
"segment", session_id, segment_id, False, "录音会话标识不匹配。"
|
||||
)
|
||||
return
|
||||
try:
|
||||
future = self.lifecycle.save_transcript_segment(segment)
|
||||
except Exception as error:
|
||||
self._on_transcription_completed(
|
||||
"segment", session_id, segment_id, False, str(error)[:200]
|
||||
)
|
||||
return
|
||||
future.add_done_callback(
|
||||
lambda completed: self._notify_transcription_completed(
|
||||
"segment", session_id, segment_id, completed
|
||||
)
|
||||
)
|
||||
|
||||
def _finish_transcription(self, session_id: str, status: str) -> None:
|
||||
if session_id.strip() != str(self.lifecycle.transcription_session_id or ""):
|
||||
self._on_transcription_completed(
|
||||
"stop", session_id, "", False, "录音会话标识不匹配。"
|
||||
)
|
||||
return
|
||||
try:
|
||||
future = self.lifecycle.finish_transcription(status=status)
|
||||
except Exception as error:
|
||||
self._on_transcription_completed(
|
||||
"stop", session_id, "", False, str(error)[:200]
|
||||
)
|
||||
return
|
||||
future.add_done_callback(
|
||||
lambda completed: self._notify_transcription_completed(
|
||||
"stop", session_id, "", completed
|
||||
)
|
||||
)
|
||||
|
||||
def _close_from_companion(self, reason: str) -> None:
|
||||
self._companion_ended = True
|
||||
self._close_reason = reason
|
||||
self.close()
|
||||
|
||||
def hangup(self) -> None:
|
||||
self._close_reason = "desktop-hangup"
|
||||
self.close()
|
||||
|
||||
def _begin_shutdown(self) -> None:
|
||||
if self._closing:
|
||||
return
|
||||
self._closing = True
|
||||
self._media_active = False
|
||||
if self._injected and not self._companion_ended and not self._released:
|
||||
self._page.runJavaScript(
|
||||
"void window.doctorConsultation?.close?.().catch(() => undefined)"
|
||||
)
|
||||
if self._start_requested and not self._call_cycle_closed:
|
||||
self.lifecycle.end(self._close_reason)
|
||||
self._release_webengine()
|
||||
|
||||
def wait_for_lifecycles(self, timeout: float) -> bool:
|
||||
return all(lifecycle.wait(timeout) for lifecycle in self._lifecycles)
|
||||
|
||||
def _release_webengine(self) -> None:
|
||||
if self._released:
|
||||
return
|
||||
self._released = True
|
||||
policies = QWebEnginePage.PermissionPolicy
|
||||
for origin, feature in self._legacy_grants:
|
||||
with suppress(RuntimeError):
|
||||
self._page.setFeaturePermission(
|
||||
origin,
|
||||
feature,
|
||||
policies.PermissionDeniedByUser,
|
||||
)
|
||||
self._legacy_grants.clear()
|
||||
for permission in self._permission_grants:
|
||||
try:
|
||||
if permission.isValid():
|
||||
permission.reset()
|
||||
except RuntimeError:
|
||||
pass
|
||||
self._permission_grants.clear()
|
||||
|
||||
try:
|
||||
self._channel.deregisterObject(self._bridge)
|
||||
self._page.setWebChannel(None)
|
||||
except RuntimeError:
|
||||
pass
|
||||
try:
|
||||
self._profile.cookieStore().deleteAllCookies()
|
||||
self._profile.clearHttpCache()
|
||||
self._profile.clearAllVisitedLinks()
|
||||
except RuntimeError:
|
||||
pass
|
||||
try:
|
||||
self._page.begin_shutdown()
|
||||
self._page.setUrl(QUrl("about:blank"))
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
view = self.takeCentralWidget()
|
||||
if view is not None:
|
||||
view.close()
|
||||
view.deleteLater()
|
||||
self._page.deleteLater()
|
||||
self._profile.deleteLater()
|
||||
|
||||
def closeEvent(self, event: Any) -> None:
|
||||
self._begin_shutdown()
|
||||
event.accept()
|
||||
|
||||
|
||||
else:
|
||||
_EmbeddedVideoWindow = None # type: ignore[assignment, misc]
|
||||
|
||||
|
||||
class VideoCallWindow:
|
||||
"""Facade for the only currently supported backend: embedded QtWebEngine."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
request: VideoCallRequest,
|
||||
*,
|
||||
repository: Any,
|
||||
local_dist: str | Path | None = None,
|
||||
remote_url: str | None = None,
|
||||
logger: logging.Logger | None = None,
|
||||
browser_opener: Callable[[str], bool] | None = None,
|
||||
open_im: bool = False,
|
||||
patient_name: str = "患者",
|
||||
) -> None:
|
||||
del browser_opener # Reserved for a future authenticated handoff implementation.
|
||||
try:
|
||||
self.backend_mode = require_supported_backend(request.backend_mode)
|
||||
except VideoTicketError as error:
|
||||
raise VideoWindowError(str(error)) from error
|
||||
if not WEBENGINE_AVAILABLE:
|
||||
raise VideoWindowError(
|
||||
"embedded video is unavailable and automatic browser fallback is disabled"
|
||||
)
|
||||
if QApplication is None or QApplication.instance() is None:
|
||||
raise VideoWindowError("embedded video requires an active QApplication")
|
||||
|
||||
self.request = request
|
||||
self.repository = repository
|
||||
self.open_im = bool(open_im)
|
||||
self.patient_name = str(patient_name or "患者").strip() or "患者"
|
||||
self.logger = logger or _LOGGER
|
||||
self.location = resolve_companion_location(
|
||||
local_dist=local_dist,
|
||||
remote_url=remote_url,
|
||||
)
|
||||
self.lifecycle = OrderedCallLifecycle(request, repository, self.logger)
|
||||
self._lifecycles = [self.lifecycle]
|
||||
self._session: Any = None
|
||||
|
||||
def _new_lifecycle(self) -> OrderedCallLifecycle:
|
||||
lifecycle = OrderedCallLifecycle(self.request, self.repository, self.logger)
|
||||
self._lifecycles.append(lifecycle)
|
||||
return lifecycle
|
||||
|
||||
@property
|
||||
def qt_window(self) -> Any:
|
||||
return self._session
|
||||
|
||||
def open(self) -> VideoCallWindow:
|
||||
try:
|
||||
self._session = _EmbeddedVideoWindow(
|
||||
self.request,
|
||||
self.location,
|
||||
self.lifecycle,
|
||||
logger=self.logger,
|
||||
lifecycle_factory=self._new_lifecycle,
|
||||
open_im=self.open_im,
|
||||
patient_name=self.patient_name,
|
||||
)
|
||||
except Exception:
|
||||
self.lifecycle.end("window-open-failed")
|
||||
raise
|
||||
self._session.show()
|
||||
self._session.raise_()
|
||||
self._session.activateWindow()
|
||||
return self
|
||||
|
||||
show = open
|
||||
|
||||
def hangup(self) -> None:
|
||||
if self._session is not None:
|
||||
self._session.hangup()
|
||||
else:
|
||||
self.lifecycle.end("unopened-session")
|
||||
|
||||
def close(self) -> None:
|
||||
if self._session is not None:
|
||||
self._session.close()
|
||||
else:
|
||||
self.lifecycle.end("unopened-session")
|
||||
|
||||
def wait_for_lifecycle(self, timeout: float = 0.25) -> bool:
|
||||
"""Wait briefly for ordered backend writes; timeout is capped at five seconds."""
|
||||
|
||||
if self._session is not None:
|
||||
return self._session.wait_for_lifecycles(timeout)
|
||||
return all(lifecycle.wait(timeout) for lifecycle in self._lifecycles)
|
||||
|
||||
wait = wait_for_lifecycle
|
||||
|
||||
|
||||
def open_video_call(
|
||||
request: VideoCallRequest,
|
||||
*,
|
||||
repository: Any,
|
||||
local_dist: str | Path | None = None,
|
||||
remote_url: str | None = None,
|
||||
logger: logging.Logger | None = None,
|
||||
browser_opener: Callable[[str], bool] | None = None,
|
||||
open_im: bool = False,
|
||||
patient_name: str = "患者",
|
||||
) -> VideoCallWindow:
|
||||
"""Create and immediately open a trusted embedded video window."""
|
||||
|
||||
if not isinstance(request, VideoCallRequest):
|
||||
raise VideoTicketError("request must be a VideoCallRequest")
|
||||
return VideoCallWindow(
|
||||
request,
|
||||
repository=repository,
|
||||
local_dist=local_dist,
|
||||
remote_url=remote_url,
|
||||
logger=logger,
|
||||
browser_opener=browser_opener,
|
||||
open_im=open_im,
|
||||
patient_name=patient_name,
|
||||
).open()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CompanionLocation",
|
||||
"TrustedDocumentPolicy",
|
||||
"VideoCallWindow",
|
||||
"VideoWindowError",
|
||||
"WEBENGINE_AVAILABLE",
|
||||
"open_video_call",
|
||||
"resolve_companion_location",
|
||||
"webengine_unavailable_reason",
|
||||
]
|
||||
Reference in New Issue
Block a user