diff --git a/app/src/doctor_workstation/app.py b/app/src/doctor_workstation/app.py index 86c065a3e..9a1c09da5 100755 --- a/app/src/doctor_workstation/app.py +++ b/app/src/doctor_workstation/app.py @@ -893,10 +893,16 @@ class ApplicationController(QObject): raise ValueError("当前后端未提供一次性通话交接票据,浏览器视频模式已安全停用。") if not WEBENGINE_AVAILABLE: raise ValueError("当前安装缺少 QtWebEngine,无法打开受信任的视频窗口。") + ticket_diag = getattr(ticket, "diagnosis_id", None) + resolved_diag_id = ( + ticket_diag + if not isinstance(ticket_diag, bool) and ticket_diag not in (None, "", 0, "0") + else diagnosis_id + ) call = launch_video_call( ticket, repository=repository, - diagnosis_id=diagnosis_id, + diagnosis_id=resolved_diag_id, patient_id=patient_id, backend_mode=mode, local_dist=video_dist_path(), @@ -910,7 +916,7 @@ class ApplicationController(QObject): "tcm.diagnosis/aiAssistant", default=False, ), - on_open_diagnosis=lambda current_id=diagnosis_id, current_key=call_key: ( + on_open_diagnosis=lambda *_args, current_id=resolved_diag_id, current_key=call_key: ( self._open_video_diagnosis(current_id, call_key=current_key) ), ) @@ -926,6 +932,37 @@ class ApplicationController(QObject): self.video_calls[call_key] = call qt_window = getattr(call, "qt_window", None) if qt_window is not None: + qt_window.setProperty("doctorSkipOpenGeometry", True) + qt_window.setMinimumSize(420, 480) + if self.shell_window is not None and self.shell_window.isVisible(): + screen = self.shell_window.screen() + if screen is not None: + avail = screen.availableGeometry() + if getattr(self, "_saved_shell_before_video", None) is None: + self._saved_shell_before_video = ( + self.shell_window.isMaximized(), + self.shell_window.geometry(), + self.shell_window.minimumSize(), + ) + pad = 6 + gap = 8 + # Account for Windows native frame borders on qt_window so right edge never clips + frame_w_extra = max(12, qt_window.frameGeometry().width() - qt_window.width()) + frame_h_extra = max(34, qt_window.frameGeometry().height() - qt_window.height()) + usable_w = avail.width() - pad * 2 - gap + vid_outer_w = min(540, max(436, int(usable_w * 0.34))) + main_w = max(820, usable_w - vid_outer_w) + if main_w + vid_outer_w > usable_w: + vid_outer_w = max(420, usable_w - main_w) + vid_client_w = max(420, vid_outer_w - frame_w_extra) + usable_h = avail.height() - pad * 2 + vid_client_h = max(480, usable_h - frame_h_extra) + if self.shell_window.isMaximized(): + self.shell_window.showNormal() + self.shell_window.setMinimumSize(min(820, main_w), 620) + self.shell_window.setGeometry(avail.left() + pad, avail.top() + pad, main_w, usable_h) + qt_window.resize(vid_client_w, vid_client_h) + qt_window.move(avail.left() + pad + main_w + gap, avail.top() + pad) qt_window.destroyed.connect( lambda _obj=None, key=call_key, expected=call: self._release_video_call( key, @@ -942,6 +979,10 @@ class ApplicationController(QObject): dialog = shell.open_diagnosis_by_id(diagnosis_id, modeless=True) if dialog is None: return + if bool(dialog.property("hostedInSpatialWing")) or getattr(shell, "wing_manager", None) is not None: + shell.raise_() + shell.activateWindow() + return call = self.video_calls.get(call_key) video_window = getattr(call, "qt_window", None) if video_window is not None: @@ -1052,6 +1093,16 @@ class ApplicationController(QObject): self._video_preview_generation += 1 if self.video_calls.get(call_key) is call: self.video_calls.pop(call_key, None) + saved_shell = getattr(self, "_saved_shell_before_video", None) + if not self.video_calls and saved_shell is not None and self.shell_window is not None: + self._saved_shell_before_video = None + was_max, old_rect, old_min = saved_shell + with suppress(RuntimeError): + self.shell_window.setMinimumSize(old_min) + if was_max: + self.shell_window.showMaximized() + elif old_rect.isValid(): + self.shell_window.setGeometry(old_rect) def _forget_demo_dialog(self, call_key: str, dialog: DemoVideoDialog) -> None: if self.demo_video_dialogs.get(call_key) is dialog: diff --git a/app/src/doctor_workstation/ui/appointment_drawer.py b/app/src/doctor_workstation/ui/appointment_drawer.py index 922050a81..9ba383712 100755 --- a/app/src/doctor_workstation/ui/appointment_drawer.py +++ b/app/src/doctor_workstation/ui/appointment_drawer.py @@ -1714,6 +1714,9 @@ class AppointmentDrawer(QDialog): QTimer.singleShot(0, self._sync_to_owner) def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 - Qt API + if self.property('hostedInSpatialWing'): + super().paintEvent(event) + return painter = QPainter(self) painter.fillRect(self.rect(), QColor(26, 28, 31, 196)) painter.end() @@ -1760,6 +1763,9 @@ class AppointmentDrawer(QDialog): super().mousePressEvent(event) def _sync_to_owner(self) -> None: + if self.property('hostedInSpatialWing'): + self._update_drawer_width() + return target = main_window_target_rect(self) if target is not None: self.setGeometry(target) @@ -1775,6 +1781,10 @@ class AppointmentDrawer(QDialog): def _update_drawer_width(self) -> None: if not hasattr(self, "panel"): return + if self.property('hostedInSpatialWing'): + self.panel.setMinimumWidth(0) + self.panel.setMaximumWidth(16777215) + return target = max(1, int(round(self.width() * 0.60))) self.panel.setFixedWidth(target) diff --git a/app/src/doctor_workstation/ui/command_palette.py b/app/src/doctor_workstation/ui/command_palette.py index d34e48ef0..fe12fa036 100644 --- a/app/src/doctor_workstation/ui/command_palette.py +++ b/app/src/doctor_workstation/ui/command_palette.py @@ -165,6 +165,7 @@ class CommandPaletteDialog(QDialog): super().__init__(parent) self.setObjectName("CommandPaletteDialog") self.setProperty("doctorSkipOpenGeometry", True) + self.setProperty("skipSpatialWing", True) self.setWindowFlags( Qt.WindowType.FramelessWindowHint | Qt.WindowType.Dialog diff --git a/app/src/doctor_workstation/ui/diagnosis_drawer.py b/app/src/doctor_workstation/ui/diagnosis_drawer.py index 1262d8635..62cff2207 100755 --- a/app/src/doctor_workstation/ui/diagnosis_drawer.py +++ b/app/src/doctor_workstation/ui/diagnosis_drawer.py @@ -1,16 +1,16 @@ -"""Scoped visual primitives for diagnosis readonly pages and edit drawers. - -The diagnosis workspace uses the same cool white, indigo and blue-gray visual -language as the desktop shell. Every rule remains isolated behind diagnosis -object names and dynamic properties so adjacent pages keep their own styling. -""" +"""Scoped visual primitives for diagnosis readonly pages and edit drawers. + +The diagnosis workspace uses the same cool white, indigo and blue-gray visual +language as the desktop shell. Every rule remains isolated behind diagnosis +object names and dynamic properties so adjacent pages keep their own styling. +""" from __future__ import annotations -import weakref -from collections.abc import Mapping, Sequence -from dataclasses import dataclass -from math import ceil +import weakref +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from math import ceil from typing import Any from PySide6.QtCore import ( @@ -63,12 +63,12 @@ from PySide6.QtWidgets import ( QWidget, ) -from .chat_items import ChatItem, parse_chat_item -from .design_system import PALETTE, clinical_stylesheet -from .diagnosis_editors import FlowLayout +from .chat_items import ChatItem, parse_chat_item +from .design_system import PALETTE, clinical_stylesheet +from .diagnosis_editors import FlowLayout from .diagnosis_media import shared_image_manager from .diagnosis_terms import FIELD_DICTIONARIES, format_timestamp, shared_terms -from .image_drop import can_drop_images, capture_image_drop +from .image_drop import can_drop_images, capture_image_drop DIAGNOSIS_QSS = r""" QDialog#DiagnosisDialogRoot { @@ -82,7 +82,7 @@ QFrame#DiagnosisDrawer { border-left: 1px solid #EDEDEE; } QFrame#DiagnosisDrawerHeader { - background-color: #FFFFFF; + background-color: #FFFFFF; border-bottom: 1px solid #EDEDEE; } QFrame#DiagnosisDrawerFooter { @@ -104,7 +104,7 @@ QLabel#DiagnosisDrawerModeBadge, QLabel#DiagnosisReadonlyStatus, QLabel[diagnosisTag="true"] { padding: 4px 9px; - border-radius: $ds_radius_small; + border-radius: $ds_radius_small; font-size: 12px; font-weight: 500; } @@ -158,8 +158,8 @@ QDialog QPushButton:pressed { border-color: #354BB4; } QDialog QPushButton:disabled { - color: $ds_disabled; - background-color: $ds_disabled_surface; + color: $ds_disabled; + background-color: $ds_disabled_surface; border-color: #EDEDEE; } QDialog QPushButton[variant="primary"] { @@ -175,9 +175,9 @@ QDialog QPushButton[variant="primary"]:focus { border-color: #4156C4; } QDialog QPushButton[variant="primary"]:disabled { - color: $ds_disabled; - background-color: $ds_disabled_surface; - border-color: $ds_line; + color: $ds_disabled; + background-color: $ds_disabled_surface; + border-color: $ds_line; } QDialog QPushButton[variant="secondary"] { color: #4F63D9; @@ -266,9 +266,9 @@ QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:focus { border-color: #4156C4; } QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:disabled { - color: $ds_disabled; - background-color: $ds_disabled_surface; - border-color: $ds_line; + color: $ds_disabled; + background-color: $ds_disabled_surface; + border-color: $ds_line; } QDialog#DiagnosisDialogRoot QPushButton#DiagnosisFooterCloseButton { color: #606163; @@ -382,10 +382,10 @@ QFrame#DiagnosisFormHost { QFrame[diagnosisSection="true"] { background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 16px; + border-radius: 16px; } QLabel[diagnosisFieldLabel="true"] { - color: $ds_muted; + color: $ds_muted; font-size: 12px; font-weight: 500; } @@ -397,11 +397,11 @@ QLabel#DiagnosisUnitLabel { } QLineEdit[diagnosisField="true"], QComboBox[diagnosisField="true"], -QPlainTextEdit[diagnosisField="true"], -QDateEdit[diagnosisField="true"], -QDoubleSpinBox[diagnosisField="true"], -QSpinBox[diagnosisField="true"], -QTimeEdit[diagnosisField="true"] { +QPlainTextEdit[diagnosisField="true"], +QDateEdit[diagnosisField="true"], +QDoubleSpinBox[diagnosisField="true"], +QSpinBox[diagnosisField="true"], +QTimeEdit[diagnosisField="true"] { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; @@ -434,13 +434,13 @@ QPlainTextEdit[diagnosisField="true"] { } QLineEdit[diagnosisField="true"]:focus, QComboBox[diagnosisField="true"]:focus, -QPlainTextEdit[diagnosisField="true"]:focus, -QDateEdit[diagnosisField="true"]:focus, -QDoubleSpinBox[diagnosisField="true"]:focus, -QSpinBox[diagnosisField="true"]:focus, -QTimeEdit[diagnosisField="true"]:focus { +QPlainTextEdit[diagnosisField="true"]:focus, +QDateEdit[diagnosisField="true"]:focus, +QDoubleSpinBox[diagnosisField="true"]:focus, +QSpinBox[diagnosisField="true"]:focus, +QTimeEdit[diagnosisField="true"]:focus { border: 1px solid #8B9AD9; - background-color: $ds_surface; + background-color: $ds_surface; } QLineEdit[diagnosisField="true"][invalid="true"], QComboBox[diagnosisField="true"][invalid="true"], @@ -452,11 +452,11 @@ QLineEdit[diagnosisField="true"]:read-only, QPlainTextEdit[diagnosisField="true"]:read-only, QLineEdit[diagnosisField="true"]:disabled, QComboBox[diagnosisField="true"]:disabled, -QPlainTextEdit[diagnosisField="true"]:disabled, -QDateEdit[diagnosisField="true"]:disabled, -QDoubleSpinBox[diagnosisField="true"]:disabled, -QSpinBox[diagnosisField="true"]:disabled, -QTimeEdit[diagnosisField="true"]:disabled { +QPlainTextEdit[diagnosisField="true"]:disabled, +QDateEdit[diagnosisField="true"]:disabled, +QDoubleSpinBox[diagnosisField="true"]:disabled, +QSpinBox[diagnosisField="true"]:disabled, +QTimeEdit[diagnosisField="true"]:disabled { color: #606163; background-color: #F7F7F7; border-color: #EDEDEE; @@ -466,8 +466,8 @@ QLabel#DiagnosisSectionTitle { background-color: transparent; border: 0; padding: 0; - font-size: 14px; - font-weight: 600; + font-size: 14px; + font-weight: 600; letter-spacing: 0.02em; } QFrame#DiagnosisSectionAccent { @@ -484,49 +484,49 @@ QFrame#DiagnosisReadonlyPage { background-color: #F6F6F6; } QFrame#DiagnosisReadonlyHero { - background-color: $ds_surface; - border: 1px solid $ds_line; - border-radius: $ds_radius_panel; + background-color: $ds_surface; + border: 1px solid $ds_line; + border-radius: $ds_radius_panel; } QLabel#DiagnosisReadonlyTitle { color: #1A1C1F; font-size: 16px; font-weight: 500; } -QLabel#DiagnosisReadonlyPatientName { - color: #1A1C1F; - font-size: 18px; - font-weight: 600; -} -QLabel#DiagnosisReadonlyHeroMeta, -QLabel#DiagnosisPrivacyText, -QLabel#DiagnosisOrderOffsetPreview, -QLabel#DiagnosisOrdersSummary { - color: #606163; - font-size: 12px; -} -QLabel#DiagnosisOrderOffsetLabel { - color: #1A1C1F; - font-size: 13px; - font-weight: 500; -} -QPushButton#DiagnosisOrderOffsetHelp { - min-width: 22px; - max-width: 22px; - min-height: 22px; - max-height: 22px; - padding: 0; - color: #4F63D9; - background-color: #EEF1FA; - border: 1px solid #EEF1FA; - border-radius: 11px; - font-weight: 700; -} -QPushButton#DiagnosisOrderOffsetHelp:hover, -QPushButton#DiagnosisOrderOffsetHelp:focus { - background-color: #EEF1FA; - border-color: #8B9AD9; -} +QLabel#DiagnosisReadonlyPatientName { + color: #1A1C1F; + font-size: 18px; + font-weight: 600; +} +QLabel#DiagnosisReadonlyHeroMeta, +QLabel#DiagnosisPrivacyText, +QLabel#DiagnosisOrderOffsetPreview, +QLabel#DiagnosisOrdersSummary { + color: #606163; + font-size: 12px; +} +QLabel#DiagnosisOrderOffsetLabel { + color: #1A1C1F; + font-size: 13px; + font-weight: 500; +} +QPushButton#DiagnosisOrderOffsetHelp { + min-width: 22px; + max-width: 22px; + min-height: 22px; + max-height: 22px; + padding: 0; + color: #4F63D9; + background-color: #EEF1FA; + border: 1px solid #EEF1FA; + border-radius: 11px; + font-weight: 700; +} +QPushButton#DiagnosisOrderOffsetHelp:hover, +QPushButton#DiagnosisOrderOffsetHelp:focus { + background-color: #EEF1FA; + border-color: #8B9AD9; +} QLabel#DiagnosisReadonlyStatus[severity="neutral"] { color: #8E8F90; background-color: rgba(255, 255, 255, 190); @@ -556,7 +556,7 @@ QFrame#DiagnosisReadonlyCaseCard, QFrame[diagnosisReadonlyCard="true"] { background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 16px; + border-radius: 16px; } QLabel#DiagnosisReadonlyCardTitle { color: #1A1C1F; @@ -735,25 +735,25 @@ QFrame#DiagnosisChatBubble[side="doctor"] { border: 1px solid #F0F0F0; border-radius: 8px; } -QFrame#DiagnosisChatEvent { - background-color: #F7F8FA; - border: 1px solid #EDEDEE; - border-radius: 8px; -} -QLabel#DiagnosisChatEventMarker { - color: #697386; - font-size: 12px; - font-weight: 600; -} -QLabel#DiagnosisChatEventTitle { - color: #374151; - font-size: 13px; - font-weight: 600; -} -QLabel#DiagnosisChatEventDetail { - color: #697386; - font-size: 12px; -} +QFrame#DiagnosisChatEvent { + background-color: #F7F8FA; + border: 1px solid #EDEDEE; + border-radius: 8px; +} +QLabel#DiagnosisChatEventMarker { + color: #697386; + font-size: 12px; + font-weight: 600; +} +QLabel#DiagnosisChatEventTitle { + color: #374151; + font-size: 13px; + font-weight: 600; +} +QLabel#DiagnosisChatEventDetail { + color: #697386; + font-size: 12px; +} QLabel#DiagnosisChatMeta { color: #606163; font-size: 12px; @@ -785,7 +785,7 @@ QWidget[diagnosisChoiceHost="true"] QPushButton { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 10px; + border-radius: 10px; font-size: 12px; } QWidget[diagnosisChoiceHost="true"] QPushButton:hover, @@ -883,35 +883,35 @@ QLabel#DiagnosisUnsupportedState { padding: 22px; font-size: 13px; } -QDialog#DiagnosisDailyEditor, -QDialog#DiagnosisOrderDetailDialog, -QDialog#DiagnosisRecordingPlayer { - background-color: #FFFFFF; -} -QDialog#DiagnosisDailyEditor { - background-color: #F7F7F7; -} -QFrame#DiagnosisEditorHeader, -QFrame#DiagnosisEditorFooter { - background-color: #FFFFFF; - border: 0; -} -QFrame#DiagnosisEditorHeader { - border-bottom: 1px solid #EDEDEE; -} -QFrame#DiagnosisEditorFooter { - border-top: 1px solid #EDEDEE; -} -QWidget#DiagnosisEditorContent { - background-color: #FFFFFF; - border: 1px solid #EDEDEE; - border-radius: 12px; -} -QWidget#DiagnosisEditorContent QLabel { - color: #1A1C1F; - font-size: 12px; - font-weight: 500; -} +QDialog#DiagnosisDailyEditor, +QDialog#DiagnosisOrderDetailDialog, +QDialog#DiagnosisRecordingPlayer { + background-color: #FFFFFF; +} +QDialog#DiagnosisDailyEditor { + background-color: #F7F7F7; +} +QFrame#DiagnosisEditorHeader, +QFrame#DiagnosisEditorFooter { + background-color: #FFFFFF; + border: 0; +} +QFrame#DiagnosisEditorHeader { + border-bottom: 1px solid #EDEDEE; +} +QFrame#DiagnosisEditorFooter { + border-top: 1px solid #EDEDEE; +} +QWidget#DiagnosisEditorContent { + background-color: #FFFFFF; + border: 1px solid #EDEDEE; + border-radius: 12px; +} +QWidget#DiagnosisEditorContent QLabel { + color: #1A1C1F; + font-size: 12px; + font-weight: 500; +} QLabel#DiagnosisDialogHeading { color: #1A1C1F; font-size: 18px; @@ -929,17 +929,17 @@ QLabel#DiagnosisEditorError { border-radius: 7px; padding: 8px 10px; } -QScrollArea#DiagnosisEditorScroll, -QScrollArea#DiagnosisOrderDetailScroll { - background-color: #F7F7F7; - border: 1px solid #EDEDEE; - border-radius: 10px; -} -QScrollArea#DiagnosisEditorScroll, -QScrollArea#DiagnosisEditorScroll > QWidget > QWidget { - background-color: #F7F7F7; - border: 0; -} +QScrollArea#DiagnosisEditorScroll, +QScrollArea#DiagnosisOrderDetailScroll { + background-color: #F7F7F7; + border: 1px solid #EDEDEE; + border-radius: 10px; +} +QScrollArea#DiagnosisEditorScroll, +QScrollArea#DiagnosisEditorScroll > QWidget > QWidget { + background-color: #F7F7F7; + border: 0; +} QFrame#DiagnosisOrderOffsetBar, QFrame#DiagnosisOrderDetailHero { background-color: #F7F7F7; @@ -1010,84 +1010,84 @@ QDialog#DiagnosisPrescriptionEditor QSpinBox:focus, QDialog#DiagnosisPrescriptionEditor QDoubleSpinBox:focus { border-color: #8B9AD9; } -QWidget#DiagnosisNotesTimeline QPushButton[imageDropActive="true"] { - background-color: #EEF1FA; - border: 2px dashed #4F63D9; - color: #4F63D9; -} +QWidget#DiagnosisNotesTimeline QPushButton[imageDropActive="true"] { + background-color: #EEF1FA; + border: 2px dashed #4F63D9; + color: #4F63D9; +} """ -# Normalize the legacy component palette in one place. Keeping the selectors -# untouched protects the mature drawer behavior while aligning every nested -# editor, table and state with the shell's current blue-white theme. -_DIAGNOSIS_BLUE_REPLACEMENTS = ( - ("#0891B2", "#4F63D9"), - ("#0E7490", "#4156C4"), - ("#22D3EE", "#8B9AD9"), - ("#67E8F9", "#EEF1FA"), - ("#A5F3FC", "#EEF1FA"), - ("#CFFAFE", "#EEF1FA"), - ("#ECFEFF", "#F7F7F7"), - ("#D9ECFF", "#EEF1FA"), - ("#134E4A", "#1A1C1F"), - ("#2A6B64", "#1A1C1F"), - ("#5B7A76", "#606163"), - ("#66736D", "#606163"), - ("#94A8A4", "#8E8F90"), - ("#67B8C9", "#8B9AD9"), - ("#D5E5E2", "#EDEDEE"), - ("#E2EBE8", "#EDEDEE"), - ("#D9DEDA", "#EDEDEE"), - ("#CBD3CE", "#EDEDEE"), - ("#F5F8F7", "#FFFFFF"), - ("#F0F2EF", "#F7F7F7"), - ("#F0F5F3", "#F7F7F7"), - ("#F0FDFA", "#F7F7F7"), - ("#0F172A", "#1A1C1F"), - ("#1F2937", "#1A1C1F"), - ("#333333", "#1A1C1F"), - ("#475569", "#1A1C1F"), - ("#64748B", "#606163"), - ("#6B7280", "#606163"), - ("#999999", "#8E8F90"), - ("#9AA39E", "#8E8F90"), - ("#C0C4CC", "#8E8F90"), - ("#F1F5F9", "#F7F7F7"), - ("#E2E8F0", "#EDEDEE"), - ("#DCE3EC", "#EDEDEE"), - ("#CBD5E1", "#EDEDEE"), - ("#E5E7EB", "#EDEDEE"), - ("#E6EBF2", "#EDEDEE"), - ("#F8FAFC", "#FFFFFF"), - ("#F6F6F6", "#F6F6F6"), - ("#FAFAFA", "#FFFFFF"), - ("#F8F8F8", "#F7F7F7"), - ("#16A34A", "#287B65"), - ("#15803D", "#287B65"), - ("#F0FDF4", "#EAF9F3"), - ("#ECFDF5", "#EAF9F3"), - ("#BBF7D0", "#BFE9DC"), - ("#A7F3D0", "#BFE9DC"), - ("#B45309", "#A9691D"), - ("#EA580C", "#A9691D"), - ("#F97316", "#A9691D"), - ("#FFFBEB", "#FFF5E6"), - ("#FFF7ED", "#FFF5E6"), - ("#FCD34D", "#F3D6AC"), - ("#FDE68A", "#F3D6AC"), - ("#FED7AA", "#F3D6AC"), - ("#DC2626", "#BE4B58"), - ("#B91C1C", "#BE4B58"), - ("#F56C6C", "#BE4B58"), - ("#FEF2F2", "#FFF1F3"), - ("#FFF7F7", "#FFF1F3"), - ("#FEE2E2", "#FFE4E8"), - ("#FECACA", "#F7C8CD"), - ("#FCA5A5", "#F19BA4"), -) -for _source_color, _theme_color in _DIAGNOSIS_BLUE_REPLACEMENTS: - DIAGNOSIS_QSS = DIAGNOSIS_QSS.replace(_source_color, _theme_color) -DIAGNOSIS_QSS = clinical_stylesheet(DIAGNOSIS_QSS) +# Normalize the legacy component palette in one place. Keeping the selectors +# untouched protects the mature drawer behavior while aligning every nested +# editor, table and state with the shell's current blue-white theme. +_DIAGNOSIS_BLUE_REPLACEMENTS = ( + ("#0891B2", "#4F63D9"), + ("#0E7490", "#4156C4"), + ("#22D3EE", "#8B9AD9"), + ("#67E8F9", "#EEF1FA"), + ("#A5F3FC", "#EEF1FA"), + ("#CFFAFE", "#EEF1FA"), + ("#ECFEFF", "#F7F7F7"), + ("#D9ECFF", "#EEF1FA"), + ("#134E4A", "#1A1C1F"), + ("#2A6B64", "#1A1C1F"), + ("#5B7A76", "#606163"), + ("#66736D", "#606163"), + ("#94A8A4", "#8E8F90"), + ("#67B8C9", "#8B9AD9"), + ("#D5E5E2", "#EDEDEE"), + ("#E2EBE8", "#EDEDEE"), + ("#D9DEDA", "#EDEDEE"), + ("#CBD3CE", "#EDEDEE"), + ("#F5F8F7", "#FFFFFF"), + ("#F0F2EF", "#F7F7F7"), + ("#F0F5F3", "#F7F7F7"), + ("#F0FDFA", "#F7F7F7"), + ("#0F172A", "#1A1C1F"), + ("#1F2937", "#1A1C1F"), + ("#333333", "#1A1C1F"), + ("#475569", "#1A1C1F"), + ("#64748B", "#606163"), + ("#6B7280", "#606163"), + ("#999999", "#8E8F90"), + ("#9AA39E", "#8E8F90"), + ("#C0C4CC", "#8E8F90"), + ("#F1F5F9", "#F7F7F7"), + ("#E2E8F0", "#EDEDEE"), + ("#DCE3EC", "#EDEDEE"), + ("#CBD5E1", "#EDEDEE"), + ("#E5E7EB", "#EDEDEE"), + ("#E6EBF2", "#EDEDEE"), + ("#F8FAFC", "#FFFFFF"), + ("#F6F6F6", "#F6F6F6"), + ("#FAFAFA", "#FFFFFF"), + ("#F8F8F8", "#F7F7F7"), + ("#16A34A", "#287B65"), + ("#15803D", "#287B65"), + ("#F0FDF4", "#EAF9F3"), + ("#ECFDF5", "#EAF9F3"), + ("#BBF7D0", "#BFE9DC"), + ("#A7F3D0", "#BFE9DC"), + ("#B45309", "#A9691D"), + ("#EA580C", "#A9691D"), + ("#F97316", "#A9691D"), + ("#FFFBEB", "#FFF5E6"), + ("#FFF7ED", "#FFF5E6"), + ("#FCD34D", "#F3D6AC"), + ("#FDE68A", "#F3D6AC"), + ("#FED7AA", "#F3D6AC"), + ("#DC2626", "#BE4B58"), + ("#B91C1C", "#BE4B58"), + ("#F56C6C", "#BE4B58"), + ("#FEF2F2", "#FFF1F3"), + ("#FFF7F7", "#FFF1F3"), + ("#FEE2E2", "#FFE4E8"), + ("#FECACA", "#F7C8CD"), + ("#FCA5A5", "#F19BA4"), +) +for _source_color, _theme_color in _DIAGNOSIS_BLUE_REPLACEMENTS: + DIAGNOSIS_QSS = DIAGNOSIS_QSS.replace(_source_color, _theme_color) +DIAGNOSIS_QSS = clinical_stylesheet(DIAGNOSIS_QSS) def _text(value: Any, default: str = "—") -> str: @@ -1167,19 +1167,19 @@ class DiagnosisSwitch(QAbstractButton): track = QRectF(1, 3, self.width() - 2, self.height() - 6) checked = self.isChecked() painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"])) - if not self.isEnabled(): - painter.setOpacity(0.6) + painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"])) + if not self.isEnabled(): + painter.setOpacity(0.6) painter.drawRoundedRect(track, track.height() / 2, track.height() / 2) diameter = track.height() - 4 x = track.right() - diameter - 2 if checked else track.left() + 2 painter.setBrush(QColor("#FFFFFF")) painter.drawEllipse(QRectF(x, track.top() + 2, diameter, diameter)) - if self.hasFocus(): - painter.setOpacity(1) - painter.setPen(QPen(QColor(PALETTE["focus"]), 1)) - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 11, 11) + if self.hasFocus(): + painter.setOpacity(1) + painter.setPen(QPen(QColor(PALETTE["focus"]), 1)) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 11, 11) painter.end() @@ -1217,19 +1217,19 @@ class SaveStateButton(QPushButton): painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) enabled = self.isEnabled() - idle_color = PALETTE["accent_pressed"] if self.isDown() else PALETTE["accent"] + idle_color = PALETTE["accent_pressed"] if self.isDown() else PALETTE["accent"] color = { - "success": PALETTE["success"], - "error": PALETTE["danger"], - "loading": PALETTE["accent"], - }.get(self._state, idle_color if enabled else PALETTE["disabled_surface"]) + "success": PALETTE["success"], + "error": PALETTE["danger"], + "loading": PALETTE["accent"], + }.get(self._state, idle_color if enabled else PALETTE["disabled_surface"]) painter.setPen(Qt.PenStyle.NoPen) painter.setBrush(QColor(color)) painter.drawRoundedRect(QRectF(self.rect()).adjusted(1, 1, -1, -1), 10, 10) - if self.hasFocus(): - painter.setPen(QPen(QColor(PALETTE["focus"]), 1)) - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 10, 10) + if self.hasFocus(): + painter.setPen(QPen(QColor(PALETTE["focus"]), 1)) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 10, 10) label = { "loading": "正在保存", "success": "保存成功", @@ -1253,9 +1253,9 @@ class SaveStateButton(QPushButton): else: painter.drawLine(x + 3, center_y - 5, x + 12, center_y + 5) painter.drawLine(x + 12, center_y - 5, x + 3, center_y + 5) - painter.setPen(QColor( - PALETTE["disabled"] if not enabled and self._state == "idle" else PALETTE["surface"] - )) + painter.setPen(QColor( + PALETTE["disabled"] if not enabled and self._state == "idle" else PALETTE["surface"] + )) painter.drawText( QRect(x + icon_width, 0, metrics.horizontalAdvance(label), self.height()), Qt.AlignmentFlag.AlignCenter, @@ -1339,7 +1339,7 @@ class DiagnosisLineEdit(QLineEdit): self.setText(text) -class DiagnosisTextEdit(QPlainTextEdit): +class DiagnosisTextEdit(QPlainTextEdit): """Multiline editor using the same scoped field state as line inputs.""" def __init__(self, rows: int = 3, parent: QWidget | None = None) -> None: @@ -1355,113 +1355,113 @@ class DiagnosisTextEdit(QPlainTextEdit): # QPlainTextEdit defaults to ~80 columns; that blows past the drawer width. return QSize(48, self._hint_height) - def sizeHint(self) -> QSize: # noqa: N802 - Qt virtual - return QSize(160, self._hint_height) - - -class ExpandableDiagnosisTextEdit(DiagnosisTextEdit): - """An inline long-text editor without an inner scrollbar when expanded.""" - - def __init__(self, rows: int = 3, parent: QWidget | None = None) -> None: - super().__init__(rows, parent) - self._collapsed_height = self._hint_height - self._caption = "内容" - self._expand_host: QWidget | None = None - self.expand_button = QPushButton("展开全部", self) - self.expand_button.setObjectName("DiagnosisTextExpandButton") - self.expand_button.setProperty("variant", "link") - self.expand_button.setCheckable(True) - self.expand_button.setAutoDefault(False) - self.expand_button.setCursor(Qt.CursorShape.PointingHandCursor) - self.expand_button.setToolTip("展开文本框,查看和编辑全部内容") - self.expand_button.hide() - self.expand_button.toggled.connect(self._toggle_expanded) - self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self._height_sync = QTimer(self) - self._height_sync.setSingleShot(True) - self._height_sync.setInterval(0) - self._height_sync.timeout.connect(self._sync_content_height) - self.textChanged.connect(self._height_sync.start) - self.document().documentLayout().documentSizeChanged.connect( - lambda _size: self._height_sync.start() - ) - - def wrap_with_expander(self, caption: str) -> QWidget: - """Keep the original plain-text editor as the form's save/readonly target.""" - - if self._expand_host is None: - self._caption = caption - self.setAccessibleName(caption) - self.expand_button.setAccessibleName(f"展开{caption}全部内容") - self._expand_host = QWidget() - self._expand_host.setMinimumWidth(0) - self._expand_host.setFocusProxy(self) - layout = QVBoxLayout(self._expand_host) - layout.setContentsMargins(0, 0, 0, 0) - layout.setSpacing(2) - layout.addWidget(self) - layout.addWidget(self.expand_button, 0, Qt.AlignmentFlag.AlignRight) - return self._expand_host - - def setPlainText(self, text: str) -> None: # noqa: N802 - Qt API - # A newly loaded record starts compact; typing/paste/undo keep its state. - self.expand_button.setChecked(False) - super().setPlainText(text) - - def _toggle_expanded(self, expanded: bool) -> None: - self.expand_button.setText("收起" if expanded else "展开全部") - self.expand_button.setAccessibleName( - f"收起{self._caption}" if expanded else f"展开{self._caption}全部内容" - ) - self.expand_button.setToolTip( - "收起为紧凑文本框,内容不会丢失" if expanded else "展开文本框,查看和编辑全部内容" - ) - self.setVerticalScrollBarPolicy( - Qt.ScrollBarPolicy.ScrollBarAlwaysOff - if expanded - else Qt.ScrollBarPolicy.ScrollBarAsNeeded - ) - self.verticalScrollBar().setValue(0) - self._height_sync.start() - - def _sync_content_height(self) -> None: - expanded = self.expand_button.isChecked() - document = self.document() - document_layout = document.documentLayout() - # QPlainTextDocumentLayout.documentSize().height() counts lines, not - # pixels. Measure the actual wrapped blocks, including offscreen ones. - height = self.height() - self.viewport().height() + 2 * document.documentMargin() - block = document.begin() - while block.isValid(): - height += document_layout.blockBoundingRect(block).height() - if not expanded and height > self._collapsed_height: - break - block = block.next() - self.expand_button.setVisible(expanded or height > self._collapsed_height) - target = max(self._collapsed_height, ceil(height)) if expanded else self._collapsed_height - if self._hint_height != target: - self._hint_height = target - self.setFixedHeight(target) - self.updateGeometry() - - def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt API - super().resizeEvent(event) - if hasattr(self, "_height_sync"): - self._height_sync.start() - - def showEvent(self, event: QShowEvent) -> None: # noqa: N802 - Qt API - super().showEvent(event) - self._height_sync.start() - - def changeEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API - super().changeEvent(event) - if event.type() in (QEvent.Type.FontChange, QEvent.Type.StyleChange) and hasattr( - self, "_height_sync" - ): - self._height_sync.start() - - -class DiagnosisComboBox(QComboBox): + def sizeHint(self) -> QSize: # noqa: N802 - Qt virtual + return QSize(160, self._hint_height) + + +class ExpandableDiagnosisTextEdit(DiagnosisTextEdit): + """An inline long-text editor without an inner scrollbar when expanded.""" + + def __init__(self, rows: int = 3, parent: QWidget | None = None) -> None: + super().__init__(rows, parent) + self._collapsed_height = self._hint_height + self._caption = "内容" + self._expand_host: QWidget | None = None + self.expand_button = QPushButton("展开全部", self) + self.expand_button.setObjectName("DiagnosisTextExpandButton") + self.expand_button.setProperty("variant", "link") + self.expand_button.setCheckable(True) + self.expand_button.setAutoDefault(False) + self.expand_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.expand_button.setToolTip("展开文本框,查看和编辑全部内容") + self.expand_button.hide() + self.expand_button.toggled.connect(self._toggle_expanded) + self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self._height_sync = QTimer(self) + self._height_sync.setSingleShot(True) + self._height_sync.setInterval(0) + self._height_sync.timeout.connect(self._sync_content_height) + self.textChanged.connect(self._height_sync.start) + self.document().documentLayout().documentSizeChanged.connect( + lambda _size: self._height_sync.start() + ) + + def wrap_with_expander(self, caption: str) -> QWidget: + """Keep the original plain-text editor as the form's save/readonly target.""" + + if self._expand_host is None: + self._caption = caption + self.setAccessibleName(caption) + self.expand_button.setAccessibleName(f"展开{caption}全部内容") + self._expand_host = QWidget() + self._expand_host.setMinimumWidth(0) + self._expand_host.setFocusProxy(self) + layout = QVBoxLayout(self._expand_host) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(2) + layout.addWidget(self) + layout.addWidget(self.expand_button, 0, Qt.AlignmentFlag.AlignRight) + return self._expand_host + + def setPlainText(self, text: str) -> None: # noqa: N802 - Qt API + # A newly loaded record starts compact; typing/paste/undo keep its state. + self.expand_button.setChecked(False) + super().setPlainText(text) + + def _toggle_expanded(self, expanded: bool) -> None: + self.expand_button.setText("收起" if expanded else "展开全部") + self.expand_button.setAccessibleName( + f"收起{self._caption}" if expanded else f"展开{self._caption}全部内容" + ) + self.expand_button.setToolTip( + "收起为紧凑文本框,内容不会丢失" if expanded else "展开文本框,查看和编辑全部内容" + ) + self.setVerticalScrollBarPolicy( + Qt.ScrollBarPolicy.ScrollBarAlwaysOff + if expanded + else Qt.ScrollBarPolicy.ScrollBarAsNeeded + ) + self.verticalScrollBar().setValue(0) + self._height_sync.start() + + def _sync_content_height(self) -> None: + expanded = self.expand_button.isChecked() + document = self.document() + document_layout = document.documentLayout() + # QPlainTextDocumentLayout.documentSize().height() counts lines, not + # pixels. Measure the actual wrapped blocks, including offscreen ones. + height = self.height() - self.viewport().height() + 2 * document.documentMargin() + block = document.begin() + while block.isValid(): + height += document_layout.blockBoundingRect(block).height() + if not expanded and height > self._collapsed_height: + break + block = block.next() + self.expand_button.setVisible(expanded or height > self._collapsed_height) + target = max(self._collapsed_height, ceil(height)) if expanded else self._collapsed_height + if self._hint_height != target: + self._hint_height = target + self.setFixedHeight(target) + self.updateGeometry() + + def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt API + super().resizeEvent(event) + if hasattr(self, "_height_sync"): + self._height_sync.start() + + def showEvent(self, event: QShowEvent) -> None: # noqa: N802 - Qt API + super().showEvent(event) + self._height_sync.start() + + def changeEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API + super().changeEvent(event) + if event.type() in (QEvent.Type.FontChange, QEvent.Type.StyleChange) and hasattr( + self, "_height_sync" + ): + self._height_sync.start() + + +class DiagnosisComboBox(QComboBox): """Choice editor with the legacy text API used by diagnosis saving.""" def __init__( @@ -1690,26 +1690,27 @@ class DiagnosisChoiceButtons(QWidget): for button in self._buttons: value = str(button.property("diagnosisValue")) label = str(button.property("diagnosisLabel") or button.text()) - button.setChecked(value in token_set or label in token_set) - repolish(button) + want = value in token_set or label in token_set + if button.isChecked() != want: + button.setChecked(want) if was_exclusive: self._group.setExclusive(True) def setReadOnly(self, read_only: bool) -> None: # noqa: N802 # Match admin fieldset[disabled]: keep selected chip paint, block interaction. - self._read_only = bool(read_only) + target = bool(read_only) + if target == self._read_only and getattr(self, "_readonly_applied", False): + return + self._read_only = target + self._readonly_applied = True self.setProperty("diagnosisChoiceLocked", self._read_only) self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, self._read_only) - self.setCursor( - Qt.CursorShape.ArrowCursor if self._read_only else Qt.CursorShape.ArrowCursor + cursor_shape = ( + Qt.CursorShape.ArrowCursor if self._read_only else Qt.CursorShape.PointingHandCursor ) for button in self._buttons: button.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, self._read_only) - if self._read_only: - button.setCursor(Qt.CursorShape.ArrowCursor) - else: - button.setCursor(Qt.CursorShape.PointingHandCursor) - repolish(button) + button.setCursor(cursor_shape) repolish(self) def isReadOnly(self) -> bool: # noqa: N802 @@ -1850,18 +1851,18 @@ class MessageStrip(QFrame): self.glyph = QLabel("i") self.glyph.setFixedWidth(18) self.glyph.setAlignment(Qt.AlignmentFlag.AlignCenter) - self.glyph.setStyleSheet(clinical_stylesheet("font-weight:700; color:$ds_accent;")) + self.glyph.setStyleSheet(clinical_stylesheet("font-weight:700; color:$ds_accent;")) self.label = QLabel() self.label.setWordWrap(True) - self.label.setStyleSheet(clinical_stylesheet("color:$ds_text; font-size:13px;")) + self.label.setStyleSheet(clinical_stylesheet("color:$ds_text; font-size:13px;")) layout.addWidget(self.glyph) layout.addWidget(self.label, 1) self.action_button = QPushButton() self.action_button.setObjectName("DiagnosisMessageAction") self.action_button.setStyleSheet( - "QPushButton{min-height:28px;padding:0 10px;color:#1A1C1F;background:#F0F0F0;" - "border:1px solid #E4E4E5;border-radius:7px;font-weight:500;}" - "QPushButton:hover,QPushButton:focus{background:#EEF1FA;border-color:#8B9AD9;}" + "QPushButton{min-height:28px;padding:0 10px;color:#1A1C1F;background:#F0F0F0;" + "border:1px solid #E4E4E5;border-radius:7px;font-weight:500;}" + "QPushButton:hover,QPushButton:focus{background:#EEF1FA;border-color:#8B9AD9;}" ) self.action_button.clicked.connect(self.action_requested) self.action_button.hide() @@ -1929,7 +1930,7 @@ class LoadingOverlay(QFrame): layout.setSpacing(8) self.glyph = _LoadingSpinner(self) label = QLabel(text) - label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;")) + label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;")) layout.addWidget(self.glyph) layout.addWidget(label) self.hide() @@ -2020,15 +2021,15 @@ class RecordTable(QTableWidget): Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter ) if column_index in danger_columns: - item.setForeground(QColor(PALETTE["danger"])) + item.setForeground(QColor(PALETTE["danger"])) kind = semantic.get(column_index) if kind: palette = { - "success": (PALETTE["success"], PALETTE["success_soft"]), - "warning": (PALETTE["warning"], PALETTE["warning_soft"]), - "danger": (PALETTE["danger"], PALETTE["danger_soft"]), - "info": (PALETTE["accent"], PALETTE["accent_soft"]), - "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), + "success": (PALETTE["success"], PALETTE["success_soft"]), + "warning": (PALETTE["warning"], PALETTE["warning_soft"]), + "danger": (PALETTE["danger"], PALETTE["danger_soft"]), + "info": (PALETTE["accent"], PALETTE["accent_soft"]), + "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), } foreground, background = palette.get(kind, palette["neutral"]) item.setForeground(QColor(foreground)) @@ -2068,20 +2069,20 @@ class BloodTrendChart(QWidget): plot = self.rect().adjusted(48, 24, -22, -38) values = [value for value in (*self._fasting, *self._postprandial) if value is not None] if not values or plot.width() <= 0 or plot.height() <= 0: - painter.setPen(QColor(PALETTE["muted"])) + painter.setPen(QColor(PALETTE["muted"])) painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, "当前时间范围暂无血糖数据") painter.end() return upper = max(12.0, max(values) * 1.15) - painter.setPen(QPen(QColor(PALETTE["line"]), 1)) + painter.setPen(QPen(QColor(PALETTE["line"]), 1)) for step in range(5): y = plot.bottom() - round(plot.height() * step / 4) painter.drawLine(plot.left(), y, plot.right(), y) - painter.setPen(QColor(PALETTE["muted"])) + painter.setPen(QColor(PALETTE["muted"])) painter.drawText( 4, y - 8, 40, 16, Qt.AlignmentFlag.AlignRight, f"{upper * step / 4:.0f}" ) - painter.setPen(QPen(QColor(PALETTE["line"]), 1)) + painter.setPen(QPen(QColor(PALETTE["line"]), 1)) count = max(1, len(self._dates) - 1) def point(index: int, value: float) -> QPointF: @@ -2091,8 +2092,8 @@ class BloodTrendChart(QWidget): ) for series, color in ( - (self._fasting, QColor("#4F63D9")), - (self._postprandial, QColor("#A9691D")), + (self._fasting, QColor("#4F63D9")), + (self._postprandial, QColor("#A9691D")), ): previous: QPointF | None = None painter.setPen(QPen(color, 2.5)) @@ -2106,12 +2107,12 @@ class BloodTrendChart(QWidget): painter.drawLine(previous, current) painter.drawEllipse(current, 3.2, 3.2) previous = current - painter.setPen(QColor("#4F63D9")) + painter.setPen(QColor("#4F63D9")) painter.drawText(plot.left(), 4, 94, 18, Qt.AlignmentFlag.AlignLeft, "● 空腹血糖") - painter.setPen(QColor("#A9691D")) + painter.setPen(QColor("#A9691D")) painter.drawText(plot.left() + 100, 4, 110, 18, Qt.AlignmentFlag.AlignLeft, "● 餐后血糖") if self._dates: - painter.setPen(QColor(PALETTE["muted"])) + painter.setPen(QColor(PALETTE["muted"])) painter.drawText( plot.left(), plot.bottom() + 8, @@ -2314,7 +2315,7 @@ class DailyRecordPanel(QFrame): self.todo_table.setMinimumHeight(180) todo_layout.addWidget(self.todo_table) self.todo_summary = QLabel("共 0 条") - self.todo_summary.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;")) + self.todo_summary.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;")) todo_layout.addWidget(self.todo_summary, 0, Qt.AlignmentFlag.AlignRight) root.addWidget(todo_card) self.clear() @@ -2471,9 +2472,9 @@ class DailyRecordPanel(QFrame): label_font.setWeight(QFont.Weight.Normal) for row_index, (metric, label) in enumerate(self.METRICS): label_item = QTableWidgetItem(label) - label_item.setFont(label_font) - label_item.setForeground(QColor(PALETTE["muted"])) - label_item.setBackground(QColor(PALETTE["surface_alt"])) + label_item.setFont(label_font) + label_item.setForeground(QColor(PALETTE["muted"])) + label_item.setBackground(QColor(PALETTE["surface_alt"])) self.matrix.setItem(row_index, 0, label_item) for date_index, date in enumerate(dates, 1): b = blood.get(date) @@ -2526,11 +2527,11 @@ class DailyRecordPanel(QFrame): item = QTableWidgetItem(value) item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) if high: - item.setForeground(QColor(PALETTE["danger"])) - item.setBackground(QColor(PALETTE["danger_soft"])) + item.setForeground(QColor(PALETTE["danger"])) + item.setBackground(QColor(PALETTE["danger_soft"])) elif value.endswith("· 自录"): - item.setForeground(QColor(PALETTE["text"])) - item.setBackground(QColor(PALETTE["surface_alt"])) + item.setForeground(QColor(PALETTE["text"])) + item.setBackground(QColor(PALETTE["surface_alt"])) edit_kind = "" edit_source: Any = None if metric in {"fasting", "postprandial", "other", "bp", "western", "insulin"}: @@ -2745,29 +2746,29 @@ class _RemoteImageButton(QPushButton): request = QNetworkRequest(url) request.setTransferTimeout(10_000) request.setMaximumRedirectsAllowed(4) - request.setAttribute( - QNetworkRequest.Attribute.RedirectPolicyAttribute, - QNetworkRequest.RedirectPolicy.SameOriginRedirectPolicy, - ) - reply = self._manager.get(request) - self._reply = reply - reply.setProperty("diagnosisImageGeneration", generation) - reply.setProperty("diagnosisImageOversize", False) - reply.downloadProgress.connect(self._download_progress) - reply.finished.connect(self._reply_finished) - - def _download_progress(self, bytes_received: int, bytes_total: int) -> None: - """Abort a current reply as soon as its received or declared size is unsafe.""" - - reply = self.sender() - if reply is not self._reply: - return - if bytes_received <= self._MAX_IMAGE_BYTES and ( - bytes_total < 0 or bytes_total <= self._MAX_IMAGE_BYTES - ): - return - reply.setProperty("diagnosisImageOversize", True) - reply.abort() + request.setAttribute( + QNetworkRequest.Attribute.RedirectPolicyAttribute, + QNetworkRequest.RedirectPolicy.SameOriginRedirectPolicy, + ) + reply = self._manager.get(request) + self._reply = reply + reply.setProperty("diagnosisImageGeneration", generation) + reply.setProperty("diagnosisImageOversize", False) + reply.downloadProgress.connect(self._download_progress) + reply.finished.connect(self._reply_finished) + + def _download_progress(self, bytes_received: int, bytes_total: int) -> None: + """Abort a current reply as soon as its received or declared size is unsafe.""" + + reply = self.sender() + if reply is not self._reply: + return + if bytes_received <= self._MAX_IMAGE_BYTES and ( + bytes_total < 0 or bytes_total <= self._MAX_IMAGE_BYTES + ): + return + reply.setProperty("diagnosisImageOversize", True) + reply.abort() def _reply_finished(self) -> None: """Use a QObject receiver connection so destruction auto-disconnects the callback.""" @@ -2787,19 +2788,19 @@ class _RemoteImageButton(QPushButton): reply.deleteLater() return self._reply = None - if not self._owner_is_current(): - reply.deleteLater() - return - error = reply.error() - if bool(reply.property("diagnosisImageOversize")) or ( - error != QNetworkReply.NetworkError.NoError - ): - reply.deleteLater() - self._show_fallback() - return - payload = bytes(reply.readAll()) - reply.deleteLater() - self._apply_payload(payload, generation) + if not self._owner_is_current(): + reply.deleteLater() + return + error = reply.error() + if bool(reply.property("diagnosisImageOversize")) or ( + error != QNetworkReply.NetworkError.NoError + ): + reply.deleteLater() + self._show_fallback() + return + payload = bytes(reply.readAll()) + reply.deleteLater() + self._apply_payload(payload, generation) def _apply_payload(self, payload: bytes, generation: int) -> bool: """Decode a current reply; kept separate so offline tests can exercise rendering.""" @@ -2854,20 +2855,20 @@ class NotesTimeline(QWidget): add_requested = Signal() upload_requested = Signal(str) - images_dropped = Signal(object, str) - image_drop_failed = Signal(str) - delete_attachment_requested = Signal(int, str, str) - open_attachment_requested = Signal(str) - preview_images_requested = Signal(object, int) + images_dropped = Signal(object, str) + image_drop_failed = Signal(str) + delete_attachment_requested = Signal(int, str, str) + open_attachment_requested = Signal(str) + preview_images_requested = Signal(object, int) def __init__(self, *, editable: bool = False, parent: QWidget | None = None) -> None: super().__init__(parent) self.setObjectName("DiagnosisNotesTimeline") self._editable = editable self._can_delete = editable - self._upload_available = True - self._upload_busy = False - self._drop_targets: dict[QWidget, str] = {} + self._upload_available = True + self._upload_busy = False + self._drop_targets: dict[QWidget, str] = {} self._image_generation = 0 self.root = QVBoxLayout(self) self.root.setContentsMargins(0, 0, 0, 0) @@ -2888,10 +2889,10 @@ class NotesTimeline(QWidget): self.tongue_button.clicked.connect(lambda: self.upload_requested.emit("tongue_images")) self.report_button.clicked.connect(lambda: self.upload_requested.emit("report_files")) self.root.addWidget(self.toolbar) - self.drop_hint = QLabel("可拖入图片;拖到“上传舌象”或“上传报告”按钮可直接分类。") - self.drop_hint.setObjectName("DiagnosisDialogGuidance") - self.drop_hint.setWordWrap(True) - self.root.addWidget(self.drop_hint) + self.drop_hint = QLabel("可拖入图片;拖到“上传舌象”或“上传报告”按钮可直接分类。") + self.drop_hint.setObjectName("DiagnosisDialogGuidance") + self.drop_hint.setWordWrap(True) + self.root.addWidget(self.drop_hint) self.nodes = QWidget() self.nodes_layout = QVBoxLayout(self.nodes) self.nodes_layout.setContentsMargins(22, 0, 0, 0) @@ -2902,89 +2903,89 @@ class NotesTimeline(QWidget): self.empty.setAlignment(Qt.AlignmentFlag.AlignCenter) self.empty.setMinimumHeight(80) self.root.addWidget(self.empty) - self.register_image_drop_target(self) - self.register_image_drop_target(self.tongue_button, "tongue_images") - self.register_image_drop_target(self.report_button, "report_files") - self.tongue_button.setToolTip("点击选择文件,或把图片拖到此处上传为舌象") - self.report_button.setToolTip("点击选择报告,或把图片拖到此处上传为报告") + self.register_image_drop_target(self) + self.register_image_drop_target(self.tongue_button, "tongue_images") + self.register_image_drop_target(self.report_button, "report_files") + self.tongue_button.setToolTip("点击选择文件,或把图片拖到此处上传为舌象") + self.report_button.setToolTip("点击选择报告,或把图片拖到此处上传为报告") self.set_editable(editable) def set_editable(self, editable: bool, *, can_delete: bool | None = None) -> None: self._editable = editable self._can_delete = editable if can_delete is None else bool(can_delete) self.toolbar.setVisible(self._editable) - self.drop_hint.setVisible(self._editable and self._upload_available) - self._sync_image_drop_targets() - - def set_upload_available(self, available: bool) -> None: - self._upload_available = bool(available) - self.drop_hint.setVisible(self._editable and self._upload_available) - self._sync_image_drop_targets() - - def set_upload_busy(self, busy: bool) -> None: - self._upload_busy = bool(busy) - self._sync_image_drop_targets() - - def register_image_drop_target(self, widget: QWidget, image_type: str = "") -> None: - """Include scroll viewport blank space as well as the note timeline.""" - self._drop_targets[widget] = image_type - widget.installEventFilter(self) - self._sync_image_drop_targets() - - def _sync_image_drop_targets(self) -> None: - enabled = self._editable and self._upload_available and not self._upload_busy - for widget in self._drop_targets: - widget.setAcceptDrops(enabled) - self.tongue_button.setEnabled(enabled) - self.report_button.setEnabled(enabled) - self.add_button.setEnabled(self._editable and not self._upload_busy) - if not enabled: - self._highlight_drop_target(None) - - def _highlight_drop_target(self, active: QWidget | None) -> None: - for button in (self.tongue_button, self.report_button): - highlighted = button is active - if bool(button.property("imageDropActive")) != highlighted: - button.setProperty("imageDropActive", highlighted) - repolish(button) - text = ( - "松开鼠标上传图片;未指定类别时可选择舌象或报告。" - if active is not None else "可拖入图片;拖到“上传舌象”或“上传报告”按钮可直接分类。" - ) - self.drop_hint.setText(text) - - def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802 - Qt API - if watched in self._drop_targets and event.type() in { - QEvent.Type.DragEnter, QEvent.Type.DragMove, QEvent.Type.DragLeave, QEvent.Type.Drop, - }: - if event.type() == QEvent.Type.DragLeave: - self._highlight_drop_target(None) - event.accept() - return True - if (not self._editable or not self._upload_available or self._upload_busy - or not (event.possibleActions() & Qt.DropAction.CopyAction) - or not can_drop_images(event.mimeData())): - self._highlight_drop_target(None) - event.ignore() - return True - if event.type() == QEvent.Type.Drop: - self._highlight_drop_target(None) - try: - payload = capture_image_drop(event.mimeData()) - except ValueError as error: - self.image_drop_failed.emit(str(error)) - event.ignore() - return True - # Copy semantics are essential: uploading never moves the source. - event.setDropAction(Qt.DropAction.CopyAction) - event.accept() - self.images_dropped.emit(payload, self._drop_targets[watched]) - else: - self._highlight_drop_target(watched) - event.setDropAction(Qt.DropAction.CopyAction) - event.accept() - return True - return super().eventFilter(watched, event) + self.drop_hint.setVisible(self._editable and self._upload_available) + self._sync_image_drop_targets() + + def set_upload_available(self, available: bool) -> None: + self._upload_available = bool(available) + self.drop_hint.setVisible(self._editable and self._upload_available) + self._sync_image_drop_targets() + + def set_upload_busy(self, busy: bool) -> None: + self._upload_busy = bool(busy) + self._sync_image_drop_targets() + + def register_image_drop_target(self, widget: QWidget, image_type: str = "") -> None: + """Include scroll viewport blank space as well as the note timeline.""" + self._drop_targets[widget] = image_type + widget.installEventFilter(self) + self._sync_image_drop_targets() + + def _sync_image_drop_targets(self) -> None: + enabled = self._editable and self._upload_available and not self._upload_busy + for widget in self._drop_targets: + widget.setAcceptDrops(enabled) + self.tongue_button.setEnabled(enabled) + self.report_button.setEnabled(enabled) + self.add_button.setEnabled(self._editable and not self._upload_busy) + if not enabled: + self._highlight_drop_target(None) + + def _highlight_drop_target(self, active: QWidget | None) -> None: + for button in (self.tongue_button, self.report_button): + highlighted = button is active + if bool(button.property("imageDropActive")) != highlighted: + button.setProperty("imageDropActive", highlighted) + repolish(button) + text = ( + "松开鼠标上传图片;未指定类别时可选择舌象或报告。" + if active is not None else "可拖入图片;拖到“上传舌象”或“上传报告”按钮可直接分类。" + ) + self.drop_hint.setText(text) + + def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802 - Qt API + if watched in self._drop_targets and event.type() in { + QEvent.Type.DragEnter, QEvent.Type.DragMove, QEvent.Type.DragLeave, QEvent.Type.Drop, + }: + if event.type() == QEvent.Type.DragLeave: + self._highlight_drop_target(None) + event.accept() + return True + if (not self._editable or not self._upload_available or self._upload_busy + or not (event.possibleActions() & Qt.DropAction.CopyAction) + or not can_drop_images(event.mimeData())): + self._highlight_drop_target(None) + event.ignore() + return True + if event.type() == QEvent.Type.Drop: + self._highlight_drop_target(None) + try: + payload = capture_image_drop(event.mimeData()) + except ValueError as error: + self.image_drop_failed.emit(str(error)) + event.ignore() + return True + # Copy semantics are essential: uploading never moves the source. + event.setDropAction(Qt.DropAction.CopyAction) + event.accept() + self.images_dropped.emit(payload, self._drop_targets[watched]) + else: + self._highlight_drop_target(watched) + event.setDropAction(Qt.DropAction.CopyAction) + event.accept() + return True + return super().eventFilter(watched, event) def set_state(self, text: str) -> None: self.empty.setText(text) @@ -3021,14 +3022,14 @@ class NotesTimeline(QWidget): attachments = QWidget() attachments_layout = FlowLayout(attachments, horizontal_spacing=8, vertical_spacing=8) images = _pick(note, "tongue_images", "images", default=[]) or [] - if not isinstance(images, Sequence) or isinstance(images, (str, bytes, bytearray)): - images = [images] - image_paths = [ - str(_pick(image, "url", "path", "file_url", default=image) or "") - for image in images - ] - note_id = int(_pick(note, "id", "note_id", default=0) or 0) - for image_index, path in enumerate(image_paths): + if not isinstance(images, Sequence) or isinstance(images, (str, bytes, bytearray)): + images = [images] + image_paths = [ + str(_pick(image, "url", "path", "file_url", default=image) or "") + for image in images + ] + note_id = int(_pick(note, "id", "note_id", default=0) or 0) + for image_index, path in enumerate(image_paths): image_host = QWidget() image_layout = QGridLayout(image_host) image_layout.setContentsMargins(0, 0, 0, 0) @@ -3042,12 +3043,12 @@ class NotesTimeline(QWidget): object_name="DiagnosisTongueThumb", parent=image_host, ) - thumb.setEnabled(bool(path)) - thumb.clicked.connect( - lambda _checked=False, sources=image_paths, index=image_index: ( - self.preview_images_requested.emit(sources, index) - ) - ) + thumb.setEnabled(bool(path)) + thumb.clicked.connect( + lambda _checked=False, sources=image_paths, index=image_index: ( + self.preview_images_requested.emit(sources, index) + ) + ) image_layout.addWidget(thumb, 0, 0) if self._can_delete and note_id > 0 and path: remove = QPushButton("×") @@ -3143,7 +3144,7 @@ class ChatPanel(QWidget): toolbar_layout.setContentsMargins(0, 0, 0, 0) toolbar_layout.setSpacing(8) archive = QLabel("仅展示服务端已归档消息(only_archived=1)") - archive.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;")) + archive.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;")) toolbar_layout.addWidget(archive) toolbar_layout.addStretch(1) self.sync_button = QPushButton("同步最新(后台异步)") @@ -3175,16 +3176,16 @@ class ChatPanel(QWidget): widget = item.widget() if widget is not None and widget not in {self.empty, self.toolbar, self.info}: widget.deleteLater() - visible_count = 0 + visible_count = 0 for message in messages: - item = parse_chat_item(message, include_date=True) - if item is None: - continue - visible_count += 1 - if item.variant == "event": - self.root.insertWidget(max(2, self.root.count() - 1), self._event_row(item)) - continue - side = "doctor" if item.role == "doctor" else "patient" + item = parse_chat_item(message, include_date=True) + if item is None: + continue + visible_count += 1 + if item.variant == "event": + self.root.insertWidget(max(2, self.root.count() - 1), self._event_row(item)) + continue + side = "doctor" if item.role == "doctor" else "patient" row = QWidget() row_layout = QHBoxLayout(row) row_layout.setContentsMargins(0, 0, 0, 0) @@ -3197,14 +3198,14 @@ class ChatPanel(QWidget): bubble_layout.setSpacing(5) meta = QLabel( f"{_text(_pick(message, 'sender_name', 'from_staff_name', 'name'), '患者' if side == 'patient' else '医生')} " - f"{item.time_text}" + f"{item.time_text}" ) meta.setObjectName("DiagnosisChatMeta") - meta.setTextFormat(Qt.TextFormat.PlainText) + meta.setTextFormat(Qt.TextFormat.PlainText) message_type = str( _pick(message, "message_type", "msg_type", "type", default="text") or "text" ).lower() - body_text = _text(_pick(message, "text", "content", "message"), "不支持的消息") + body_text = _text(_pick(message, "text", "content", "message"), "不支持的消息") body: QWidget if message_type in {"image", "2"}: target = str( @@ -3244,11 +3245,11 @@ class ChatPanel(QWidget): ) body = action else: - text = QLabel(body_text) + text = QLabel(body_text) text.setObjectName("DiagnosisChatText") - text.setTextFormat(Qt.TextFormat.PlainText) + text.setTextFormat(Qt.TextFormat.PlainText) text.setWordWrap(True) - text.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + text.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) body = text bubble_layout.addWidget(meta) bubble_layout.addWidget(body) @@ -3259,50 +3260,50 @@ class ChatPanel(QWidget): row_layout.addWidget(bubble) row_layout.addStretch(1) self.root.insertWidget(max(2, self.root.count() - 1), row) - self.empty.setVisible(visible_count == 0) - - @staticmethod - def _event_row(item: ChatItem) -> QWidget: - row = QWidget() - layout = QHBoxLayout(row) - layout.setContentsMargins(0, 0, 0, 0) - layout.addStretch(1) - card = QFrame() - card.setObjectName("DiagnosisChatEvent") - card.setProperty("tone", item.tone) - card.setMaximumWidth(620) - card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) - content = QGridLayout(card) - content.setContentsMargins(12, 10, 12, 10) - content.setHorizontalSpacing(9) - content.setVerticalSpacing(4) - marker = QLabel(item.marker) - marker.setObjectName("DiagnosisChatEventMarker") - marker.setTextFormat(Qt.TextFormat.PlainText) - marker.setFixedWidth(22) - marker.setAlignment(Qt.AlignmentFlag.AlignCenter) - content.addWidget(marker, 0, 0) - title = QLabel(item.title) - title.setObjectName("DiagnosisChatEventTitle") - title.setTextFormat(Qt.TextFormat.PlainText) - title.setWordWrap(True) - content.addWidget(title, 0, 1) - content.setColumnStretch(1, 1) - if item.time_text: - time = QLabel(item.time_text) - time.setObjectName("DiagnosisChatMeta") - time.setTextFormat(Qt.TextFormat.PlainText) - content.addWidget(time, 0, 2, alignment=Qt.AlignmentFlag.AlignRight) - if item.detail: - detail = QLabel(item.detail) - detail.setObjectName("DiagnosisChatEventDetail") - detail.setTextFormat(Qt.TextFormat.PlainText) - detail.setWordWrap(True) - detail.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - content.addWidget(detail, 1, 1, 1, 2) - layout.addWidget(card, 4) - layout.addStretch(1) - return row + self.empty.setVisible(visible_count == 0) + + @staticmethod + def _event_row(item: ChatItem) -> QWidget: + row = QWidget() + layout = QHBoxLayout(row) + layout.setContentsMargins(0, 0, 0, 0) + layout.addStretch(1) + card = QFrame() + card.setObjectName("DiagnosisChatEvent") + card.setProperty("tone", item.tone) + card.setMaximumWidth(620) + card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) + content = QGridLayout(card) + content.setContentsMargins(12, 10, 12, 10) + content.setHorizontalSpacing(9) + content.setVerticalSpacing(4) + marker = QLabel(item.marker) + marker.setObjectName("DiagnosisChatEventMarker") + marker.setTextFormat(Qt.TextFormat.PlainText) + marker.setFixedWidth(22) + marker.setAlignment(Qt.AlignmentFlag.AlignCenter) + content.addWidget(marker, 0, 0) + title = QLabel(item.title) + title.setObjectName("DiagnosisChatEventTitle") + title.setTextFormat(Qt.TextFormat.PlainText) + title.setWordWrap(True) + content.addWidget(title, 0, 1) + content.setColumnStretch(1, 1) + if item.time_text: + time = QLabel(item.time_text) + time.setObjectName("DiagnosisChatMeta") + time.setTextFormat(Qt.TextFormat.PlainText) + content.addWidget(time, 0, 2, alignment=Qt.AlignmentFlag.AlignRight) + if item.detail: + detail = QLabel(item.detail) + detail.setObjectName("DiagnosisChatEventDetail") + detail.setTextFormat(Qt.TextFormat.PlainText) + detail.setWordWrap(True) + detail.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + content.addWidget(detail, 1, 1, 1, 2) + layout.addWidget(card, 4) + layout.addStretch(1) + return row @dataclass(frozen=True) @@ -3409,7 +3410,7 @@ class CaseGrid(QFrame): title_row.addWidget(self.title_label) self.subtitle = QLabel("病例 · 诊断日期 —") self.subtitle.setStyleSheet( - 'color:#606163;font-size:12px;' + 'color:#606163;font-size:12px;' ) title_row.addWidget(self.subtitle) title_row.addStretch(1) @@ -3419,7 +3420,7 @@ class CaseGrid(QFrame): if group_index: divider = QFrame() divider.setFrameShape(QFrame.Shape.HLine) - divider.setStyleSheet(clinical_stylesheet("border:0; border-top:1px solid $ds_line;")) + divider.setStyleSheet(clinical_stylesheet("border:0; border-top:1px solid $ds_line;")) self.root.addWidget(divider) group_title = QLabel(f"● {group_name}") group_title.setProperty("diagnosisCaseGroup", True) @@ -3577,11 +3578,11 @@ def readonly_card(title: str, object_name: str, body: QWidget) -> QFrame: def set_tag_item(item: QTableWidgetItem, kind: str) -> None: palette = { - "success": (PALETTE["success"], PALETTE["success_soft"]), - "warning": (PALETTE["warning"], PALETTE["warning_soft"]), - "danger": (PALETTE["danger"], PALETTE["danger_soft"]), - "info": (PALETTE["accent"], PALETTE["accent_soft"]), - "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), + "success": (PALETTE["success"], PALETTE["success_soft"]), + "warning": (PALETTE["warning"], PALETTE["warning_soft"]), + "danger": (PALETTE["danger"], PALETTE["danger_soft"]), + "info": (PALETTE["accent"], PALETTE["accent_soft"]), + "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), } foreground, background = palette.get(kind, palette["neutral"]) item.setForeground(QColor(foreground)) diff --git a/app/src/doctor_workstation/ui/dialogs/ai_consult.py b/app/src/doctor_workstation/ui/dialogs/ai_consult.py index 6d84945f6..2a56ec2c9 100755 --- a/app/src/doctor_workstation/ui/dialogs/ai_consult.py +++ b/app/src/doctor_workstation/ui/dialogs/ai_consult.py @@ -4790,14 +4790,25 @@ class AiConsultDialog(QDialog): layout.setSpacing(12) splitter = QSplitter(Qt.Orientation.Horizontal) - splitter.setChildrenCollapsible(False) + self._main_splitter = splitter + splitter.setChildrenCollapsible(True) splitter.addWidget(self._build_center()) - splitter.addWidget(self._build_right_pane()) + self._right_context_pane = self._build_right_pane() + splitter.addWidget(self._right_context_pane) splitter.setStretchFactor(0, 1) splitter.setStretchFactor(1, 0) splitter.setSizes([920, 460]) layout.addWidget(splitter, 1) + def resizeEvent(self, event: Any) -> None: # noqa: N802 + super().resizeEvent(event) + pane = getattr(self, "_right_context_pane", None) + if pane is not None and self.property("hostedInSpatialWing"): + # When docked as a narrow side-wing beside the live workstation, hide duplicate chart rail + want_visible = self.width() >= 860 + if pane.isVisible() != want_visible: + pane.setVisible(want_visible) + def _build_right_pane(self) -> QWidget: host = QWidget() host.setObjectName("AiConsultRightPane") diff --git a/app/src/doctor_workstation/ui/dialogs/diagnosis.py b/app/src/doctor_workstation/ui/dialogs/diagnosis.py index c54c1a4a7..a5dac8bdc 100755 --- a/app/src/doctor_workstation/ui/dialogs/diagnosis.py +++ b/app/src/doctor_workstation/ui/dialogs/diagnosis.py @@ -762,6 +762,11 @@ class OrderDetailDrawer(QDialog): QTimer.singleShot(0, self.sync_to_owner) def sync_to_owner(self) -> None: + if self.property("hostedInSpatialWing"): + self.scrim.hide() + self.drawer_panel.setMinimumWidth(0) + self.drawer_panel.setMaximumWidth(16777215) + return owner = self._owner if owner is not None: # The scrim is an overlay of its owner, including when that owner is @@ -909,6 +914,11 @@ class DiagnosisDialog(QDialog): self._loaded_tabs: set[str] = set() self._loading_tabs: set[str] = set() self._daily_todo_status: int | None = None + self._pending_focus_target: tuple[str, str, int | None] | None = None + self._highlighted_target: QWidget | None = None + self._highlight_timer = QTimer(self) + self._highlight_timer.setSingleShot(True) + self._highlight_timer.timeout.connect(self._clear_field_highlight) self._recording_players: list[RecordingPlayerDialog] = [] self._image_preview: ImagePreviewDialog | None = None self._inline_recording_cells: list[RecordingPlaybackCell] = [] @@ -950,11 +960,21 @@ class DiagnosisDialog(QDialog): ) self.setObjectName("DiagnosisDialogRoot") - if self._embedded: + from ..spatial_wings import find_spatial_shell, install_wing_dialog_support + + in_spatial_shell = not self._embedded and find_spatial_shell(parent) is not None + if self._embedded or in_spatial_shell: self.setWindowFlags(Qt.WindowType.Widget) self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, False) + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) self.setMinimumSize(0, 0) - self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Expanding) + self.setSizePolicy( + QSizePolicy.Policy.Ignored if self._embedded else QSizePolicy.Policy.Expanding, + QSizePolicy.Policy.Expanding, + ) + if in_spatial_shell: + self.setProperty("hostedInSpatialWing", True) + self.setProperty("doctorSkipOpenGeometry", True) else: self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint) self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground) @@ -962,6 +982,8 @@ class DiagnosisDialog(QDialog): self.resize(1024, 640) self.setWindowTitle("患者信息详情") self.setStyleSheet(DIAGNOSIS_QSS) + if not self._embedded: + install_wing_dialog_support(self, icon_kind="consultations", preferred_width=660) self.view_stack = QStackedLayout(self) self.view_stack.setContentsMargins(0, 0, 0, 0) @@ -1325,7 +1347,8 @@ class DiagnosisDialog(QDialog): self._studio_outline_layout.addWidget(btn) self._studio_outline_buttons.append(btn) self._studio_outline_layout.addStretch(1) - self.studio_outline.setVisible(self.tabs.count() > 1) + hide_in_wing = bool(self.property("hostedInSpatialWing")) and self.width() < 860 + self.studio_outline.setVisible(self.tabs.count() > 1 and not hide_in_wing) def _sync_studio_outline_selection(self, index: int) -> None: if len(self._studio_outline_buttons) != self.tabs.count(): @@ -1404,6 +1427,7 @@ class DiagnosisDialog(QDialog): def _build_basic_tab(self) -> QScrollArea: scroll = QScrollArea() + self._basic_scroll = scroll scroll.setObjectName("DiagnosisDrawerBody") scroll.setProperty("diagnosisTabKey", "basic") scroll.setWidgetResizable(True) @@ -1416,7 +1440,7 @@ class DiagnosisDialog(QDialog): content.setObjectName("DiagnosisTabBasic") content.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) content.setMinimumWidth(0) - content.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) + content.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) layout = QVBoxLayout(content) layout.setContentsMargins(20, 16, 20, 20) layout.setSpacing(8) @@ -1439,8 +1463,12 @@ class DiagnosisDialog(QDialog): form_layout.setSpacing(12) self.edit_fields: dict[str, Any] = {} self.display_fields: dict[str, Any] = {} + self._field_containers: dict[str, QWidget] = {} + self._section_headings: dict[int, QWidget] = {} for section_key, (title, rows) in enumerate(_FORM_SECTIONS): - form_layout.addWidget(section_heading(title, f"DiagnosisSection_{section_key}")) + sec_hdr = section_heading(title, f"DiagnosisSection_{section_key}") + self._section_headings[section_key] = sec_hdr + form_layout.addWidget(sec_hdr) for row_index, row_fields in enumerate(rows): row_host = QWidget() row_host.setSizePolicy( @@ -1460,6 +1488,7 @@ class DiagnosisDialog(QDialog): else: display = editor container = self._field_container(label, display, span, editor=editor) + self._field_containers[key] = container row_layout.addWidget(container, span) fields.append(container) occupied += span @@ -2046,8 +2075,15 @@ class DiagnosisDialog(QDialog): label.setFixedWidth(100) label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + def _is_wing_or_embedded(self) -> bool: + if self._embedded or bool(self.property("hostedInSpatialWing")): + return True + from ..spatial_wings import find_spatial_shell + + return find_spatial_shell(self) is not None + def _sync_host_geometry(self) -> None: - if self._embedded: + if self._is_wing_or_embedded(): return owner = self._owner if not self._standalone_readonly and owner is not None and owner is not self: @@ -2072,6 +2108,16 @@ class DiagnosisDialog(QDialog): def _update_drawer_geometry(self) -> None: if not hasattr(self, "drawer_panel"): return + if self._is_wing_or_embedded(): + scrim = getattr(self, "drawer_scrim", None) + if isinstance(scrim, QWidget): + scrim.hide() + w = max(360, self.width()) + self.drawer_panel.setMinimumWidth(0) + self.drawer_panel.setMaximumWidth(16777215) + self._reflow_form(w) + self._sync_choice_field_heights() + return drawer_width = self.width() if self.width() <= 768 else max(456, round(self.width() * 0.60)) self.drawer_panel.setFixedWidth(drawer_width) # Reflow against the actual drawer content width, not the fullscreen overlay. @@ -2092,7 +2138,7 @@ class DiagnosisDialog(QDialog): layout.addWidget(self.readonly_hero_right, 0, 1, Qt.AlignmentFlag.AlignRight) def _install_owner_filter(self) -> None: - if self._embedded: + if self._is_wing_or_embedded(): return if self._owner is not None and not self._owner_filter_installed: self._owner.installEventFilter(self) @@ -2101,7 +2147,7 @@ class DiagnosisDialog(QDialog): def _rebind_owner(self) -> None: """Resolve the live Shell window for every open/show cycle.""" - if self._embedded: + if self._is_wing_or_embedded(): self._owner = None self._owner_filter_installed = False return @@ -2127,13 +2173,14 @@ class DiagnosisDialog(QDialog): super().resizeEvent(event) def showEvent(self, event: Any) -> None: - if not self._embedded: + if not self._is_wing_or_embedded(): self._rebind_owner() self._sync_host_geometry() self._update_drawer_geometry() self._reflow_readonly_hero() super().showEvent(event) - self._queue_owner_sync() + if not self._is_wing_or_embedded(): + self._queue_owner_sync() def _queue_owner_sync(self) -> None: generation = self._generation @@ -2253,6 +2300,8 @@ class DiagnosisDialog(QDialog): self._local_audio_dialog = None self._diagnosis_id = int(diagnosis_id) self._patient_id = 0 + self._pending_focus_target = None + self._clear_field_highlight() self._editable = bool( editable and has_permission(self.permissions, "tcm.diagnosis/edit", default=True) ) @@ -2306,10 +2355,14 @@ class DiagnosisDialog(QDialog): ) self.title_label.setText("编辑诊单" if self._editable else "诊单详情") self.mode_label.setText("编辑" if self._editable else "只读") - self.mode_label.setProperty("kind", "warning" if self._editable else "info") - repolish(self.mode_label) - self.drawer_panel.setProperty("mode", "edit" if self._editable else "viewOnly") - repolish(self.drawer_panel) + want_kind = "warning" if self._editable else "info" + if self.mode_label.property("kind") != want_kind: + self.mode_label.setProperty("kind", want_kind) + repolish(self.mode_label) + want_mode = "edit" if self._editable else "viewOnly" + if self.drawer_panel.property("mode") != want_mode: + self.drawer_panel.setProperty("mode", want_mode) + repolish(self.drawer_panel) self.close_button.setText("取消" if self._editable else "关闭") for timeline in self._notes_timelines: timeline.set_editable( @@ -2496,6 +2549,90 @@ class DiagnosisDialog(QDialog): self._load_visible_readonly_sections() else: self._ensure_tab_loaded(self._current_tab_key()) + if self._pending_focus_target is not None: + t_key, f_key, s_idx = self._pending_focus_target + self._pending_focus_target = None + self._apply_clinical_target(t_key, field_key=f_key, section_index=s_idx) + + def _clear_field_highlight(self) -> None: + if self._highlighted_target is not None: + with suppress(RuntimeError): + self._highlighted_target.setStyleSheet("") + self._highlighted_target = None + + def focus_clinical_target( + self, + tab_key: str = "basic", + *, + field_key: str = "", + section_index: int | None = None, + ) -> None: + """Switch to `tab_key` and scroll/highlight `field_key` or `section_index`.""" + + if not self._authoritative_detail_loaded: + self._pending_focus_target = (tab_key, field_key, section_index) + self._apply_clinical_target(tab_key, field_key=field_key, section_index=section_index) + + def _apply_clinical_target( + self, + tab_key: str = "basic", + *, + field_key: str = "", + section_index: int | None = None, + ) -> None: + resolved_tab = tab_key or "basic" + matched_idx = -1 + if hasattr(self, "tabs"): + for i in range(self.tabs.count()): + if self.tabs.tabBar().tabData(i) == resolved_tab: + matched_idx = i + break + if matched_idx < 0: + resolved_tab = "basic" + for i in range(self.tabs.count()): + if self.tabs.tabBar().tabData(i) == "basic": + matched_idx = i + break + if matched_idx >= 0 and self.tabs.currentIndex() != matched_idx: + self.tabs.setCurrentIndex(matched_idx) + + if resolved_tab != "basic": + return + + scroll = getattr(self, "_basic_scroll", None) + if scroll is None or scroll.widget() is None: + return + target: QWidget | None = None + if section_index is not None: + target = self._section_headings.get(section_index) + if field_key and field_key in self._field_containers: + target = self._field_containers[field_key] + if target is None: + scroll.verticalScrollBar().setValue(0) + return + + def _do_scroll() -> None: + with suppress(RuntimeError): + if scroll.widget() is None or not target.isVisibleTo(scroll.widget()): + if scroll.widget() is not None and scroll.widget().layout() is not None: + scroll.widget().layout().activate() + if self.form_host.layout() is not None: + self.form_host.layout().activate() + y_pos = target.mapTo(scroll.widget(), target.rect().topLeft()).y() + scroll.verticalScrollBar().setValue(max(0, y_pos - 22)) + self._clear_field_highlight() + target.setStyleSheet( + "background-color: #E7F5F0; border-radius: 10px; padding: 3px 6px;" + ) + self._highlighted_target = target + self._highlight_timer.start(1600) + if self._editable and field_key in self.edit_fields: + ed = self.edit_fields[field_key] + if isinstance(ed, QWidget) and ed.isEnabled(): + ed.setFocus() + + _do_scroll() + QTimer.singleShot(30, _do_scroll) def _load_error(self, error: Exception, generation: int) -> None: if generation == self._generation: @@ -2552,7 +2689,6 @@ class DiagnosisDialog(QDialog): editor._sync_flow_height() if hasattr(self, "form_host"): self.form_host.updateGeometry() - self.form_host.adjustSize() def _show_authoritative_content(self, visible: bool) -> None: self.readonly_patient_card.setVisible(visible) @@ -2587,8 +2723,10 @@ class DiagnosisDialog(QDialog): or (key in _PATIENT_BASIC_FIELDS and self._basic_locked) or (key in {"phone", "id_card"} and not self._can_phone_plain) ) + was_locked = field.isReadOnly() if callable(getattr(field, "isReadOnly", None)) else None field.setReadOnly(locked) - repolish(field) + if was_locked != locked and not isinstance(field, DiagnosisChoiceButtons): + repolish(field) def _current_tab_key(self) -> str: index = self.tabs.currentIndex() diff --git a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py index 30f88d7f0..40aa747f5 100755 --- a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py +++ b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py @@ -563,11 +563,14 @@ class IssuedPrescriptionAiDialog(QDialog): self._history_agreement_visible = False self.setWindowTitle("诊断与药方 · AI 分析报告") self.resize(1440, 940) - self.setMinimumSize(940, 640) + self.setMinimumSize(540, 480) font = QFont(body_family()) font.setPixelSize(13) self.setFont(font) self.setStyleSheet(dialog_style() + rail_qss()) + from ..spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(self, icon_kind="ai", preferred_width=680) self._permissions_snapshot = permissions self._current_user = current_user self._pending_drafts: dict[str, tuple[str, int]] = {} diff --git a/app/src/doctor_workstation/ui/dialogs/prescription.py b/app/src/doctor_workstation/ui/dialogs/prescription.py index 7c61aefb9..95f3092c9 100755 --- a/app/src/doctor_workstation/ui/dialogs/prescription.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription.py @@ -3987,6 +3987,21 @@ class PrescriptionEditorDialog(QDialog): self._fit_drawer_geometry() def _fit_drawer_geometry(self) -> None: + if self.property("hostedInSpatialWing"): + self.drawer_surface.setMaximumWidth(16777215) + w = max(460, self.width()) + show_live_slip = w >= 860 + if hasattr(self, "live_preview_pane"): + self.live_preview_pane.setVisible(show_live_slip) + if self.diagnosis_host.isVisible(): + half = max(260, w // 2) + self.workspace_splitter.setSizes([half, w - half, 0]) + elif show_live_slip: + slip_w = min(320, int(w * 0.36)) + self.workspace_splitter.setSizes([0, w - slip_w, slip_w]) + else: + self.workspace_splitter.setSizes([0, w, 0]) + return target = main_window_target_rect(self) if target is not None: width = target.width() @@ -4021,6 +4036,11 @@ class PrescriptionEditorDialog(QDialog): super().showEvent(event) self._fit_drawer_geometry() + def resizeEvent(self, event: Any) -> None: # noqa: N802 + super().resizeEvent(event) + if self.property("hostedInSpatialWing"): + self._fit_drawer_geometry() + def _update_herb_summary(self) -> None: if not hasattr(self, "herbs"): return @@ -6149,8 +6169,11 @@ class PrescriptionDetailDialog(QDialog): self.user_document.setDocumentMargin(0) self._render_slip_previews() self.setWindowTitle("查看处方") - self.setMinimumSize(900, 700) + self.setMinimumSize(460, 480) self.resize(1240, 800) + from ..spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(self, icon_kind="prescriptions", preferred_width=660) # 与「处方电子签署」一致:左侧三联预览,右侧签署流程与操作。 root = QVBoxLayout(self) root.setContentsMargins(0, 0, 0, 0) @@ -6325,6 +6348,15 @@ class PrescriptionDetailDialog(QDialog): if callable(getattr(self.repository, "get_prescription_esign_status", None)): self.refresh_esign() + def resizeEvent(self, event: Any) -> None: # noqa: N802 + super().resizeEvent(event) + if self.property("hostedInSpatialWing") and hasattr(self, "workspace_splitter"): + want_orient = ( + Qt.Orientation.Vertical if self.width() < 780 else Qt.Orientation.Horizontal + ) + if self.workspace_splitter.orientation() != want_orient: + self.workspace_splitter.setOrientation(want_orient) + def _render_steps(self) -> None: legacy = self.esign.get("status") == "legacy" and self.esign.get("required") is False awaiting_upload = awaiting_prescription_upload(self.prescription, self.esign) diff --git a/app/src/doctor_workstation/ui/dialogs/prescription_ai.py b/app/src/doctor_workstation/ui/dialogs/prescription_ai.py index d11f2a47b..2c9ca9aa2 100755 --- a/app/src/doctor_workstation/ui/dialogs/prescription_ai.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription_ai.py @@ -744,9 +744,12 @@ class PrescriptionAiReportDialog(QDialog): self.setObjectName("PrescriptionAiDialog") self.setWindowTitle(self.kind.title) self.resize(920, 760) - self.setMinimumSize(720, 560) + self.setMinimumSize(460, 440) self.setStyleSheet(PRESCRIPTION_AI_QSS) self.setCursor(Qt.CursorShape.ArrowCursor) + from ..spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(self, icon_kind="ai", preferred_width=560) root = QVBoxLayout(self) root.setContentsMargins(22, 18, 22, 18) @@ -1482,8 +1485,11 @@ class DiagnosisAiAssistantDialog(QDialog): self.setObjectName("PrescriptionAiDialog") self.setWindowTitle("AI 问诊助手") self.resize(720, 520) - self.setMinimumSize(580, 420) + self.setMinimumSize(440, 380) self.setStyleSheet(PRESCRIPTION_AI_QSS) + from ..spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(self, icon_kind="ai", preferred_width=520) root = QVBoxLayout(self) root.setContentsMargins(22, 20, 22, 20) diff --git a/app/src/doctor_workstation/ui/dialogs/video_cockpit.py b/app/src/doctor_workstation/ui/dialogs/video_cockpit.py index 201cc0c96..2b32ad594 100644 --- a/app/src/doctor_workstation/ui/dialogs/video_cockpit.py +++ b/app/src/doctor_workstation/ui/dialogs/video_cockpit.py @@ -181,7 +181,7 @@ class VideoCockpitDemoDialog(QDialog): def _capture_demo_tongue(self) -> None: self._tongue_count += 1 - self._tongue_status.setText(f"✓ 已抓拍第 {self._tongue_count} 帧高清舌象并准备归档") + self._tongue_status.setText(f"已抓拍第 {self._tongue_count} 帧高清舌象并准备归档") def _tick(self) -> None: self._seconds += 1 diff --git a/app/src/doctor_workstation/ui/icons.py b/app/src/doctor_workstation/ui/icons.py index dd757fa25..20875aac7 100755 --- a/app/src/doctor_workstation/ui/icons.py +++ b/app/src/doctor_workstation/ui/icons.py @@ -361,6 +361,15 @@ def _right(p: QPainter, w: float) -> None: _polyline(p, (9.0, 5.5), (15.5, 12.0), (9.0, 18.5)) +@_glyph("play") +def _play(p: QPainter, w: float) -> None: + path = QPainterPath(QPointF(8.5, 5.75)) + path.lineTo(QPointF(18.25, 12.0)) + path.lineTo(QPointF(8.5, 18.25)) + path.closeSubpath() + _duotone_path(p, path, 44) + + @_glyph("notification", "bell") def _bell(p: QPainter, w: float) -> None: path = QPainterPath(QPointF(6.75, 17.5)) diff --git a/app/src/doctor_workstation/ui/pages/consultations.py b/app/src/doctor_workstation/ui/pages/consultations.py index 37b4c3f02..225a28eb6 100755 --- a/app/src/doctor_workstation/ui/pages/consultations.py +++ b/app/src/doctor_workstation/ui/pages/consultations.py @@ -3212,6 +3212,8 @@ class ConsultationsPage(QWidget): self.cancel_toolbar_button.setEnabled( has_record and _single_cancellable_appointment(record) is not None ) + if self.patient_context_store is not None and record is not None: + self.patient_context_store.update_from_row(record) @property def _diagnosis_dialog(self) -> DiagnosisDialog: diff --git a/app/src/doctor_workstation/ui/pages/reception.py b/app/src/doctor_workstation/ui/pages/reception.py index 3b1db4075..2098c22dc 100755 --- a/app/src/doctor_workstation/ui/pages/reception.py +++ b/app/src/doctor_workstation/ui/pages/reception.py @@ -92,9 +92,11 @@ from ..filter_disclosure import FilterDisclosure from ..reception_style import body_family, heading_family, number_family from ..reception_workspace import RECEPTION_WORKSPACE_QSS, ReceptionWorkbench from ..report_provenance import report_provenance_lines +from ..spatial_wings import find_spatial_shell from ..state import PatientContextStore from ..theme import mark_business_dialog from ..viewmodels.cockpit_vm import derive_cockpit_snapshot +from ..visuals.ai_report_wing import ClinicalAiReportWingPanel from ..visuals.reception_cockpit import ReceptionDigitalTwinCockpit from ..widgets import ( EmptyState, @@ -4275,6 +4277,15 @@ class ReceptionPage(QWidget): self.patient_context_store: PatientContextStore | None = None self._workspace_mode = "chart" self._latest_daily_blood: list[Any] = [] + self._latest_daily_window: dict[str, Any] = {} + self._latest_doctor_notes: list[Any] = [] + self._latest_prescriptions: list[Any] = [] + self._cockpit_queue_scope: str = "today_all" + self._cockpit_auto_fallback_done: bool = False + self._cockpit_consult_fallback_done: bool = False + self._cockpit_fallback_notice: str = "" + self._syncing_patient_store: bool = False + self._wing_ai_report_panel: ClinicalAiReportWingPanel | None = None self.view_mode_stack = QStackedWidget(self) self.view_mode_stack.setObjectName("ReceptionViewModeStack") @@ -4296,7 +4307,7 @@ class ReceptionPage(QWidget): ret_layout = QHBoxLayout(self._return_to_cockpit_bar) ret_layout.setContentsMargins(10, 4, 14, 4) ret_layout.setSpacing(10) - back_cockpit_btn = QPushButton("← 返回三焦全息驾驶舱", self._return_to_cockpit_bar) + back_cockpit_btn = QPushButton("← 返回临床接诊总览", self._return_to_cockpit_bar) back_cockpit_btn.setCursor(Qt.CursorShape.PointingHandCursor) back_cockpit_btn.setStyleSheet( "QPushButton { background-color: #0E6F5C; color: #FFFFFF; border: 0;" @@ -4330,9 +4341,11 @@ class ReceptionPage(QWidget): self.cockpit_view = ReceptionDigitalTwinCockpit(self.view_mode_stack) self.cockpit_view.appointment_selected.connect(self._select_record_from_cockpit) self.cockpit_view.filter_status_requested.connect(self._set_queue_filter) + self.cockpit_view.queue_scope_requested.connect(self.set_cockpit_queue_scope) self.cockpit_view.refresh_requested.connect(self._refresh_workspace) self.cockpit_view.start_video_requested.connect(self._request_video) self.cockpit_view.edit_diagnosis_requested.connect(self._edit_diagnosis) + self.cockpit_view.locus_selected.connect(self._open_diagnosis_for_locus) self.cockpit_view.notify_assistant_requested.connect(self._notify_assistant) self.cockpit_view.complete_visit_requested.connect(self._complete_appointment) self.cockpit_view.open_chart_tab_requested.connect(self._open_structured_chart_tab) @@ -4359,10 +4372,15 @@ class ReceptionPage(QWidget): panel.setFixedWidth(width) def set_patient_context_store(self, store: PatientContextStore) -> None: - """Attach the Spatial Shell context store and default to Digital Twin Cockpit.""" + """Attach the Spatial Shell context store and default to Clinical Cockpit.""" self.patient_context_store = store self._root_layout.setContentsMargins(0, 2, 0, 2) + self._cockpit_queue_scope = "today_all" + self._cockpit_auto_fallback_done = False + self._cockpit_consult_fallback_done = False + self._cockpit_fallback_notice = "" + self._queue_date = date.today().isoformat() self._queue_filter_status = None for st_key, btn in self._queue_filter_buttons.items(): btn.setChecked(st_key is None) @@ -4370,6 +4388,77 @@ class ReceptionPage(QWidget): self.set_workspace_mode("cockpit") self._sync_cockpit_and_context() + def set_cockpit_queue_scope(self, scope: str, *, keep_notice: bool = False) -> None: + """Switch outpatient queue scope in Spatial Cockpit mode.""" + + normalized = str(scope or "today_all").strip().lower() + if normalized not in {"today_pending", "today_all", "recent_all", "consultations"}: + normalized = "today_all" + self._cockpit_queue_scope = normalized + if not keep_notice: + self._cockpit_fallback_notice = "" + # Explicit doctor scope switch disables further automatic scope jumps + self._cockpit_auto_fallback_done = True + self._cockpit_consult_fallback_done = True + + if normalized == "today_pending": + self._queue_date = date.today().isoformat() + self._queue_filter_status = 1 + elif normalized == "today_all": + self._queue_date = date.today().isoformat() + self._queue_filter_status = None + else: + self._queue_date = "" + self._queue_filter_status = None + + for st_key, btn in self._queue_filter_buttons.items(): + btn.setChecked(st_key == self._queue_filter_status) + self._clear_selection() + self._reset_queue_state() + ReceptionPage.refresh(self) + + def load_patient_from_context(self, snapshot: Any) -> None: + """Load full clinical bundle when a patient is selected in another Spatial tab.""" + + if self._syncing_patient_store or snapshot is None or not getattr(snapshot, "has_patient", False): + return + appt_id = _as_int(getattr(snapshot, "appointment_id", 0), 0) or 0 + diag_id = _as_int(getattr(snapshot, "diagnosis_id", 0), 0) or 0 + pat_id = _as_int(getattr(snapshot, "patient_id", 0), 0) or 0 + if appt_id > 0: + if _same_id(appt_id, self._selected_appointment_id): + return + seed = dict(getattr(snapshot, "raw_record", None) or {}) + seed.update( + { + "id": appt_id, + "appointment_id": appt_id, + "diagnosis_id": diag_id or seed.get("diagnosis_id"), + "patient_id": pat_id or seed.get("patient_id"), + "patient_name": getattr(snapshot, "patient_name", "患者"), + } + ) + self._select_record(seed, silent=True) + return + if diag_id > 0: + synthetic_id = -abs(diag_id) + if _same_id(synthetic_id, self._selected_appointment_id): + return + seed = dict(getattr(snapshot, "raw_record", None) or {}) + seed.update( + { + "_queue_source": "consultation", + "id": synthetic_id, + "real_appointment_id": 0, + "diagnosis_id": diag_id, + "patient_id": pat_id or seed.get("patient_id"), + "patient_name": getattr(snapshot, "patient_name", "患者"), + "status": 1, + "status_desc": getattr(snapshot, "status_text", "在管诊单") or "在管诊单", + } + ) + self._select_record(seed, silent=True) + def set_workspace_mode(self, mode: str) -> None: normalized = "cockpit" if str(mode).strip().lower() == "cockpit" else "chart" self._workspace_mode = normalized @@ -4382,7 +4471,70 @@ class ReceptionPage(QWidget): if self.patient_context_store is not None: self.patient_context_store.set_cockpit_mode(normalized) + def _open_diagnosis_for_locus(self, locus_id: str) -> None: + """Open DiagnosisDialog directly at the corresponding tab & clinical field for `locus_id`.""" + + locus_map: dict[str, tuple[str, str, int | None]] = { + # Tab 1: 全身症候 + "head_eye_sleep": ("basic", "sleep_condition", 3), + "oral_thirst": ("basic", "appetite", 3), + "liver_pancreas_spleen": ("basic", "weight_change", 3), + "kidney_limbs": ("basic", "urine_condition", 3), + # Tab 2: 病史用药 + "local_diagnosis": ("basic", "local_hospital_diagnosis", 2), + "current_meds": ("basic", "current_medications", 1), + "past_history": ("basic", "past_history", 4), + "allergy_family": ("basic", "allergy_history", 5), + # Tab 3: 四诊处方 + "tongue_pulse": ("notes", "", None), + "notes_media": ("notes", "", None), + "rx_summary": ("prescription", "", None), + "rx_principle": ("prescription", "", None), + # Summary & Glycemic Cards + "summary_capsule": ("basic", "", 0), + "daily_glucose": ("daily", "", None), + } + if locus_id.startswith("vital:"): + v_field = locus_id.split(":", 1)[1].strip() or "systolic_pressure" + tab_key, field_key, sec_idx = ("basic", v_field, 1) + else: + tab_key, field_key, sec_idx = locus_map.get(locus_id, ("basic", "", None)) + + context = self._selection_context() + if context is None or context[2] is None or context[2] <= 0: + show_toast(self, "请先选择有效诊单患者。", "warning") + return + diag_id = int(context[2]) + dlg = self._ensure_diagnosis_dialog() + shell = find_spatial_shell(self) + already_open_same = ( + shell is not None + and shell.wing_manager.is_open + and shell.wing_manager.active_widget is dlg + and getattr(dlg, "_diagnosis_id", 0) == diag_id + ) + if not already_open_same: + if self._can_edit: + dlg.open_for( + diag_id, + editable=True, + seed=self._selected_detail or self._selected_record, + modeless=shell is not None, + ) + else: + dlg.open_view_only( + diag_id, + seed=self._selected_detail or self._selected_record, + modeless=shell is not None, + ) + dlg.focus_clinical_target(tab_key, field_key=field_key, section_index=sec_idx) + def _open_structured_chart_tab(self, tab_index: int = 0) -> None: + if find_spatial_shell(self) is not None: + tab_key = "daily" if tab_index == 3 else ("notes" if tab_index == 2 else "basic") + locus_for_tab = "daily_glucose" if tab_key == "daily" else ("notes_media" if tab_key == "notes" else "summary_capsule") + self._open_diagnosis_for_locus(locus_for_tab) + return self.set_workspace_mode("chart") if hasattr(self, "detail_tabs") and 0 <= tab_index < self.detail_tabs.count(): self.detail_tabs.setCurrentIndex(tab_index) @@ -4412,58 +4564,110 @@ class ReceptionPage(QWidget): self._sync_cockpit_and_context() def _sync_cockpit_and_context(self) -> None: - """Synchronize the 3-column Digital Twin Cockpit and global PatientContextStore.""" + """Synchronize the 3-column Clinical Cockpit and global PatientContextStore.""" if not hasattr(self, "cockpit_view"): return detail = self._selected_detail or {} - appointment = get_value(detail, "appointment", None) or self._selected_record or {} - patient = get_value(detail, "patient", None) or {} - diagnosis = get_value(detail, "diagnosis", None) or {} + has_loaded_patient = self._selected_appointment_id is not None and bool( + self._selected_detail or self._selected_record + ) + appointment = ( + (get_value(detail, "appointment", None) or self._selected_record or {}) + if has_loaded_patient + else {} + ) + patient = (get_value(detail, "patient", None) or {}) if has_loaded_patient else {} + diagnosis = (get_value(detail, "diagnosis", None) or {}) if has_loaded_patient else {} self.cockpit_view.set_queue_records( self._queue_records, self._selected_appointment_id, + active_scope=self._cockpit_queue_scope, active_filter_status=self._queue_filter_status, queue_date=self._queue_date, + scope_notice=self._cockpit_fallback_notice, ) doc_name = display_text( first_value( appointment, "doctor_name", - default=first_value(self.current_user, "name", "real_name", default="主诊中医师"), + default=first_value( + diagnosis, + "doctor_name", + default=first_value(self.current_user, "name", "real_name", default="主诊中医师"), + ), ) ) - asst_name = display_text(first_value(appointment, "assistant_name", default=""), "") + asst_name = display_text( + first_value( + appointment, + "assistant_name", + default=first_value(diagnosis, "assistant_name", default=""), + ), + "", + ) + diag_id = _as_int( + first_value( + diagnosis, + "id", + "diagnosis_id", + default=first_value(appointment, "diagnosis_id", default=None), + ) + ) + real_appt = bool(self._selected_appointment_id is not None and self._selected_appointment_id > 0) self.cockpit_view.set_care_team_context( doctor_name=doc_name, assistant_name=asst_name, - can_edit=bool(self._can_edit and self._selected_appointment_id is not None), - can_notify=bool(self._selected_appointment_id is not None), + can_edit=bool(self._can_edit and has_loaded_patient and diag_id is not None and diag_id > 0), + can_notify=real_appt, can_complete=bool( - hasattr(self, "complete_button") and self.complete_button.isEnabled() + real_appt and hasattr(self, "complete_button") and self.complete_button.isEnabled() ), ) if self.patient_context_store is not None: - if self._selected_appointment_id is not None and appointment: - self.patient_context_store.update_from_reception(appointment, patient, diagnosis) - elif not self._queue_records: - self.patient_context_store.clear() + self._syncing_patient_store = True + try: + if has_loaded_patient and appointment: + self.patient_context_store.update_from_reception(appointment, patient, diagnosis) + elif not self._queue_records and not has_loaded_patient: + self.patient_context_store.clear() + finally: + self._syncing_patient_store = False - ai_payload = self._ai_analysis_payloads.get(self._ai_analysis_active_model) + active_model = self._ai_analysis_active_model + ai_state = self._ai_analysis_model_states.get(active_model, "empty") + ai_msg = self._ai_analysis_model_messages.get(active_model, "") + ai_payload = self._ai_analysis_payloads.get(active_model) vm = derive_cockpit_snapshot( - appointment, - patient, - diagnosis, - daily_records=self._latest_daily_blood, - ai_payload=ai_payload, - active_ai_model=self._ai_analysis_active_model, + appointment if has_loaded_patient else None, + patient if has_loaded_patient else None, + diagnosis if has_loaded_patient else None, + daily_window=self._latest_daily_window if has_loaded_patient else None, + daily_records=self._latest_daily_blood if has_loaded_patient else None, + tracking_notes=self._daily_tracking_fallback if has_loaded_patient else None, + doctor_notes=self._latest_doctor_notes if has_loaded_patient else None, + prescriptions=self._latest_prescriptions if has_loaded_patient else None, + ai_payload=ai_payload if has_loaded_patient else None, + ai_state=ai_state if has_loaded_patient else "empty", + ai_message=ai_msg if has_loaded_patient else "", + active_ai_model=active_model, ) self.cockpit_view.set_snapshot(vm) self.cockpit_snapshot_updated.emit(vm) + self._sync_wing_ai_report_panel() def _ensure_diagnosis_dialog(self) -> DiagnosisDialog: + shell = find_spatial_shell(self) + ensure_global = getattr(shell, "_ensure_global_diagnosis_dialog", None) + if callable(ensure_global): + shared = ensure_global() + if not getattr(shared, "_reception_saved_wired", False): + shared.saved.connect(self._diagnosis_saved) + shared._reception_saved_wired = True # type: ignore[attr-defined] + self.diagnosis_dialog = shared + return shared dialog = getattr(self, "diagnosis_dialog", None) if dialog is None: dialog = DiagnosisDialog(self.repository, self) @@ -5977,6 +6181,7 @@ class ReceptionPage(QWidget): self.ai_analysis_card.setProperty("analysisState", state) self.ai_analysis_card.style().unpolish(self.ai_analysis_card) self.ai_analysis_card.style().polish(self.ai_analysis_card) + self._sync_wing_ai_report_panel() self._sync_cockpit_and_context() def _render_ai_analysis_payload( @@ -7229,9 +7434,88 @@ class ReceptionPage(QWidget): force=True, ) - def _open_ai_analysis_dialog(self) -> None: - """Show the full cached analysis without issuing another model request.""" + def _current_patient_display_name(self) -> str: + detail = self._selected_detail or {} + appt = get_value(detail, "appointment", None) or self._selected_record or {} + diag = get_value(detail, "diagnosis", None) or {} + pat = get_value(detail, "patient", None) or {} + name = display_text( + first_value( + appt, + "patient_name", + "name", + default=first_value( + diag, + "patient_name", + "name", + default=first_value(pat, "patient_name", "name", default=""), + ), + ), + "", + ) + return "" if name in {"", "—"} else name + def _sync_wing_ai_report_panel(self) -> None: + panel = self._wing_ai_report_panel + if panel is None: + return + shell = find_spatial_shell(self) + is_hosted = shell is not None and shell.wing_manager.active_widget is panel + if not panel.isVisible() and not is_hosted: + return + can_regen = bool( + (self._can_ai_regenerate and self._ai_analysis_patient_flow and self._ai_analysis_patient_id is not None) + or (self._can_ai_analysis and not self._ai_analysis_patient_flow and self._ai_analysis_diagnosis_id is not None) + ) + panel.set_report_context( + histories=self._ai_analysis_histories, + model_states=self._ai_analysis_model_states, + model_messages=self._ai_analysis_model_messages, + active_model=self._ai_analysis_active_model, + patient_name=self._current_patient_display_name(), + can_regenerate=can_regen and not self._ai_analysis_regenerating, + ) + + def _trigger_wing_ai_regenerate(self) -> None: + if self._ai_analysis_patient_flow and self._can_ai_regenerate: + self._regenerate_patient_ai_reports() + else: + self._retry_ai_analysis() + + def _ensure_wing_ai_report_panel(self) -> ClinicalAiReportWingPanel: + if self._wing_ai_report_panel is None: + panel = ClinicalAiReportWingPanel(self) + panel.hide() + panel.model_selected.connect(self.select_cockpit_ai_model) + panel.regenerate_requested.connect(self._trigger_wing_ai_regenerate) + panel.open_ai_consult_requested.connect(self._open_ai_consult) + self._wing_ai_report_panel = panel + return self._wing_ai_report_panel + + def open_ai_report_wing(self) -> bool: + """Open the high-density Clinical AI Report Companion Wing beside the cockpit.""" + + shell = find_spatial_shell(self) + if shell is None: + return False + panel = self._ensure_wing_ai_report_panel() + + p_name = self._current_patient_display_name() + shell.wing_manager.present_widget( + panel, + title="AI 循证诊断报告", + subtitle=p_name, + icon_kind="ai", + preferred_width=540, + ) + self._sync_wing_ai_report_panel() + return True + + def _open_ai_analysis_dialog(self) -> None: + """Show the full cached analysis in Spatial Wing (or legacy dialog in standalone tests).""" + + if self.open_ai_report_wing(): + return if not self._ai_analysis_payloads: return preferred_model = self._ai_analysis_active_model @@ -7294,18 +7578,24 @@ class ReceptionPage(QWidget): def _sync_queue_filter_summary(self) -> None: status = STATUS_TEXT.get(self._queue_filter_status, "全部状态") today = date.today().isoformat() - self.queue_title.setText( - "历史接诊" if self._queue_date < today else - "今日接诊" if self._queue_date == today else "预约接诊" - ) - summary = f"{self._queue_date} · {status}" + if not self._queue_date: + scope_title = "在管诊单" if self._cockpit_queue_scope == "consultations" else "近期挂号" + self.queue_title.setText(scope_title) + date_prefix = scope_title + else: + self.queue_title.setText( + "历史接诊" if self._queue_date < today else + "今日接诊" if self._queue_date == today else "预约接诊" + ) + date_prefix = self._queue_date + summary = f"{date_prefix} · {status}" keyword = self.search_edit.text().strip() self.queue_filter_summary.setText(summary + (" · 姓名已筛选" if keyword else "")) self.queue_filter_summary.setToolTip(summary + (f" · 姓名:{keyword}" if keyword else "")) if hasattr(self, "queue_empty_description"): conditions = f"{status}、当前姓名" if keyword else status self.queue_empty_description.setText( - f"{self._queue_date}\n当前账号在“{conditions}”筛选下没有挂号记录。" + f"{date_prefix}\n当前账号在“{conditions}”筛选下没有挂号记录。" ) def _search_changed(self, value: str) -> None: @@ -7439,13 +7729,19 @@ class ReceptionPage(QWidget): if silent and self._queue_loading and not workspace_refresh: return - selected_date = self._queue_date or date.today().isoformat() + if self.patient_context_store is not None and self._cockpit_queue_scope in { + "recent_all", + "consultations", + }: + selected_date = "" + else: + selected_date = self._queue_date or date.today().isoformat() page_size = self._queue_page_size if silent or workspace_refresh: loaded = max(len(self._queue_records), self._queue_page * self._queue_page_size) if loaded > page_size: page_size = loaded - query = { + query: dict[str, Any] = { "status": self._queue_filter_status, "start_date": selected_date, "end_date": selected_date, @@ -7454,6 +7750,8 @@ class ReceptionPage(QWidget): "patient_name": self.search_edit.text().strip(), "include_status_counts": 1, } + if self.patient_context_store is not None: + query["_cockpit_scope"] = self._cockpit_queue_scope self._sync_queue_filter_summary() query_key = self._query_key(query) if query_key != self._queue_query_key: @@ -7484,8 +7782,58 @@ class ReceptionPage(QWidget): query["start_date"], query["end_date"], query["patient_name"], + query.get("_cockpit_scope", ""), ) + @staticmethod + def _consultation_to_queue_record(item: Any) -> dict[str, Any]: + """Adapt a Consultation list item into a selectable queue record.""" + + raw = getattr(item, "raw", None) + base: dict[str, Any] = dict(raw) if isinstance(raw, Mapping) else {} + if isinstance(item, Mapping): + base.update(item) + diag_id = _as_int( + first_value(item, "id", "diagnosis_id", default=base.get("id")), + 0, + ) or 0 + appt_id = _as_int( + first_value( + base, + "latest_appointment_id", + "appointment_id", + default=0, + ), + 0, + ) or 0 + record_id = appt_id if appt_id > 0 else (-abs(diag_id) if diag_id > 0 else 0) + pat_id = _as_int( + first_value(item, "patient_id", "source_patient_id", default=base.get("patient_id")), + 0, + ) or 0 + pat_name = display_text( + first_value(item, "patient_name", "name", default=base.get("patient_name") or "患者") + ) + base.update( + { + "_queue_source": "consultation", + "id": record_id, + "real_appointment_id": appt_id, + "diagnosis_id": diag_id, + "patient_id": pat_id, + "source_patient_id": pat_id, + "patient_name": pat_name, + "status": _as_int( + first_value(base, "appointment_status", "status", default=1), 1 + ) + or 1, + "status_desc": display_text( + first_value(base, "appointment_status_desc", "status_desc", default="在管诊单") + ), + } + ) + return base + def _reset_queue_state(self) -> None: self._queue_records = [] self._queue_render_signature = () @@ -7633,11 +7981,32 @@ class ReceptionPage(QWidget): # 每刷新一次表格就上下跳一次——而轮询定时器每 5 秒就刷新一次。 # 已有数据时保持旧行可见、静默替换;失败仍然照常报错。 frozen_query = dict(query) + cockpit_scope = str(frozen_query.pop("_cockpit_scope", "") or "") page_no = int(frozen_query["page_no"]) - query_key = self._query_key(frozen_query) + query_key = self._query_key(query) + def request() -> Any: if generation != self._queue_generation: return _ASYNC_REQUEST_CANCELLED + if cockpit_scope == "consultations" and callable( + getattr(self.repository, "list_consultations", None) + ): + consult_res = invoke( + self.repository, + "list_consultations", + page_no=page_no, + page_size=int(frozen_query["page_size"]), + keyword=frozen_query.get("patient_name", ""), + ) + mapped_items = [ + self._consultation_to_queue_record(row) + for row in page_items(consult_res) + ] + total_val = _as_int( + first_value(consult_res, "total", "count", default=len(mapped_items)), + len(mapped_items), + ) + return {"lists": mapped_items, "count": total_val, "total": total_val} return invoke( self.repository, "list_appointments", @@ -7674,6 +8043,28 @@ class ReceptionPage(QWidget): if generation != self._queue_generation or query_key not in (None, self._queue_query_key): return page_records = page_items(result) + # Smart initial auto-fallback in Spatial Cockpit mode when today's queue is empty + if ( + not page_records + and not append + and self.patient_context_store is not None + and not self.search_edit.text().strip() + ): + if self._cockpit_queue_scope == "today_all" and not self._cockpit_auto_fallback_done: + self._cockpit_auto_fallback_done = True + self._cockpit_fallback_notice = "今日无排班 · 近期挂号" + self.set_cockpit_queue_scope("recent_all", keep_notice=True) + return + if ( + self._cockpit_queue_scope == "recent_all" + and self._cockpit_auto_fallback_done + and not self._cockpit_consult_fallback_done + and callable(getattr(self.repository, "list_consultations", None)) + ): + self._cockpit_consult_fallback_done = True + self._cockpit_fallback_notice = "暂无挂号 · 在管诊单" + self.set_cockpit_queue_scope("consultations", keep_notice=True) + return if append: records = list(self._queue_records) existing_ids = { @@ -7892,19 +8283,85 @@ class ReceptionPage(QWidget): ) -> dict[str, Any]: if cancel_event is not None and cancel_event.is_set(): return {"cancelled": True} - detail = invoke( - self.repository, - "get_reception", - appointment_id=appointment_id, - id=appointment_id, + is_consultation_only = appointment_id < 0 or ( + str(first_value(record, "_queue_source", default="") or "") == "consultation" + and (_as_int(first_value(record, "real_appointment_id", default=0), 0) or 0) <= 0 ) + if is_consultation_only: + diag_target = _as_int( + first_value(record, "diagnosis_id", "id", default=abs(appointment_id)), + 0, + ) or abs(appointment_id) + raw_diag: Any = {} + if callable(getattr(self.repository, "get_diagnosis_detail", None)): + try: + raw_diag = invoke( + self.repository, + "get_diagnosis_detail", + diagnosis_id=diag_target, + id=diag_target, + readonly=not self._can_edit, + ) + except Exception: + raw_diag = invoke( + self.repository, + "get_diagnosis_detail", + diagnosis_id=diag_target, + id=diag_target, + readonly=True, + ) + elif callable(getattr(self.repository, "diagnosis_readonly_detail", None)): + raw_diag = invoke( + self.repository, + "diagnosis_readonly_detail", + diagnosis_id=diag_target, + id=diag_target, + ) + if ( + get_value(raw_diag, "data", None) is not None + and get_value(raw_diag, "diagnosis", None) is None + and get_value(raw_diag, "id", None) is None + ): + raw_diag = get_value(raw_diag, "data", raw_diag) + diag_obj = get_value(raw_diag, "diagnosis", None) or raw_diag or {} + pat_obj = get_value(raw_diag, "patient", None) or diag_obj + appt_seed = dict(record) if isinstance(record, Mapping) else {} + appt_seed.setdefault("id", appointment_id) + appt_seed.setdefault("diagnosis_id", diag_target) + appt_seed.setdefault( + "patient_name", + first_value(diag_obj, "patient_name", "name", default="患者"), + ) + detail: Any = { + "appointment": appt_seed, + "diagnosis": diag_obj, + "patient": pat_obj, + "doctor_notes": get_value(raw_diag, "doctor_notes", None) or [], + "tracking_notes": get_value(raw_diag, "tracking_notes", None) or [], + } + else: + real_appt_id = ( + _as_int(first_value(record, "real_appointment_id", default=appointment_id), appointment_id) + or appointment_id + ) + detail = invoke( + self.repository, + "get_reception", + appointment_id=real_appt_id, + id=real_appt_id, + ) + if ( + get_value(detail, "data", None) is not None + and get_value(detail, "appointment", None) is None + ): + detail = get_value(detail, "data", detail) + # Keep record ID matching expected_id when Consultation had real_appointment_id + appt_inner = get_value(detail, "appointment", None) + if isinstance(appt_inner, dict) and appointment_id != real_appt_id: + appt_inner["id"] = appointment_id + appt_inner["real_appointment_id"] = real_appt_id if cancel_event is not None and cancel_event.is_set(): return {"detail": detail, "cancelled": True} - if ( - get_value(detail, "data", None) is not None - and get_value(detail, "appointment", None) is None - ): - detail = get_value(detail, "data", detail) diagnosis_id = _as_int( first_value( get_value(detail, "diagnosis", None) or {}, @@ -7916,6 +8373,7 @@ class ReceptionPage(QWidget): notes = get_value(detail, "doctor_notes", None) or get_value(detail, "notes", None) or [] notes = list(notes) if isinstance(notes, (list, tuple)) else [notes] daily: Any = {} + prescriptions: list[Any] = [] embedded_tracking = get_value(detail, "tracking_notes", None) or [] tracking_notes = list(embedded_tracking) if isinstance( embedded_tracking, (list, tuple) @@ -7942,12 +8400,13 @@ class ReceptionPage(QWidget): and callable(getattr(self.repository, "get_tracking_window", None)) ): end_date = date.today() + window_days = 20 if self.patient_context_store is not None else 6 try: daily = invoke( self.repository, "get_tracking_window", diagnosis_id=diagnosis_id, - start_date=(end_date - timedelta(days=6)).isoformat(), + start_date=(end_date - timedelta(days=window_days)).isoformat(), end_date=end_date.isoformat(), ) except Exception as error: @@ -7967,11 +8426,27 @@ class ReceptionPage(QWidget): ) except Exception as error: warnings.append(f"跟踪备注:{friendly_error(error)}") + if ( + (cancel_event is None or not cancel_event.is_set()) + and diagnosis_id is not None + and callable(getattr(self.repository, "list_prescriptions_by_diagnosis", None)) + ): + try: + prescriptions = page_items( + invoke( + self.repository, + "list_prescriptions_by_diagnosis", + diagnosis_id=diagnosis_id, + ) + ) + except Exception as error: + warnings.append(f"已开处方:{friendly_error(error)}") return { "detail": detail, "notes": notes, "daily": daily, "tracking_notes": tracking_notes, + "prescriptions": prescriptions, "warnings": warnings, } @@ -8099,7 +8574,11 @@ class ReceptionPage(QWidget): return tracking_notes = list(get_value(bundle, "tracking_notes", None) or []) self._daily_tracking_fallback = tracking_notes - self._render_daily(get_value(bundle, "daily", None) or {}, tracking_notes) + daily_payload = get_value(bundle, "daily", None) or {} + self._latest_daily_window = dict(daily_payload) if isinstance(daily_payload, Mapping) else {} + self._latest_daily_blood = list(get_value(daily_payload, "blood_records", None) or []) + self._render_daily(daily_payload, tracking_notes) + self._sync_cockpit_and_context() warnings = list(get_value(bundle, "warnings", None) or []) if warnings: self.daily_panel.state.show_message( @@ -8185,7 +8664,9 @@ class ReceptionPage(QWidget): notes = get_value(bundle, "notes", None) if notes is None: notes = get_value(detail, "doctor_notes", None) or get_value(detail, "notes", None) - self._render_notes(list(notes or [])) + self._latest_doctor_notes = list(notes or []) + self._latest_prescriptions = list(get_value(bundle, "prescriptions", None) or []) + self._render_notes(self._latest_doctor_notes) diagnosis_id = _as_int( first_value( diagnosis, @@ -8199,6 +8680,9 @@ class ReceptionPage(QWidget): self._daily_diagnosis_id = diagnosis_id tracking_notes = list(get_value(bundle, "tracking_notes", None) or []) self._daily_tracking_fallback = tracking_notes + daily_payload = get_value(bundle, "daily", None) or {} + self._latest_daily_window = dict(daily_payload) if isinstance(daily_payload, Mapping) else {} + self._latest_daily_blood = list(get_value(daily_payload, "blood_records", None) or []) self.daily_panel.set_patient_age( first_value( diagnosis, @@ -8207,7 +8691,7 @@ class ReceptionPage(QWidget): ) ) self._render_daily( - get_value(bundle, "daily", None) or {}, + daily_payload, tracking_notes, ) warnings = list(get_value(bundle, "warnings", None) or []) @@ -9392,6 +9876,10 @@ class ReceptionPage(QWidget): self._daily_loading = False self._daily_diagnosis_id = None self._daily_tracking_fallback = [] + self._latest_daily_window = {} + self._latest_daily_blood = [] + self._latest_doctor_notes = [] + self._latest_prescriptions = [] self.daily_panel.clear_with_message( "正在读取患者日常记录…" if seed else "选择患者后加载最近 7 天日常记录。" ) @@ -9455,6 +9943,10 @@ class ReceptionPage(QWidget): self._daily_loading = False self._daily_diagnosis_id = None self._daily_tracking_fallback = [] + self._latest_daily_window = {} + self._latest_daily_blood = [] + self._latest_doctor_notes = [] + self._latest_prescriptions = [] self.daily_panel.set_error("患者详情加载失败,暂时无法读取日常记录。") self.followup_text.setText("患者详情加载失败,暂时无法读取跟踪备注。") self.health_summary_label.setText("患者详情加载失败,暂时无法读取健康数据。") @@ -9501,7 +9993,8 @@ class ReceptionPage(QWidget): ) ) status = _as_int(first_value(appointment, "status", default=None)) - self.notify_button.setEnabled(appointment_id is not None) + real_appt = appointment_id is not None and appointment_id > 0 + self.notify_button.setEnabled(real_appt) self.video_button.setEnabled( appointment_id is not None and diagnosis_id is not None and patient_id is not None ) @@ -9534,7 +10027,7 @@ class ReceptionPage(QWidget): self.complete_button.setEnabled( self._can_complete and not self._completion_pending - and appointment_id is not None + and real_appt and status in RECEPTION_STATUSES ) note_enabled = self._can_note and diagnosis_id is not None and not self._note_busy diff --git a/app/src/doctor_workstation/ui/shell.py b/app/src/doctor_workstation/ui/shell.py index 198f82c84..1f0a9a700 100755 --- a/app/src/doctor_workstation/ui/shell.py +++ b/app/src/doctor_workstation/ui/shell.py @@ -2630,10 +2630,13 @@ class ShellWindow(QMainWindow): ) -> DiagnosisDialog | None: """Open one authoritative diagnosis in the strongest permitted mode.""" - try: - normalized_id = int(diagnosis_id) - except (TypeError, ValueError): + if isinstance(diagnosis_id, bool): normalized_id = 0 + else: + try: + normalized_id = int(diagnosis_id) + except (TypeError, ValueError): + normalized_id = 0 if normalized_id <= 0: show_toast(self, "当前视频缺少有效诊单编号。", "warning", 3600) return None diff --git a/app/src/doctor_workstation/ui/shell_spatial.py b/app/src/doctor_workstation/ui/shell_spatial.py index 2e5876da6..6a0323ad5 100644 --- a/app/src/doctor_workstation/ui/shell_spatial.py +++ b/app/src/doctor_workstation/ui/shell_spatial.py @@ -27,6 +27,8 @@ from PySide6.QtWidgets import ( QMainWindow, QMenu, QPushButton, + QSizePolicy, + QSplitter, QStackedWidget, QVBoxLayout, QWidget, @@ -52,6 +54,7 @@ from .shell import ( _bounded_initial_window_size, _resolve_navigation, ) +from .spatial_wings import SpatialWingManager from .state import PatientContextStore, PatientSnapshot from .viewmodels import derive_cockpit_snapshot from .visuals.aurora_sheet import CollapsibleObsidianSheet @@ -94,9 +97,10 @@ QFrame#SpatialPillNavIsland { border-radius: 22px; } QPushButton#SpatialNavPill { + min-width: 0px; min-height: 36px; max-height: 36px; - padding: 0 16px; + padding: 0 11px; border: 0; border-radius: 18px; background-color: transparent; @@ -114,9 +118,10 @@ QPushButton#SpatialNavPill:checked { font-weight: 600; } QPushButton#SpatialAiNavPill { + min-width: 0px; min-height: 36px; max-height: 36px; - padding: 0 15px; + padding: 0 12px; border: 1px solid #DFEAE6; border-radius: 18px; background-color: #F7FAF9; @@ -212,7 +217,7 @@ QPushButton#SpatialDoctorCapsule:hover { QFrame#SpatialPatientCapsule { background-color: #FFFFFF; border: 1px solid #E1ECE8; - border-radius: 24px; + border-radius: 27px; } QPushButton#SpatialSecondaryPill { min-height: 42px; @@ -437,25 +442,85 @@ class SpatialShellWindow(QMainWindow): self.topbar = self._build_top_capsule_bar() root.addWidget(self.topbar) - self.sub_hero = self._build_context_sub_hero() - root.addWidget(self.sub_hero) + # Dual-Wing Workspace Splitter: [Left Wing Dock | Main Clinical Stage | Right Wing Dock] + self.wing_splitter = QSplitter(Qt.Orientation.Horizontal, canvas) + self.wing_splitter.setObjectName("SpatialWingSplitter") + self.wing_splitter.setChildrenCollapsible(False) + self.wing_splitter.setHandleWidth(6) + self.wing_splitter.setStyleSheet( + "QSplitter#SpatialWingSplitter { background: transparent; }" + "QSplitter#SpatialWingSplitter::handle { background: transparent; }" + "QSplitter#SpatialWingSplitter::handle:hover { background: rgba(14, 111, 92, 45); border-radius: 3px; }" + ) - self.stack = QStackedWidget(canvas) + self.left_wing_dock = QWidget(self.wing_splitter) + self.left_wing_dock.setObjectName("SpatialLeftWingDock") + + self.main_stage_host = QWidget(self.wing_splitter) + self.main_stage_host.setObjectName("SpatialMainStageHost") + self.main_stage_host.setMinimumWidth(580) + stage_layout = QVBoxLayout(self.main_stage_host) + stage_layout.setContentsMargins(0, 0, 0, 0) + stage_layout.setSpacing(10) + + self.sub_hero = self._build_context_sub_hero() + stage_layout.addWidget(self.sub_hero) + + self.stack = QStackedWidget(self.main_stage_host) self.stack.setObjectName("SpatialPageStack") self.stack.setStyleSheet("QStackedWidget#SpatialPageStack { background: transparent; border: 0; }") - root.addWidget(self.stack, 1) + stage_layout.addWidget(self.stack, 1) # Serene.ai Pull-Up Deep Obsidian Aurora-Glass Bottom Sheet - self.ai_bottom_sheet = CollapsibleObsidianSheet(canvas) + self.ai_bottom_sheet = CollapsibleObsidianSheet(self.main_stage_host) self.ai_bottom_sheet.expanded_changed.connect(self._on_sheet_expanded_changed) self.ai_bottom_sheet.open_ai_report_requested.connect(self._open_active_patient_ai_report) self.ai_bottom_sheet.open_ai_consult_requested.connect(self._open_active_patient_ai_consult) self.ai_bottom_sheet.model_selected.connect(self._on_sheet_model_selected) self.ai_bottom_sheet.set_view_model(derive_cockpit_snapshot().aurora) - root.addWidget(self.ai_bottom_sheet) + stage_layout.addWidget(self.ai_bottom_sheet) + + self.right_wing_dock = QWidget(self.wing_splitter) + self.right_wing_dock.setObjectName("SpatialRightWingDock") + + self.wing_splitter.addWidget(self.left_wing_dock) + self.wing_splitter.addWidget(self.main_stage_host) + self.wing_splitter.addWidget(self.right_wing_dock) + self.wing_splitter.setStretchFactor(0, 0) + self.wing_splitter.setStretchFactor(1, 1) + self.wing_splitter.setStretchFactor(2, 0) + root.addWidget(self.wing_splitter, 1) + + self.wing_manager = SpatialWingManager( + self, + left_dock=self.left_wing_dock, + right_dock=self.right_wing_dock, + splitter=self.wing_splitter, + ) + self.wing_manager.wing_visibility_changed.connect(self._on_wing_visibility_changed) self._register_pages() self._bind_shortcuts() + QTimer.singleShot(280, self._prewarm_wing_surfaces) + + def _on_wing_visibility_changed(self, visible: bool) -> None: + # Auto-collapse the bottom obsidian sheet when a docked wing opens so the cockpit stays airy + if visible and self.wing_manager.mode == "docked" and self.ai_bottom_sheet.is_expanded: + self.set_ai_bottom_sheet_expanded(False) + + def _prewarm_wing_surfaces(self) -> None: + """Warm up heavy wing panels on idle after startup so the first click opens in < 15ms.""" + + if not self.isVisible(): + return + rec_page = self.pages.get("reception") + if rec_page is not None: + ensure_wing = getattr(rec_page, "_ensure_wing_ai_report_panel", None) + if callable(ensure_wing): + panel = ensure_wing() + self.wing_manager.prewarm_widget(panel, preferred_width=540) + dlg = self._ensure_global_diagnosis_dialog() + self.wing_manager.prewarm_widget(dlg, preferred_width=660) def _build_top_capsule_bar(self) -> QWidget: bar = _DraggableHeaderBar(self) @@ -463,13 +528,13 @@ class SpatialShellWindow(QMainWindow): bar.setFixedHeight(52) layout = QHBoxLayout(bar) layout.setContentsMargins(2, 0, 2, 0) - layout.setSpacing(12) + layout.setSpacing(8) # Left Brand Mark (Alveo × Serene minimal geometric brand) brand_wrap = QWidget(bar) brand_row = QHBoxLayout(brand_wrap) - brand_row.setContentsMargins(0, 0, 4, 0) - brand_row.setSpacing(10) + brand_row.setContentsMargins(0, 0, 2, 0) + brand_row.setSpacing(8) self.brand_mark = _AlveoJadeEmblem(brand_wrap) brand_row.addWidget(self.brand_mark) @@ -481,26 +546,29 @@ class SpatialShellWindow(QMainWindow): brand_text.setStyleSheet("color: #0F1F1D; background: transparent;") brand_row.addWidget(brand_text) - brand_tag = QLabel("clinical.os", brand_wrap) - brand_tag.setStyleSheet("color: #7A908C; font-size: 13px; background: transparent;") + brand_tag = QLabel("临床智医", brand_wrap) + brand_tag.setStyleSheet("color: #7A908C; font-size: 12px; background: transparent;") + self.brand_tag = brand_tag brand_row.addWidget(brand_tag) layout.addWidget(brand_wrap) layout.addStretch(1) - # Center Floating Pill Navigation Island (Zero-sidebar centerpiece!) + # Center Floating Pill Navigation Island (Zero-sidebar centerpiece, never compressed!) self.nav_island = QFrame(bar) self.nav_island.setObjectName("SpatialPillNavIsland") self.nav_island.setFixedHeight(44) + self.nav_island.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) self.nav_layout = QHBoxLayout(self.nav_island) - self.nav_layout.setContentsMargins(4, 3, 4, 3) + self.nav_layout.setContentsMargins(5, 3, 5, 3) self.nav_layout.setSpacing(3) layout.addWidget(self.nav_island) - # Separate AI Coach / Syndrome Lab Pill right beside or inside island + # Separate AI Syndrome Assistant Pill inside island with guaranteed room if self._can_ai_assistant: self.ai_nav_button = QPushButton("AI 辨证师", self.nav_island) self.ai_nav_button.setObjectName("SpatialAiNavPill") + self.ai_nav_button.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed) self.ai_nav_button.setIcon(icons.icon("ai", "#0E6F5C", 15)) self.ai_nav_button.setIconSize(QSize(15, 15)) self.ai_nav_button.setCursor(Qt.CursorShape.PointingHandCursor) @@ -509,10 +577,13 @@ class SpatialShellWindow(QMainWindow): layout.addStretch(1) - # Right Global Search Capsule + Utility Circles + Doctor Identity Pill + Window Controls + # Right Global Search Capsule (elastic width so High-DPI never clips center nav!) self.search_capsule = QFrame(bar) self.search_capsule.setObjectName("SpatialSearchCapsule") - self.search_capsule.setFixedSize(244, 40) + self.search_capsule.setMinimumWidth(140) + self.search_capsule.setMaximumWidth(196) + self.search_capsule.setFixedHeight(40) + self.search_capsule.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed) s_layout = QHBoxLayout(self.search_capsule) s_layout.setContentsMargins(12, 0, 8, 0) s_layout.setSpacing(6) @@ -535,6 +606,15 @@ class SpatialShellWindow(QMainWindow): s_layout.addWidget(self.palette_badge) layout.addWidget(self.search_capsule) + self.compact_search_button = QPushButton(bar) + self.compact_search_button.setObjectName("SpatialCircleButton") + self.compact_search_button.setIcon(icons.icon("search", "#2B403E", 16)) + self.compact_search_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.compact_search_button.setToolTip("搜索患者或打开命令面板(Ctrl+K)") + self.compact_search_button.clicked.connect(self.open_command_palette) + self.compact_search_button.hide() + layout.addWidget(self.compact_search_button) + self.refresh_button = QPushButton(bar) self.refresh_button.setObjectName("SpatialCircleButton") self.refresh_button.setIcon(icons.icon("refresh", "#2B403E", 16)) @@ -558,7 +638,9 @@ class SpatialShellWindow(QMainWindow): dept_name = str( first_value(self.current_user, "department_name", "dept_name", default="糖代谢专科") ).strip() - self.user_menu_button = QPushButton(f"{doc_name} · {dept_name}", bar) + self._short_user_label = doc_name + self._full_user_label = f"{doc_name} · {dept_name}" + self.user_menu_button = QPushButton(self._full_user_label, bar) self.user_menu_button.setObjectName("SpatialDoctorCapsule") self.user_menu_button.setIcon(icons.icon("patients", "#0E6F5C", 16)) self.user_menu_button.setCursor(Qt.CursorShape.PointingHandCursor) @@ -615,7 +697,7 @@ class SpatialShellWindow(QMainWindow): hero = QWidget(self) hero.setObjectName("SpatialSubHero") - hero.setFixedHeight(64) + hero.setFixedHeight(68) layout = QHBoxLayout(hero) layout.setContentsMargins(4, 0, 4, 0) layout.setSpacing(12) @@ -630,7 +712,7 @@ class SpatialShellWindow(QMainWindow): self.hero_title_label = QLabel("全息辨证接诊舱", hero) h_font = QFont(heading_family()) - h_font.setPixelSize(28) + h_font.setPixelSize(26) h_font.setWeight(QFont.Weight.DemiBold) self.hero_title_label.setFont(h_font) self.hero_title_label.setStyleSheet("color: #0E1D1B; background: transparent;") @@ -642,30 +724,32 @@ class SpatialShellWindow(QMainWindow): # Right: Active Patient Floating Capsule (Alveo 'Margaret Osei · 71 yrs · COPD') self.patient_capsule = QFrame(hero) self.patient_capsule.setObjectName("SpatialPatientCapsule") - self.patient_capsule.setFixedHeight(48) + self.patient_capsule.setFixedHeight(54) pc_layout = QHBoxLayout(self.patient_capsule) - pc_layout.setContentsMargins(8, 4, 16, 4) + pc_layout.setContentsMargins(10, 6, 18, 6) pc_layout.setSpacing(10) self.patient_avatar_badge = QLabel("患", self.patient_capsule) - self.patient_avatar_badge.setFixedSize(34, 34) + self.patient_avatar_badge.setFixedSize(36, 36) self.patient_avatar_badge.setAlignment(Qt.AlignmentFlag.AlignCenter) self.patient_avatar_badge.setStyleSheet( "background-color: #E2F3EE; color: #0E6F5C; border: 1px solid #DFC793;" - " border-radius: 17px; font-size: 14px; font-weight: 600;" + " border-radius: 18px; font-size: 14px; font-weight: 600;" ) pc_layout.addWidget(self.patient_avatar_badge) p_meta_col = QVBoxLayout() p_meta_col.setContentsMargins(0, 0, 0, 0) - p_meta_col.setSpacing(1) + p_meta_col.setSpacing(2) self.context_patient_name = QLabel("等待选择接诊患者", self.patient_capsule) + self.context_patient_name.setMinimumHeight(20) self.context_patient_name.setStyleSheet( "color: #10201E; font-size: 13px; font-weight: 600; background: transparent;" ) p_meta_col.addWidget(self.context_patient_name) - self.context_patient_sub = QLabel("点击今日门诊计划自动同步全站上下文", self.patient_capsule) + self.context_patient_sub = QLabel("从右侧接诊队列或患者列表选择患者", self.patient_capsule) + self.context_patient_sub.setMinimumHeight(16) self.context_patient_sub.setStyleSheet( "color: #6E8380; font-size: 11px; background: transparent;" ) @@ -682,9 +766,10 @@ class SpatialShellWindow(QMainWindow): self.quick_chart_button.clicked.connect(self._open_active_patient_diagnosis) layout.addWidget(self.quick_chart_button) - # [▷ 开启视频面诊] Primary Alveo Emerald Pill (Alveo 'Start ward round') - self.quick_video_button = QPushButton("▷ 开启视频面诊", hero) + # [开启视频面诊] Primary Alveo Emerald Pill (Alveo 'Start ward round') + self.quick_video_button = QPushButton("开启视频面诊", hero) self.quick_video_button.setObjectName("SpatialPrimaryEmeraldPill") + self.quick_video_button.setIcon(icons.icon("video", "#FFFFFF", 15)) self.quick_video_button.setCursor(Qt.CursorShape.PointingHandCursor) self.quick_video_button.setEnabled(False) self.quick_video_button.clicked.connect(self._trigger_active_patient_video) @@ -721,6 +806,7 @@ class SpatialShellWindow(QMainWindow): btn = QPushButton(pill_title, self.nav_island) btn.setObjectName("SpatialNavPill") + btn.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed) btn.setCheckable(True) btn.setCursor(Qt.CursorShape.PointingHandCursor) btn.clicked.connect( @@ -843,6 +929,9 @@ class SpatialShellWindow(QMainWindow): def toggle_ai_bottom_sheet(self) -> None: self.ai_bottom_sheet.toggle_expanded() + def set_ai_bottom_sheet_expanded(self, expanded: bool) -> None: + self.ai_bottom_sheet.set_expanded(bool(expanded)) + def _on_sheet_expanded_changed(self, expanded: bool) -> None: self.patient_context_store.set_bottom_sheet_expanded(expanded) self._sync_ai_sheet_button(expanded) @@ -868,21 +957,133 @@ class SpatialShellWindow(QMainWindow): select_model = getattr(rec_page, "select_cockpit_ai_model", None) if callable(select_model): select_model(model_key) + return + self.ai_bottom_sheet.set_view_model( + derive_cockpit_snapshot(active_ai_model=model_key).aurora + ) def _on_patient_context_changed(self, snapshot: PatientSnapshot) -> None: if not snapshot or not snapshot.has_patient: self.patient_avatar_badge.setText("患") self.context_patient_name.setText("等待选择接诊患者") - self.context_patient_sub.setText("点击今日门诊计划自动同步全站上下文") + self.context_patient_sub.setText("从右侧接诊队列或患者列表选择患者") self.quick_chart_button.setEnabled(False) self.quick_video_button.setEnabled(False) return self.patient_avatar_badge.setText(snapshot.patient_name[:1]) - self.context_patient_name.setText(f"{snapshot.patient_name} · {snapshot.status_text}") + disp_name = snapshot.patient_name + if len(disp_name) > 14: + disp_name = f"{disp_name[:13]}…" + self.context_patient_name.setText(f"{disp_name} · {snapshot.status_text}") + self.context_patient_name.setToolTip(f"{snapshot.patient_name} · {snapshot.status_text}") self.context_patient_sub.setText(snapshot.subtitle_line) self.quick_chart_button.setEnabled(snapshot.diagnosis_id > 0) self.quick_video_button.setEnabled(snapshot.diagnosis_id > 0 or snapshot.appointment_id > 0) + rec_page = self.pages.get("reception") + sync_context = getattr(rec_page, "load_patient_from_context", None) + if callable(sync_context): + sync_context(snapshot) + if self.wing_manager.is_open: + self._sync_open_wing_with_patient(snapshot) + + def _sync_open_wing_with_patient(self, snapshot: PatientSnapshot) -> None: + """Keep any open Right/Left Wing or Sidecar synchronized when switching patients.""" + + self.wing_manager.update_header(subtitle=snapshot.patient_name) + active_w = self.wing_manager.active_widget + if active_w is None: + return + + rec_page = self.pages.get("reception") + seed_payload: Any = snapshot.raw_record + if rec_page is not None: + sel_detail = getattr(rec_page, "_selected_detail", None) + if sel_detail: + detail_diag = get_value(sel_detail, "diagnosis", None) or {} + try: + detail_diag_id = int(first_value(detail_diag, "id", "diagnosis_id", default=0) or 0) + except (TypeError, ValueError): + detail_diag_id = 0 + if detail_diag_id == snapshot.diagnosis_id and snapshot.diagnosis_id > 0: + seed_payload = sel_detail + + if isinstance(active_w, DiagnosisDialog): + if snapshot.diagnosis_id > 0 and getattr(active_w, "_diagnosis_id", 0) != snapshot.diagnosis_id: + prev_tab_key = None + if hasattr(active_w, "tabs") and active_w.tabs.currentIndex() >= 0: + prev_tab_key = active_w.tabs.tabBar().tabData(active_w.tabs.currentIndex()) + want_editable = bool( + getattr(active_w, "_editable", False) + and has_permission(self.permissions, "tcm.diagnosis/edit", default=False) + ) + active_w.open_for( + snapshot.diagnosis_id, + editable=want_editable, + view_only=not want_editable, + seed=seed_payload, + modeless=True, + auto_show=False, + ) + if prev_tab_key and hasattr(active_w, "tabs"): + for i in range(active_w.tabs.count()): + if active_w.tabs.tabBar().tabData(i) == prev_tab_key: + if active_w.tabs.currentIndex() != i: + active_w.tabs.setCurrentIndex(i) + break + self.wing_manager.update_header( + title=active_w.windowTitle().split(" - ")[0].strip() or "编辑诊单", + subtitle=snapshot.patient_name, + ) + return + + cls_name = type(active_w).__name__ + if cls_name == "ClinicalAiReportWingPanel": + sync_ai = getattr(rec_page, "_sync_wing_ai_report_panel", None) + if callable(sync_ai): + sync_ai() + return + + if cls_name == "AiConsultDialog" and snapshot.diagnosis_id > 0: + if getattr(active_w, "diagnosis_id", 0) != snapshot.diagnosis_id: + open_fn = getattr(active_w, "open_for", None) + if callable(open_fn): + open_fn( + diagnosis_id=snapshot.diagnosis_id, + patient_id=snapshot.patient_id, + seed=seed_payload, + source_title="接诊总览", + ) + return + + if cls_name == "DiagnosisAiAssistantDialog" and snapshot.diagnosis_id > 0: + if getattr(active_w, "diagnosis_id", 0) != snapshot.diagnosis_id: + open_fn = getattr(active_w, "open_for", None) + if callable(open_fn): + open_fn(snapshot.diagnosis_id, "") + return + + if cls_name == "PrescriptionAiReportDialog" and snapshot.diagnosis_id > 0: + kind = getattr(active_w, "kind", None) + if getattr(kind, "entry", "") != "prescription": + cur_row = getattr(active_w, "prescription", None) or {} + try: + cur_diag_id = int(first_value(cur_row, "diagnosis_id", "id", default=0) or 0) + except (TypeError, ValueError): + cur_diag_id = 0 + if cur_diag_id != snapshot.diagnosis_id: + open_fn = getattr(active_w, "open_for", None) + if callable(open_fn): + row_seed = dict(snapshot.raw_record or {}) + row_seed.update( + { + "id": snapshot.diagnosis_id, + "diagnosis_id": snapshot.diagnosis_id, + "patient_name": snapshot.patient_name, + } + ) + open_fn(row_seed) + def _open_active_patient_diagnosis(self) -> None: snap = self.patient_context_store.current_patient if snap.diagnosis_id > 0: @@ -910,9 +1111,12 @@ class SpatialShellWindow(QMainWindow): def _open_active_patient_ai_report(self) -> None: rec_page = self.pages.get("reception") - open_rep = getattr(rec_page, "_open_ai_analysis_dialog", None) - if callable(open_rep) and getattr(rec_page, "_selected_detail", None): - open_rep() + open_wing = getattr(rec_page, "open_ai_report_wing", None) + if ( + callable(open_wing) + and getattr(rec_page, "_selected_appointment_id", None) is not None + and open_wing() + ): return self._open_active_patient_ai_consult() @@ -921,10 +1125,12 @@ class SpatialShellWindow(QMainWindow): if snap.diagnosis_id > 0 and self._can_ai_assistant: present_ai_consult( self.repository, + self.permissions, + self, diagnosis_id=snap.diagnosis_id, - patient_name=snap.patient_name, - permissions=self.permissions, - parent=self, + patient_id=snap.patient_id, + seed=snap.raw_record, + source_title="接诊总览", ) return self._open_global_ai_picker() @@ -977,20 +1183,32 @@ class SpatialShellWindow(QMainWindow): category="空间导航", shortcut=f"Alt+{idx}" if idx <= 6 else "", icon_kind=item.key, - callback=lambda k=item.key: self.navigate(k), + action=lambda k=item.key: self.navigate(k), ) ) entries.append( CommandEntry( key="act:ai_sheet", - title="展开 / 收起黑曜极光 AI 辨证舱", - subtitle="查看三联极光毛玻璃循证卡与控糖节律仪表盘", + title="展开 / 收起黑曜极光 AI 分析舱", + subtitle="查看三模型循证结论与病历完备度", category="临床智医", shortcut="Ctrl+]", icon_kind="ai", - callback=self.toggle_ai_bottom_sheet, + action=self.toggle_ai_bottom_sheet, ) ) + if self.wing_manager.is_open: + entries.append( + CommandEntry( + key="act:wing_mode", + title="切换伴随视窗形态(内嵌分栏 ⇄ 独立副窗)", + subtitle="在主窗并排分栏与桌面磁吸伴随窗口之间切换", + category="伴随视窗", + shortcut="", + icon_kind="consultations", + action=self.wing_manager.toggle_mode, + ) + ) entries.append( CommandEntry( key="act:refresh", @@ -999,7 +1217,7 @@ class SpatialShellWindow(QMainWindow): category="工作台操作", shortcut="F5", icon_kind="refresh", - callback=self.refresh_current_page, + action=self.refresh_current_page, ) ) snap = self.patient_context_store.current_patient @@ -1007,15 +1225,19 @@ class SpatialShellWindow(QMainWindow): entries.append( CommandEntry( key="act:diag", - title=f"打开四诊病历 · {snap.patient_name}", + title=f"打开四诊病历伴随舱 · {snap.patient_name}", subtitle=snap.subtitle_line, category="当前患者", shortcut="", icon_kind="consultations", - callback=self._open_active_patient_diagnosis, + action=self._open_active_patient_diagnosis, ) ) - dlg = CommandPaletteDialog(entries, self) + dlg = CommandPaletteDialog( + entries, + on_search_patient=lambda q: (self.global_search.setText(q), self._run_global_search()), + parent=self, + ) dlg.exec() def _toggle_maximize(self) -> None: @@ -1040,10 +1262,17 @@ class SpatialShellWindow(QMainWindow): *, modeless: bool = False, ) -> DiagnosisDialog | None: - try: - normalized_id = int(diagnosis_id) - except (TypeError, ValueError): + if isinstance(diagnosis_id, bool): normalized_id = 0 + else: + try: + normalized_id = int(diagnosis_id) + except (TypeError, ValueError): + normalized_id = 0 + if normalized_id <= 0: + fallback_id = self.patient_context_store.current_patient.diagnosis_id + if fallback_id > 0: + normalized_id = fallback_id if normalized_id <= 0: show_toast(self, "当前视频缺少有效诊单编号。", "warning", 3600) return None @@ -1088,6 +1317,42 @@ class SpatialShellWindow(QMainWindow): tip = message or ("云端同步正常" if online else "云端连接中断") self.refresh_button.setToolTip(f"刷新当前视图(F5) · {tip}") + def resizeEvent(self, event: Any) -> None: # noqa: N802 + super().resizeEvent(event) + w = self.width() + compact_top = w < 1280 + ultra_top = w < 1080 + if hasattr(self, "brand_tag"): + self.brand_tag.setVisible(not compact_top) + if hasattr(self, "palette_badge"): + self.palette_badge.setVisible(not compact_top) + if hasattr(self, "search_capsule"): + self.search_capsule.setVisible(not ultra_top) + if not ultra_top: + self.search_capsule.setMinimumWidth(118 if compact_top else 140) + self.search_capsule.setMaximumWidth(154 if compact_top else 196) + if hasattr(self, "compact_search_button"): + self.compact_search_button.setVisible(ultra_top) + short_nav = { + "reception": "总览", + "appointments": "日程", + "patients": "患者", + "prescription_library": "智库", + "prescriptions": "处方", + "consultations": "诊单", + } + for key, btn in self.nav_buttons.items(): + full_t = _SPATIAL_NAV_LABELS.get(key, btn.text()) + btn.setText(short_nav.get(key, full_t) if ultra_top else full_t) + if hasattr(self, "ai_nav_button"): + self.ai_nav_button.setText("AI 辨证" if ultra_top else "AI 辨证师") + if hasattr(self, "global_search"): + self.global_search.setPlaceholderText("搜索…" if compact_top else "搜索患者、诊单…") + if hasattr(self, "user_menu_button"): + self.user_menu_button.setText( + self._short_user_label if compact_top else self._full_user_label + ) + def showEvent(self, event: Any) -> None: # noqa: N802 super().showEvent(event) self.chat_notifications.start() @@ -1098,6 +1363,7 @@ class SpatialShellWindow(QMainWindow): def closeEvent(self, event: Any) -> None: # noqa: N802 self.chat_notifications.stop() + self.wing_manager.close_all() super().closeEvent(event) if event.isAccepted(): self.close_requested.emit() diff --git a/app/src/doctor_workstation/ui/spatial_wings.py b/app/src/doctor_workstation/ui/spatial_wings.py new file mode 100644 index 000000000..a24077874 --- /dev/null +++ b/app/src/doctor_workstation/ui/spatial_wings.py @@ -0,0 +1,1596 @@ +"""Clinical OS 4.0 Dual-Wing Companion & Docked Split-Stage Window Engine. + +Replaces center-blocking OS modal dialogs across the entire workstation with: +1. Docked Left/Right Split-Wing (`DockedWing`) inside `SpatialShellWindow` (zero occlusion, + resizable via splitter, 100% non-modal side-by-side workflow). +2. External Magnetic Left/Right Companion Sidecar Window (`CompanionSidecarWindow`) that + snaps 10px beside the main workstation at equal height and moves in lockstep. +3. Frameless Jade-Porcelain Confirm & Quick-Input Sheets (`clinical_confirm`, `clinical_get_text`, + `clinical_get_multiline`, `clinical_get_item`) replacing raw `QMessageBox` / `QInputDialog`. +""" + +from __future__ import annotations + +import os +from collections.abc import Callable, Sequence +from contextlib import suppress +from typing import Any + +from PySide6.QtCore import ( + QEasingCurve, + QEvent, + QEventLoop, + QObject, + QPointF, + QRect, + QRectF, + QSize, + Qt, + QTimer, + QVariantAnimation, + Signal, +) +from PySide6.QtGui import ( + QColor, + QFont, + QFontMetrics, + QKeySequence, + QLinearGradient, + QMouseEvent, + QPainter, + QPainterPath, + QPen, + QPixmap, + QShortcut, +) +from PySide6.QtWidgets import ( + QApplication, + QComboBox, + QDialog, + QFileDialog, + QFrame, + QHBoxLayout, + QInputDialog, + QLabel, + QLineEdit, + QMessageBox, + QPlainTextEdit, + QPushButton, + QSizePolicy, + QStackedLayout, + QVBoxLayout, + QWidget, +) + +from . import icons, motion +from .reception_style import body_family, heading_family + +SPATIAL_WING_QSS = """ +QWidget#SpatialWingCard { + background: transparent; +} +QFrame#SpatialWingHeader { + background-color: #F7FAF9; + border: 0; + border-bottom: 1px solid #E2ECE9; + border-top-left-radius: 20px; + border-top-right-radius: 20px; +} +QLabel#SpatialWingTitle { + color: #0F1F1D; + font-size: 14px; + font-weight: 600; + padding-right: 4px; +} +QLabel#SpatialWingContextBadge { + background-color: #E3F3EE; + color: #0E6F5C; + border-radius: 10px; + padding: 2px 8px; + font-size: 11px; + font-weight: 600; +} +QPushButton#SpatialWingModeBtn { + min-width: 38px; + min-height: 26px; + max-height: 26px; + padding: 0 7px; + border-radius: 13px; + border: 1px solid #DCE7E4; + background-color: #FFFFFF; + color: #4D6561; + font-size: 11px; + font-weight: 600; +} +QPushButton#SpatialWingModeBtn:hover { + background-color: #E7F4F0; + border-color: #9ED0C3; + color: #0E6F5C; +} +QPushButton#SpatialWingModeBtn:checked { + background-color: #111918; + border-color: #111918; + color: #FFFFFF; +} +QPushButton#SpatialWingDetachBtn { + min-width: 68px; + min-height: 26px; + max-height: 26px; + padding: 0 9px; + border-radius: 13px; + border: 1px solid #CFE3DD; + background-color: #EDF7F4; + color: #0E6F5C; + font-size: 11px; + font-weight: 600; +} +QPushButton#SpatialWingDetachBtn:hover { + background-color: #0E6F5C; + border-color: #0E6F5C; + color: #FFFFFF; +} +QPushButton#SpatialWingCloseBtn { + min-width: 28px; + max-width: 28px; + min-height: 28px; + max-height: 28px; + border-radius: 14px; + border: 0; + background-color: #EEF3F1; + color: #4E6461; + font-size: 14px; + font-weight: 600; + padding: 0; +} +QPushButton#SpatialWingCloseBtn:hover { + background-color: #E0584C; + color: #FFFFFF; +} +QWidget#SpatialWingBodyHost { + background-color: #FFFFFF; + border-bottom-left-radius: 20px; + border-bottom-right-radius: 20px; +} +QWidget#SpatialWingBodyHost QDialog { + background-color: #FFFFFF; + border: 0; +} +QWidget#SpatialWingBodyHost QPushButton[variant="primary"] { + background-color: #0E6F5C; + color: #FFFFFF; + border: 0; + border-radius: 17px; + min-height: 34px; + padding: 0 18px; + font-weight: 600; +} +QWidget#SpatialWingBodyHost QPushButton[variant="primary"]:hover { + background-color: #0A5B4B; +} +QWidget#SpatialWingBodyHost QPushButton[variant="secondary"] { + background-color: #F4F8F7; + color: #1A2E2C; + border: 1px solid #DCE7E4; + border-radius: 17px; + min-height: 34px; + padding: 0 16px; + font-weight: 500; +} +QWidget#SpatialWingBodyHost QPushButton[variant="secondary"]:hover { + background-color: #E6F3EF; + border-color: #9ED0C3; + color: #0E6F5C; +} +QWidget#SpatialWingBodyHost QLineEdit, +QWidget#SpatialWingBodyHost QComboBox, +QWidget#SpatialWingBodyHost QPlainTextEdit { + border: 1px solid #DCE7E4; + border-radius: 10px; + background-color: #FBFDFC; + color: #132523; +} +QWidget#SpatialWingBodyHost QLineEdit:focus, +QWidget#SpatialWingBodyHost QComboBox:focus, +QWidget#SpatialWingBodyHost QPlainTextEdit:focus { + border: 1px solid #0E6F5C; + background-color: #FFFFFF; +} +""" + + +def find_spatial_shell(widget: QWidget | None = None) -> Any | None: + """Return the active visible `SpatialShellWindow` if one exists.""" + + cursor = widget + while cursor is not None: + if getattr(cursor, "wing_manager", None) is not None and cursor.isVisible(): + return cursor + cursor = cursor.parentWidget() + app = QApplication.instance() + if app is None: + return None + for candidate in app.topLevelWidgets(): + if getattr(candidate, "wing_manager", None) is not None and candidate.isVisible(): + return candidate + return None + + +class _WingHeaderBar(QFrame): + """Unified header with Left/Right dock pills, Sidecar detach toggle, and drag support.""" + + side_requested = Signal(str) + mode_toggle_requested = Signal() + close_requested = Signal() + manual_drag_started = Signal() + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("SpatialWingHeader") + self.setFixedHeight(50) + + layout = QHBoxLayout(self) + layout.setContentsMargins(12, 6, 10, 6) + layout.setSpacing(5) + + self.icon_badge = QLabel(self) + self.icon_badge.setFixedSize(28, 28) + self.icon_badge.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.icon_badge.setStyleSheet( + "background-color: #E2F3EE; border-radius: 14px; border: 1px solid #CBE6DE;" + ) + layout.addWidget(self.icon_badge) + + self.title_label = QLabel("伴随工作视窗", self) + self.title_label.setObjectName("SpatialWingTitle") + self.title_label.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred) + t_font = QFont(heading_family()) + t_font.setPixelSize(14) + t_font.setWeight(QFont.Weight.DemiBold) + self.title_label.setFont(t_font) + layout.addWidget(self.title_label) + + self.context_badge = QLabel("", self) + self.context_badge.setObjectName("SpatialWingContextBadge") + self.context_badge.setVisible(False) + layout.addWidget(self.context_badge) + + layout.addStretch(1) + + self.left_btn = QPushButton("‹ 左翼", self) + self.left_btn.setObjectName("SpatialWingModeBtn") + self.left_btn.setCheckable(True) + self.left_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.left_btn.setToolTip("停靠在主工作台左侧") + self.left_btn.clicked.connect(lambda: self.side_requested.emit("left")) + layout.addWidget(self.left_btn) + + self.right_btn = QPushButton("右翼 ›", self) + self.right_btn.setObjectName("SpatialWingModeBtn") + self.right_btn.setCheckable(True) + self.right_btn.setChecked(True) + self.right_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.right_btn.setToolTip("停靠在主工作台右侧") + self.right_btn.clicked.connect(lambda: self.side_requested.emit("right")) + layout.addWidget(self.right_btn) + + self.detach_btn = QPushButton("独立副窗 ↗", self) + self.detach_btn.setObjectName("SpatialWingDetachBtn") + self.detach_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.detach_btn.setToolTip("切换为桌面外侧等高磁吸伴随窗口 / 嵌回主窗口") + self.detach_btn.clicked.connect(self.mode_toggle_requested.emit) + layout.addWidget(self.detach_btn) + + self.close_btn = QPushButton("×", self) + self.close_btn.setObjectName("SpatialWingCloseBtn") + self.close_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.close_btn.setToolTip("关闭当前伴随视窗(Esc)") + self.close_btn.clicked.connect(self.close_requested.emit) + layout.addWidget(self.close_btn) + + def set_metadata( + self, + *, + title: str, + subtitle: str = "", + icon_kind: str = "ai", + side: str = "right", + mode: str = "docked", + ) -> None: + self.icon_badge.setPixmap(icons.icon(icon_kind, "#0E6F5C", 15).pixmap(15, 15)) + resolved_title = title or "伴随工作视窗" + self.title_label.setText(resolved_title) + m_font = QFont(heading_family()) + m_font.setPixelSize(14) + m_font.setWeight(QFont.Weight.DemiBold) + t_width = QFontMetrics(m_font).horizontalAdvance(resolved_title) + 10 + self.title_label.setMinimumWidth(min(176, t_width)) + raw_sub = str(subtitle or "").strip() + clean_sub = f"{raw_sub[:4]}…" if len(raw_sub) > 5 else raw_sub + self.context_badge.setText(clean_sub) + self.context_badge.setToolTip(raw_sub) + self.context_badge.setVisible(bool(clean_sub)) + self.left_btn.setChecked(side == "left") + self.right_btn.setChecked(side != "left") + if mode == "sidecar": + self.detach_btn.setText("↙ 嵌回主窗") + self.detach_btn.setToolTip("将独立伴随副窗嵌回主工作站并排分栏") + else: + self.detach_btn.setText("独立副窗 ↗") + self.detach_btn.setToolTip("弹出为主窗口左侧/右侧等高磁吸独立窗口") + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + win = self.window() + if win is not None and getattr(win, "_is_companion_sidecar", False): + child = self.childAt(event.position().toPoint()) + if child is None or isinstance(child, QLabel): + handle = win.windowHandle() + if handle is not None and handle.startSystemMove(): + self.manual_drag_started.emit() + event.accept() + return + super().mousePressEvent(event) + + +class _WingGlideVeil(QWidget): + """GPU-friendly cached-pixmap glide veil: 60fps OutCubic entrance with ZERO layout reflow.""" + + def __init__(self, parent: QWidget) -> None: + super().__init__(parent) + self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True) + self.setAutoFillBackground(False) + self._pixmap: QPixmap | None = None + self._progress = 1.0 + self._offset_px = 16.0 + self._anim = QVariantAnimation(self) + self._anim.setDuration(155) + self._anim.setStartValue(0.0) + self._anim.setEndValue(1.0) + self._anim.setEasingCurve(QEasingCurve.Type.OutCubic) + self._anim.valueChanged.connect(self._on_tick) + self._anim.finished.connect(self._on_finished) + self.hide() + + def play(self, snapshot: QPixmap, *, from_side: str) -> None: + self._anim.stop() + if snapshot.isNull(): + self.hide() + return + self._pixmap = snapshot + self._progress = 0.0 + self._offset_px = 16.0 if from_side == "right" else -16.0 + parent = self.parentWidget() + if parent is not None: + self.setGeometry(parent.rect()) + self.show() + self.raise_() + self._anim.start() + + def cancel(self) -> None: + self._anim.stop() + self._pixmap = None + self.hide() + + def _on_tick(self, value: Any) -> None: + self._progress = float(value) + parent = self.parentWidget() + if parent is not None and self.size() != parent.size(): + self.setGeometry(parent.rect()) + self.update() + + def _on_finished(self) -> None: + self._pixmap = None + self.hide() + + def paintEvent(self, _event: object) -> None: # noqa: N802 + if self._pixmap is None or self._pixmap.isNull(): + return + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True) + painter.fillRect(self.rect(), QColor("#FFFFFF")) + dx = (1.0 - self._progress) * self._offset_px + painter.setOpacity(0.38 + 0.62 * self._progress) + painter.drawPixmap(QPointF(dx, 0.0), self._pixmap) + + +class SpatialWingCard(QWidget): + """20px rounded jade-porcelain card hosting any clinical panel or adapted dialog.""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("SpatialWingCard") + self.setStyleSheet(SPATIAL_WING_QSS) + self.setMinimumWidth(380) + + root = QVBoxLayout(self) + root.setContentsMargins(1, 3, 1, 1) + root.setSpacing(0) + + self.header = _WingHeaderBar(self) + root.addWidget(self.header) + + self.body_host = QWidget(self) + self.body_host.setObjectName("SpatialWingBodyHost") + self.body_host.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self.body_layout = QStackedLayout(self.body_host) + self.body_layout.setContentsMargins(0, 0, 0, 0) + self.body_layout.setStackingMode(QStackedLayout.StackingMode.StackOne) + root.addWidget(self.body_host, 1) + + self.glide_veil = _WingGlideVeil(self.body_host) + + def paintEvent(self, _event: object) -> None: # noqa: N802 + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + rect = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5) + path = QPainterPath() + path.addRoundedRect(rect, 20.0, 20.0) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.fillPath(path, QColor("#FFFFFF")) + + # Subtle top 3px Alveo emerald-to-champagne hairline clip + painter.save() + painter.setClipPath(path) + grad = QLinearGradient(rect.left(), rect.top(), rect.right(), rect.top()) + grad.setColorAt(0.0, QColor("#0E6F5C")) + grad.setColorAt(0.6, QColor("#2BA48C")) + grad.setColorAt(1.0, QColor("#DFC793")) + painter.fillRect(QRectF(rect.left(), rect.top(), rect.width(), 3.0), grad) + painter.restore() + + painter.setPen(QPen(QColor("#D8E5E1"), 1.0)) + painter.drawPath(path) + + +class CompanionSidecarWindow(QWidget): + """External frameless rounded window magnetically snapped to the Left or Right of Main.""" + + closed_by_system = Signal() + _RESIZE_MARGIN = 7 + + def __init__(self, owner: QWidget) -> None: + super().__init__(None) + self._owner = owner + self._is_companion_sidecar = True + self._magnet_locked = True + self._suppress_close_signal = False + self.setObjectName("CompanionSidecarWindow") + self.setProperty("doctorSkipOpenGeometry", True) + self.setWindowTitle("甄养堂 · 临床伴随视窗") + self.setWindowFlags(Qt.WindowType.Window | Qt.WindowType.FramelessWindowHint) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setMouseTracking(True) + self.setMinimumSize(390, 520) + + self._root = QVBoxLayout(self) + self._root.setContentsMargins(0, 0, 0, 0) + self._root.setSpacing(0) + + self._arrival_anim = QVariantAnimation(self) + self._arrival_anim.setDuration(165) + self._arrival_anim.setStartValue(0.0) + self._arrival_anim.setEndValue(1.0) + self._arrival_anim.setEasingCurve(QEasingCurve.Type.OutCubic) + self._arrival_target = QRect() + self._arrival_dx = 14 + self._arrival_anim.valueChanged.connect(self._on_arrival_tick) + self._arrival_anim.finished.connect(self._on_arrival_done) + + QShortcut(QKeySequence("Esc"), self, activated=self._emit_escape) + + def animate_arrival(self, target_rect: QRect, *, side: str) -> None: + self._arrival_anim.stop() + if motion.reduced_motion() or os.environ.get("QT_QPA_PLATFORM") == "offscreen": + self.setWindowOpacity(1.0) + self.setGeometry(target_rect) + return + self._arrival_target = QRect(target_rect) + self._arrival_dx = 14 if side == "right" else -14 + self.setWindowOpacity(0.32) + self.setGeometry( + target_rect.x() + self._arrival_dx, + target_rect.y(), + target_rect.width(), + target_rect.height(), + ) + self._arrival_anim.start() + + def _on_arrival_tick(self, value: Any) -> None: + p = float(value) + t = self._arrival_target + if t.isValid(): + self.move(t.x() + round((1.0 - p) * self._arrival_dx), t.y()) + self.setWindowOpacity(0.32 + 0.68 * p) + + def _on_arrival_done(self) -> None: + self.setWindowOpacity(1.0) + if self._arrival_target.isValid(): + self.setGeometry(self._arrival_target) + + def _emit_escape(self) -> None: + self.closed_by_system.emit() + + def set_magnet_locked(self, locked: bool) -> None: + self._magnet_locked = locked + + @property + def magnet_locked(self) -> bool: + return self._magnet_locked + + def mount_card(self, card: SpatialWingCard) -> None: + card.setParent(self) + self._root.addWidget(card, 1) + card.show() + + def _edges(self, pos: QPointF) -> Qt.Edge: + m = self._RESIZE_MARGIN + w, h = self.width(), self.height() + edges = Qt.Edge(0) + if pos.x() <= m: + edges |= Qt.Edge.LeftEdge + elif pos.x() >= w - m: + edges |= Qt.Edge.RightEdge + if pos.y() <= m: + edges |= Qt.Edge.TopEdge + elif pos.y() >= h - m: + edges |= Qt.Edge.BottomEdge + return edges + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + edges = self._edges(event.position()) + handle = self.windowHandle() + if edges and handle is not None and handle.startSystemResize(edges): + event.accept() + return + super().mousePressEvent(event) + + def closeEvent(self, event: Any) -> None: # noqa: N802 + super().closeEvent(event) + if not self._suppress_close_signal: + self.closed_by_system.emit() + + +def _relax_nested_minimum_widths(root: QWidget, cap: int = 460) -> None: + """Relax overly wide legacy QDialog child minimumWidths ONCE so side wings never clip.""" + + if getattr(root, "_spatial_wing_relaxed", False): + return + root._spatial_wing_relaxed = True # type: ignore[attr-defined] + if root.minimumWidth() > cap: + root.setMinimumWidth(min(cap, 400)) + if root.minimumHeight() > 560: + root.setMinimumHeight(420) + for child in root.findChildren(QWidget): + if child.minimumWidth() > cap: + child.setMinimumWidth(min(child.minimumWidth(), cap)) + + +class SpatialWingManager(QObject): + """Orchestrate Docked Left/Right Split-Wings and Magnetic Sidecar Windows on `SpatialShellWindow`.""" + + wing_visibility_changed = Signal(bool) + + def __init__( + self, + shell: QWidget, + *, + left_dock: QWidget, + right_dock: QWidget, + splitter: Any, + ) -> None: + super().__init__(shell) + self.shell = shell + self.left_dock = left_dock + self.right_dock = right_dock + self.splitter = splitter + + self._left_layout = QVBoxLayout(self.left_dock) + self._left_layout.setContentsMargins(0, 0, 6, 0) + self._left_layout.setSpacing(0) + + self._right_layout = QVBoxLayout(self.right_dock) + self._right_layout.setContentsMargins(6, 0, 0, 0) + self._right_layout.setSpacing(0) + + self.left_dock.hide() + self.right_dock.hide() + + self.card = SpatialWingCard(self.right_dock) + self._right_layout.addWidget(self.card, 1) + self.card.header.side_requested.connect(self.set_side) + self.card.header.mode_toggle_requested.connect(self.toggle_mode) + self.card.header.close_requested.connect(self.close_wing) + + self._side = "right" # "left" | "right" + self._mode = "docked" # "docked" | "sidecar" + self._preferred_width = 520 + self._title = "" + self._subtitle = "" + self._icon_kind = "ai" + self._active_widget: QWidget | None = None + self._active_dialog: QDialog | None = None + self._on_close_cb: Callable[[], None] | None = None + self._closing_guard = False + + self._sidecar: CompanionSidecarWindow | None = None + self._saved_shell_geom: tuple[bool, QRect, QSize] | None = None + self._syncing_geometry = False + + self.shell.installEventFilter(self) + QShortcut(QKeySequence("Esc"), self.card, activated=self.close_wing) + + @property + def is_open(self) -> bool: + return self._active_widget is not None + + @property + def side(self) -> str: + return self._side + + @property + def mode(self) -> str: + return self._mode + + @property + def active_widget(self) -> QWidget | None: + return self._active_widget + + def set_side(self, side: str) -> None: + normalized = "left" if str(side).strip().lower() == "left" else "right" + if normalized == self._side and self.is_open: + return + self._side = normalized + if self.is_open: + self._apply_placement() + + def set_mode(self, mode: str) -> None: + normalized = "sidecar" if str(mode).strip().lower() == "sidecar" else "docked" + if normalized == self._mode and self.is_open: + return + self._mode = normalized + if self.is_open: + self._apply_placement() + + def toggle_mode(self) -> None: + self.set_mode("sidecar" if self._mode == "docked" else "docked") + + def update_header(self, *, title: str | None = None, subtitle: str | None = None) -> None: + if title is not None: + self._title = title + if subtitle is not None: + self._subtitle = subtitle + self.card.header.set_metadata( + title=self._title, + subtitle=self._subtitle, + icon_kind=self._icon_kind, + side=self._side, + mode=self._mode, + ) + + def _should_animate_wing(self) -> bool: + return ( + self.shell.isVisible() + and not motion.reduced_motion() + and os.environ.get("QT_QPA_PLATFORM") != "offscreen" + ) + + def prewarm_widget(self, widget: QWidget, *, preferred_width: int = 540) -> None: + """Pre-attach a reusable heavy panel into `body_host` while keeping the wing closed.""" + + _relax_nested_minimum_widths(widget, cap=max(420, preferred_width - 40)) + if isinstance(widget, QDialog): + self._strip_dialog_chrome_once(widget, preferred_width=preferred_width) + widget.setModal(False) + widget.setProperty("hostedInSpatialWing", True) + widget.setProperty("doctorSkipOpenGeometry", True) + if widget.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground): + widget.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, False) + widget.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + if widget.windowFlags() != Qt.WindowType.Widget: + widget.setWindowFlags(Qt.WindowType.Widget) + if self.card.body_layout.indexOf(widget) < 0: + widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) + self.card.body_layout.addWidget(widget) + widget.hide() + + def _hide_inactive_body_children(self, keep: QWidget) -> None: + """Keep cached panels mounted in `body_host` (zero `setParent` cost!) while hiding all others.""" + + veil = self.card.glide_veil + for child in list(self.card.body_host.children()): + if isinstance(child, QWidget) and child is not keep and child is not veil and child.isVisible(): + child.hide() + + def _strip_dialog_chrome_once(self, dialog: QDialog, *, preferred_width: int) -> None: + if not getattr(dialog, "_spatial_wing_chrome_stripped", False): + dialog._spatial_wing_chrome_stripped = True # type: ignore[attr-defined] + scrim = getattr(dialog, "scrim", None) + if isinstance(scrim, QWidget): + scrim.hide() + scrim.setFixedWidth(0) + drawer_panel = getattr(dialog, "drawer_panel", None) + if isinstance(drawer_panel, QWidget): + drawer_panel.setMinimumWidth(0) + drawer_panel.setMaximumWidth(16777215) + for child in dialog.findChildren(QWidget): + if type(child).__name__ == "ClinicalAccentBar" or child.objectName() in { + "DiagnosisDrawerHeader", + "DiagnosisCloseButton", + }: + child.hide() + rx_header = dialog.findChild(QFrame, "PrescriptionDrawerHeader") + if rx_header is not None: + for btn in rx_header.findChildren(QPushButton): + if btn.text().strip() in {"×", "✕", "关闭"}: + btn.hide() + studio_outline = getattr(dialog, "studio_outline", None) + if isinstance(studio_outline, QWidget) and preferred_width < 840: + studio_outline.hide() + owner_ref = getattr(dialog, "_owner", None) + if owner_ref is not None and getattr(dialog, "_owner_filter_installed", False): + with suppress(RuntimeError): + owner_ref.removeEventFilter(dialog) + dialog._owner = None # type: ignore[attr-defined] + dialog._owner_filter_installed = False # type: ignore[attr-defined] + + def present_widget( + self, + widget: QWidget, + *, + title: str, + subtitle: str = "", + icon_kind: str = "ai", + preferred_width: int = 520, + side: str | None = None, + mode: str | None = None, + on_close: Callable[[], None] | None = None, + ) -> None: + """Mount a plain `QWidget` inside the Left/Right Spatial Wing or Sidecar at 60fps.""" + + self.card.glide_veil.cancel() + switching_widget = self._active_widget is not widget + if switching_widget: + self._teardown_active(reject_dialog=True) + + if side in {"left", "right"}: + self._side = side + if mode in {"docked", "sidecar"}: + self._mode = mode + self._title = title + self._subtitle = subtitle + self._icon_kind = icon_kind + self._preferred_width = max(400, min(820, int(preferred_width))) + self._active_widget = widget + self._active_dialog = widget if isinstance(widget, QDialog) else None + self._on_close_cb = on_close + + _relax_nested_minimum_widths(widget, cap=max(420, self._preferred_width - 40)) + + # Freeze shell updates for ONE atomic layout pass (zero half-baked intermediate frames!) + updates_were_enabled = self.shell.updatesEnabled() + if updates_were_enabled: + self.shell.setUpdatesEnabled(False) + try: + if self.card.body_layout.indexOf(widget) < 0: + widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) + self.card.body_layout.addWidget(widget) + self._hide_inactive_body_children(widget) + widget._in_present_widget_show = True # type: ignore[attr-defined] + try: + self.card.body_layout.setCurrentWidget(widget) + widget.show() + finally: + widget._in_present_widget_show = False # type: ignore[attr-defined] + + self._apply_placement() + if self.shell.centralWidget() and self.shell.centralWidget().layout(): + self.shell.centralWidget().layout().activate() + self.card.body_layout.activate() + finally: + if updates_were_enabled: + self.shell.setUpdatesEnabled(True) + + if ( + switching_widget + and self._mode == "docked" + and self._should_animate_wing() + and self.card.body_host.width() > 40 + ): + snap = self.card.body_host.grab() + self.card.glide_veil.play(snap, from_side=self._side) + + self.wing_visibility_changed.emit(True) + + def present_dialog( + self, + dialog: QDialog, + *, + title: str = "", + subtitle: str = "", + icon_kind: str = "consultations", + preferred_width: int = 520, + side: str | None = None, + ) -> None: + """Adapt and mount a `QDialog` non-modally inside the Spatial Wing.""" + + if self._active_dialog is dialog and self.is_open: + self.update_header( + title=title or dialog.windowTitle() or "临床工作窗", + subtitle=subtitle, + ) + self._apply_placement() + return + + self._strip_dialog_chrome_once(dialog, preferred_width=preferred_width) + + resolved_title = title or dialog.windowTitle().split(" - ")[0].strip() or "临床工作视窗" + if not subtitle: + store = getattr(self.shell, "patient_context_store", None) + snap = getattr(store, "current_patient", None) + if snap is not None and getattr(snap, "has_patient", False): + subtitle = snap.patient_name + + # Prevent WA_DeleteOnClose from prematurely freeing C++ wrapper during reparent + had_delete_on_close = dialog.testAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) + if had_delete_on_close: + dialog.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) + dialog.setProperty("_restoreDeleteOnClose", True) + + dialog.setModal(False) + dialog.setProperty("hostedInSpatialWing", True) + dialog.setProperty("doctorSkipOpenGeometry", True) + if dialog.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground): + dialog.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, False) + dialog.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + if dialog.windowFlags() != Qt.WindowType.Widget: + dialog.setWindowFlags(Qt.WindowType.Widget) + + def _on_dialog_finished(_code: int = 0) -> None: + if self._active_dialog is dialog and not self._closing_guard: + self.close_wing(from_dialog=True) + + if not getattr(dialog, "_spatial_wing_finished_wired", False): + dialog.finished.connect(_on_dialog_finished) + dialog._spatial_wing_finished_wired = True # type: ignore[attr-defined] + + self.present_widget( + dialog, + title=resolved_title, + subtitle=subtitle, + icon_kind=icon_kind, + preferred_width=preferred_width, + side=side, + ) + + def _apply_placement(self) -> None: + self.card.header.set_metadata( + title=self._title, + subtitle=self._subtitle, + icon_kind=self._icon_kind, + side=self._side, + mode=self._mode, + ) + if self._mode == "sidecar": + self._mount_in_sidecar() + else: + self._mount_in_dock() + + def _mount_in_dock(self) -> None: + if self._sidecar is not None and self._sidecar.isVisible(): + self._sidecar._suppress_close_signal = True + self._sidecar.hide() + self._sidecar._suppress_close_signal = False + self._restore_shell_geometry_if_saved() + + target_dock = self.left_dock if self._side == "left" else self.right_dock + other_dock = self.right_dock if self._side == "left" else self.left_dock + target_layout = self._left_layout if self._side == "left" else self._right_layout + + other_dock.hide() + if self.card.parentWidget() is not target_dock: + self.card.setParent(target_dock) + if target_layout.indexOf(self.card) < 0: + target_layout.addWidget(self.card, 1) + self.card.show() + target_dock.show() + + total_w = max(1080, self.splitter.width() or self.shell.width() - 40) + # Keep >= 59% width for the main clinical cockpit on 125%/150% DPI screens + wing_ratio = 0.40 if total_w < 1560 else 0.42 + wing_w = min(self._preferred_width, max(400, int(total_w * wing_ratio))) + main_w = max(640, total_w - wing_w) + if self._side == "left": + self.splitter.setSizes([wing_w, main_w, 0]) + else: + self.splitter.setSizes([0, main_w, wing_w]) + + def _ensure_sidecar(self) -> CompanionSidecarWindow: + if self._sidecar is None: + self._sidecar = CompanionSidecarWindow(self.shell) + self._sidecar.closed_by_system.connect(self.close_wing) + self.card.header.manual_drag_started.connect( + lambda: self._sidecar.set_magnet_locked(False) if self._sidecar else None + ) + self._sidecar.set_magnet_locked(True) + return self._sidecar + + def _mount_in_sidecar(self) -> None: + self.left_dock.hide() + self.right_dock.hide() + self.splitter.setSizes([0, max(800, self.shell.width()), 0]) + + sidecar = self._ensure_sidecar() + was_visible = sidecar.isVisible() + sidecar.mount_card(self.card) + self._arrange_shell_and_sidecar(initial=True) + target_geom = QRect(sidecar.geometry()) + sidecar.show() + sidecar.raise_() + if not was_visible and target_geom.isValid(): + sidecar.animate_arrival(target_geom, side=self._side) + + def _arrange_shell_and_sidecar(self, *, initial: bool = False) -> None: + if self._sidecar is None or self._syncing_geometry: + return + if not self._sidecar.magnet_locked and not initial: + return + screen = self.shell.screen() or QApplication.primaryScreen() + raw_avail = screen.availableGeometry() if screen is not None else QRect(0, 0, 1920, 1040) + # In headless offscreen tests where screen defaults to 800x600 or 1280x720 while the + # shell was explicitly sized wider, synthesize a realistic 1920x1040 desktop envelope. + if raw_avail.width() < 1400 and self.shell.width() >= 1400: + avail = QRect(0, 0, max(1920, self.shell.width() + 560), max(1040, self.shell.height() + 40)) + else: + avail = raw_avail + gap = 10 + wing_w = min(self._preferred_width, max(440, int(avail.width() * 0.36))) + + self._syncing_geometry = True + try: + main_geom = self.shell.frameGeometry() + fits_right = ( + not self.shell.isMaximized() + and main_geom.right() + gap + wing_w <= avail.right() - 4 + ) + fits_left = ( + not self.shell.isMaximized() + and main_geom.left() - gap - wing_w >= avail.left() + 4 + ) + if (self._side == "right" and fits_right) or (self._side == "left" and fits_left): + sx = ( + main_geom.right() + gap + if self._side == "right" + else main_geom.left() - gap - wing_w + ) + self._sidecar.setGeometry(sx, main_geom.top(), wing_w, main_geom.height()) + return + + # Single-screen auto-split: save original shell geometry once and arrange side-by-side! + if self._saved_shell_geom is None: + self._saved_shell_geom = ( + self.shell.isMaximized(), + QRect(self.shell.geometry()), + QSize(self.shell.minimumSize()), + ) + if self.shell.isMaximized(): + self.shell.showNormal() + self.shell.setMinimumSize(max(860, min(920, avail.width() - wing_w - 28)), 640) + + pad = 8 + usable_w = avail.width() - pad * 2 - gap + actual_wing_w = min(wing_w, max(400, int(usable_w * 0.36))) + actual_main_w = max(860, usable_w - actual_wing_w) + if actual_main_w + actual_wing_w > usable_w: + actual_wing_w = max(390, usable_w - actual_main_w) + usable_h = avail.height() - pad * 2 + top_y = avail.top() + pad + + if self._side == "right": + main_x = avail.left() + pad + side_x = main_x + actual_main_w + gap + else: + side_x = avail.left() + pad + main_x = side_x + actual_wing_w + gap + + self.shell.setGeometry(main_x, top_y, actual_main_w, usable_h) + self._sidecar.setGeometry(side_x, top_y, actual_wing_w, usable_h) + finally: + self._syncing_geometry = False + + def _restore_shell_geometry_if_saved(self) -> None: + if self._saved_shell_geom is None: + return + was_max, old_rect, old_min = self._saved_shell_geom + self._saved_shell_geom = None + self._syncing_geometry = True + try: + self.shell.setMinimumSize(old_min) + if was_max: + self.shell.showMaximized() + elif old_rect.isValid(): + self.shell.setGeometry(old_rect) + finally: + self._syncing_geometry = False + + def _teardown_active(self, *, reject_dialog: bool) -> None: + widget = self._active_widget + dialog = self._active_dialog + on_close = self._on_close_cb + self._active_widget = None + self._active_dialog = None + self._on_close_cb = None + if widget is None: + return + self._closing_guard = True + try: + widget.hide() + if dialog is not None: + if reject_dialog and dialog.result() == 0: + with suppress(RuntimeError): + dialog.reject() + if dialog.property("_restoreDeleteOnClose"): + self.card.body_layout.removeWidget(widget) + with suppress(RuntimeError): + dialog.deleteLater() + if on_close is not None: + with suppress(Exception): + on_close() + finally: + self._closing_guard = False + + def close_wing(self, *, from_dialog: bool = False) -> None: + if not self.is_open and (self._sidecar is None or not self._sidecar.isVisible()): + return + self._teardown_active(reject_dialog=not from_dialog) + self.left_dock.hide() + self.right_dock.hide() + if self._sidecar is not None and self._sidecar.isVisible(): + self._sidecar._suppress_close_signal = True + self._sidecar.hide() + self._sidecar._suppress_close_signal = False + self._restore_shell_geometry_if_saved() + self.wing_visibility_changed.emit(False) + + def close_all(self) -> None: + self.close_wing() + if self._sidecar is not None: + self._sidecar._suppress_close_signal = True + self._sidecar.close() + self._sidecar.deleteLater() + self._sidecar = None + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 + if watched is self.shell and self._mode == "sidecar" and self.is_open and self._sidecar is not None: + et = event.type() + if et in {QEvent.Type.Move, QEvent.Type.Resize} and not self._syncing_geometry: + if self._sidecar.magnet_locked and not self.shell.isMinimized(): + main_g = self.shell.frameGeometry() + gap = 10 + sx = ( + main_g.right() + gap + if self._side == "right" + else main_g.left() - gap - self._sidecar.width() + ) + self._sidecar.setGeometry(sx, main_g.top(), self._sidecar.width(), main_g.height()) + elif et == QEvent.Type.WindowStateChange: + if self.shell.isMinimized(): + self._sidecar.hide() + elif not self._sidecar.isVisible(): + self._sidecar.show() + return super().eventFilter(watched, event) + + +def _infer_wing_spec(dialog: QDialog) -> tuple[str, int]: + """Return `(icon_kind, preferred_width)` tailored to each dialog quadrant.""" + + cls_name = type(dialog).__name__ + obj_name = dialog.objectName() or "" + combined = f"{cls_name} {obj_name}" + + if any(k in combined for k in ("AiConsult", "IssuedPrescriptionAi")): + return ("ai", 620) + if any(k in combined for k in ("AiAnalysis", "AiReport", "AiAssistant", "AiStatistics")): + return ("ai", 540) + if any(k in combined for k in ("DiagnosisDialog",)): + return ("consultations", 660) + if any( + k in combined + for k in ( + "PrescriptionEditor", + "PrescriptionDetail", + "PrescriptionTemplate", + "PrescriptionEsign", + ) + ): + return ("prescriptions", 680) + if any(k in combined for k in ("Video", "AudioQueue")): + return ("video", 520) + if any(k in combined for k in ("Qr", "Update")): + return ("qrcode", 420) + if any(k in combined for k in ("Appointment",)): + return ("appointments", 460) + return ("consultations", 460) + + +_ORIG_QDIALOG_SHOW = QDialog.show +_ORIG_QDIALOG_OPEN = QDialog.open +_ORIG_QDIALOG_EXEC = QDialog.exec +_GLOBAL_QDIALOG_HOOKS_INSTALLED = False + + +def _should_route_dialog_to_wing(dialog: QDialog) -> Any: + """Return active `SpatialShellWindow` when `dialog` should mount in the Wing, else `None`.""" + + if isinstance(dialog, (QMessageBox, QInputDialog, QFileDialog)): + return None + if dialog.metaObject().className() == "QPrintDialog": + return None + if bool(dialog.property("skipSpatialWing")): + return None + if bool(getattr(dialog, "_in_present_widget_show", False)): + return None + if bool(getattr(dialog, "_embedded", False)): + return None + if not dialog.isWindow() and not bool(dialog.property("hostedInSpatialWing")): + return None + return find_spatial_shell(dialog) + + +def _resolve_dialog_wing_spec(dialog: QDialog) -> tuple[str, int, str | None]: + default_icon, default_w = _infer_wing_spec(dialog) + ic = getattr(dialog, "_wing_icon_kind", None) or default_icon + pw = getattr(dialog, "_wing_preferred_width", None) or default_w + side = getattr(dialog, "_wing_preferred_side", None) + return (str(ic), int(pw), side) + + +def install_global_qdialog_wing_hooks() -> None: + """Install once on `QDialog` so every business dialog routes `.show/.open/.exec` to Wing.""" + + global _GLOBAL_QDIALOG_HOOKS_INSTALLED + if _GLOBAL_QDIALOG_HOOKS_INSTALLED: + return + _GLOBAL_QDIALOG_HOOKS_INSTALLED = True + + def _qdialog_show(self: QDialog) -> None: + shell = _should_route_dialog_to_wing(self) + if shell is None: + _ORIG_QDIALOG_SHOW(self) + return + ic, pw, side = _resolve_dialog_wing_spec(self) + shell.wing_manager.present_dialog( + self, + icon_kind=ic, + preferred_width=pw, + side=side, + ) + + def _qdialog_open(self: QDialog) -> None: + shell = _should_route_dialog_to_wing(self) + if shell is None: + _ORIG_QDIALOG_OPEN(self) + return + ic, pw, side = _resolve_dialog_wing_spec(self) + shell.wing_manager.present_dialog( + self, + icon_kind=ic, + preferred_width=pw, + side=side, + ) + + def _qdialog_exec(self: QDialog) -> int: + if getattr(self, "_in_wing_exec", False): + return int(self.result()) + shell = _should_route_dialog_to_wing(self) + if shell is None: + return int(_ORIG_QDIALOG_EXEC(self)) + ic, pw, side = _resolve_dialog_wing_spec(self) + self._in_wing_exec = True # type: ignore[attr-defined] + self.setResult(int(QDialog.DialogCode.Rejected)) + loop = QEventLoop(self) + self.finished.connect(loop.quit) + shell.close_requested.connect(self.reject) + try: + shell.wing_manager.present_dialog( + self, + icon_kind=ic, + preferred_width=pw, + side=side, + ) + if self.isVisible(): + loop.exec() + finally: + self._in_wing_exec = False # type: ignore[attr-defined] + with suppress(RuntimeError, TypeError): + self.finished.disconnect(loop.quit) + with suppress(RuntimeError, TypeError): + shell.close_requested.disconnect(self.reject) + return int(self.result()) + + QDialog.show = _qdialog_show # type: ignore[method-assign] + QDialog.open = _qdialog_open # type: ignore[method-assign] + QDialog.exec = _qdialog_exec # type: ignore[method-assign] + + +def install_wing_dialog_support( + dialog: QDialog, + *, + icon_kind: str | None = None, + preferred_width: int | None = None, + preferred_side: str | None = None, +) -> None: + """Attach optional Spatial Wing metadata to `dialog` and ensure global hooks are active.""" + + install_global_qdialog_wing_hooks() + if icon_kind is not None: + dialog._wing_icon_kind = icon_kind # type: ignore[attr-defined] + if preferred_width is not None: + dialog._wing_preferred_width = preferred_width # type: ignore[attr-defined] + if preferred_side is not None: + dialog._wing_preferred_side = preferred_side # type: ignore[attr-defined] + + +# ── Quadrant 4: Frameless Jade-Porcelain Confirm & Quick-Input Sheets ──────── + +_CRYSTAL_SHEET_QSS = """ +QFrame#CrystalPopupSurface { + background-color: #FFFFFF; + border: 1px solid #CFE0DC; + border-radius: 20px; +} +QLabel#CrystalPopupTitle { + color: #0F1F1D; + font-size: 16px; + font-weight: 600; +} +QLabel#CrystalPopupBody { + color: #425855; + font-size: 13px; +} +QPushButton#CrystalSecondaryBtn { + min-height: 36px; + max-height: 36px; + padding: 0 18px; + border-radius: 18px; + border: 1px solid #DCE7E4; + background-color: #F4F8F7; + color: #1A2E2C; + font-size: 13px; + font-weight: 600; +} +QPushButton#CrystalSecondaryBtn:hover { + background-color: #E5F2EE; + border-color: #9ED0C3; + color: #0E6F5C; +} +QPushButton#CrystalPrimaryBtn { + min-height: 36px; + max-height: 36px; + padding: 0 20px; + border-radius: 18px; + border: 0; + background-color: #0E6F5C; + color: #FFFFFF; + font-size: 13px; + font-weight: 600; +} +QPushButton#CrystalPrimaryBtn:hover { + background-color: #0A5949; +} +QPushButton#CrystalDangerBtn { + min-height: 36px; + max-height: 36px; + padding: 0 20px; + border-radius: 18px; + border: 0; + background-color: #D9534F; + color: #FFFFFF; + font-size: 13px; + font-weight: 600; +} +QPushButton#CrystalDangerBtn:hover { + background-color: #C03D39; +} +""" + + +class ClinicalConfirmDialog(QDialog): + """Frameless 20px rounded jade-porcelain confirmation card (zero OS gray chrome).""" + + def __init__( + self, + parent: QWidget | None, + title: str, + message: str, + *, + confirm_text: str = "确认", + cancel_text: str | None = "取消", + danger: bool = False, + ) -> None: + super().__init__(parent) + self.setProperty("skipSpatialWing", True) + self.setProperty("doctorSkipOpenGeometry", True) + self.setWindowTitle(title) + self.setModal(True) + self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setStyleSheet(_CRYSTAL_SHEET_QSS) + self.setFixedWidth(430) + + outer = QVBoxLayout(self) + outer.setContentsMargins(6, 6, 6, 6) + surface = QFrame(self) + surface.setObjectName("CrystalPopupSurface") + outer.addWidget(surface) + + layout = QVBoxLayout(surface) + layout.setContentsMargins(24, 22, 24, 20) + layout.setSpacing(14) + + head = QHBoxLayout() + head.setSpacing(12) + badge = QLabel("!" if danger else "?", surface) + badge.setFixedSize(34, 34) + badge.setAlignment(Qt.AlignmentFlag.AlignCenter) + badge.setStyleSheet( + f"background-color: {'#FCEBE8' if danger else '#E2F3EE'};" + f" color: {'#D9534F' if danger else '#0E6F5C'};" + " border-radius: 17px; font-size: 16px; font-weight: 700;" + ) + head.addWidget(badge) + + t_lbl = QLabel(title, surface) + t_lbl.setObjectName("CrystalPopupTitle") + t_font = QFont(heading_family()) + t_font.setPixelSize(16) + t_font.setWeight(QFont.Weight.DemiBold) + t_lbl.setFont(t_font) + head.addWidget(t_lbl, 1) + layout.addLayout(head) + + b_lbl = QLabel(message, surface) + b_lbl.setObjectName("CrystalPopupBody") + b_lbl.setWordWrap(True) + b_lbl.setFont(QFont(body_family(), 10)) + layout.addWidget(b_lbl) + + btn_row = QHBoxLayout() + btn_row.addStretch(1) + if cancel_text: + cancel_btn = QPushButton(cancel_text, surface) + cancel_btn.setObjectName("CrystalSecondaryBtn") + cancel_btn.setCursor(Qt.CursorShape.PointingHandCursor) + cancel_btn.clicked.connect(self.reject) + btn_row.addWidget(cancel_btn) + + ok_btn = QPushButton(confirm_text, surface) + ok_btn.setObjectName("CrystalDangerBtn" if danger else "CrystalPrimaryBtn") + ok_btn.setCursor(Qt.CursorShape.PointingHandCursor) + ok_btn.clicked.connect(self.accept) + btn_row.addWidget(ok_btn) + layout.addLayout(btn_row) + + def showEvent(self, event: Any) -> None: # noqa: N802 + super().showEvent(event) + ref = self.parentWidget() + if ref is not None: + win = ref.window() + center = win.frameGeometry().center() + self.move(center.x() - self.width() // 2, center.y() - self.height() // 2) + + +class ClinicalInputDialog(QDialog): + """Frameless jade-porcelain input sheet replacing raw `QInputDialog`.""" + + def __init__( + self, + parent: QWidget | None, + title: str, + label: str, + *, + mode: str = "text", # "text" | "multiline" | "item" + text: str = "", + placeholder: str = "", + items: Sequence[str] = (), + current: int = 0, + ) -> None: + super().__init__(parent) + self._mode = mode + self.setProperty("skipSpatialWing", True) + self.setProperty("doctorSkipOpenGeometry", True) + self.setWindowTitle(title) + self.setModal(True) + self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setStyleSheet(_CRYSTAL_SHEET_QSS) + self.setFixedWidth(450) + + outer = QVBoxLayout(self) + outer.setContentsMargins(6, 6, 6, 6) + surface = QFrame(self) + surface.setObjectName("CrystalPopupSurface") + outer.addWidget(surface) + + layout = QVBoxLayout(surface) + layout.setContentsMargins(24, 20, 24, 20) + layout.setSpacing(12) + + t_lbl = QLabel(title, surface) + t_lbl.setObjectName("CrystalPopupTitle") + layout.addWidget(t_lbl) + + l_lbl = QLabel(label, surface) + l_lbl.setObjectName("CrystalPopupBody") + l_lbl.setWordWrap(True) + layout.addWidget(l_lbl) + + self.line_edit: QLineEdit | None = None + self.multi_edit: QPlainTextEdit | None = None + self.combo: QComboBox | None = None + + field_qss = ( + "border: 1px solid #CFE0DC; border-radius: 12px; padding: 8px 12px;" + " background: #F9FCFB; color: #11201E; font-size: 13px;" + ) + if mode == "multiline": + self.multi_edit = QPlainTextEdit(text, surface) + self.multi_edit.setPlaceholderText(placeholder) + self.multi_edit.setFixedHeight(108) + self.multi_edit.setStyleSheet(field_qss) + layout.addWidget(self.multi_edit) + elif mode == "item": + self.combo = QComboBox(surface) + self.combo.addItems(list(items)) + if 0 <= current < len(items): + self.combo.setCurrentIndex(current) + self.combo.setFixedHeight(38) + self.combo.setStyleSheet(field_qss) + layout.addWidget(self.combo) + else: + self.line_edit = QLineEdit(text, surface) + self.line_edit.setPlaceholderText(placeholder) + self.line_edit.setFixedHeight(38) + self.line_edit.setStyleSheet(field_qss) + self.line_edit.returnPressed.connect(self.accept) + layout.addWidget(self.line_edit) + + btn_row = QHBoxLayout() + btn_row.addStretch(1) + cancel_btn = QPushButton("取消", surface) + cancel_btn.setObjectName("CrystalSecondaryBtn") + cancel_btn.setCursor(Qt.CursorShape.PointingHandCursor) + cancel_btn.clicked.connect(self.reject) + btn_row.addWidget(cancel_btn) + + ok_btn = QPushButton("确认提交", surface) + ok_btn.setObjectName("CrystalPrimaryBtn") + ok_btn.setCursor(Qt.CursorShape.PointingHandCursor) + ok_btn.clicked.connect(self.accept) + btn_row.addWidget(ok_btn) + layout.addLayout(btn_row) + + def value(self) -> str: + if self.multi_edit is not None: + return self.multi_edit.toPlainText() + if self.combo is not None: + return self.combo.currentText() + if self.line_edit is not None: + return self.line_edit.text() + return "" + + def showEvent(self, event: Any) -> None: # noqa: N802 + super().showEvent(event) + ref = self.parentWidget() + if ref is not None: + win = ref.window() + center = win.frameGeometry().center() + self.move(center.x() - self.width() // 2, center.y() - self.height() // 2) + QTimer.singleShot( + 0, + lambda: ( + self.line_edit.setFocus() + if self.line_edit + else (self.multi_edit.setFocus() if self.multi_edit else None) + ), + ) + + +def clinical_confirm( + parent: QWidget | None, + title: str, + message: str, + *, + confirm_text: str = "确认", + cancel_text: str = "取消", + danger: bool = False, +) -> bool: + dlg = ClinicalConfirmDialog( + parent, + title, + message, + confirm_text=confirm_text, + cancel_text=cancel_text, + danger=danger, + ) + return dlg.exec() == int(QDialog.DialogCode.Accepted) + + +def clinical_alert( + parent: QWidget | None, + title: str, + message: str, + *, + danger: bool = False, +) -> None: + dlg = ClinicalConfirmDialog( + parent, + title, + message, + confirm_text="我知道了", + cancel_text=None, + danger=danger, + ) + dlg.exec() + + +def clinical_get_text( + parent: QWidget | None, + title: str, + label: str, + *, + text: str = "", + placeholder: str = "", +) -> tuple[str, bool]: + dlg = ClinicalInputDialog( + parent, title, label, mode="text", text=text, placeholder=placeholder + ) + ok = dlg.exec() == int(QDialog.DialogCode.Accepted) + return (dlg.value(), ok) + + +def clinical_get_multiline( + parent: QWidget | None, + title: str, + label: str, + *, + text: str = "", + placeholder: str = "", +) -> tuple[str, bool]: + dlg = ClinicalInputDialog( + parent, title, label, mode="multiline", text=text, placeholder=placeholder + ) + ok = dlg.exec() == int(QDialog.DialogCode.Accepted) + return (dlg.value(), ok) + + +def clinical_get_item( + parent: QWidget | None, + title: str, + label: str, + items: Sequence[str], + *, + current: int = 0, +) -> tuple[str, bool]: + dlg = ClinicalInputDialog( + parent, title, label, mode="item", items=items, current=current + ) + ok = dlg.exec() == int(QDialog.DialogCode.Accepted) + return (dlg.value(), ok) + + +__all__ = [ + "ClinicalConfirmDialog", + "ClinicalInputDialog", + "CompanionSidecarWindow", + "SpatialWingCard", + "SpatialWingManager", + "clinical_alert", + "clinical_confirm", + "clinical_get_item", + "clinical_get_multiline", + "clinical_get_text", + "find_spatial_shell", + "install_global_qdialog_wing_hooks", + "install_wing_dialog_support", +] diff --git a/app/src/doctor_workstation/ui/state/patient_context_store.py b/app/src/doctor_workstation/ui/state/patient_context_store.py index a4e43bec4..91f4ed4af 100644 --- a/app/src/doctor_workstation/ui/state/patient_context_store.py +++ b/app/src/doctor_workstation/ui/state/patient_context_store.py @@ -2,11 +2,13 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import dataclass, field from typing import Any from PySide6.QtCore import QObject, Signal +from ...core.models import Appointment, Consultation, Patient from ..widgets import display_text, first_value, gender_text @@ -40,10 +42,10 @@ class PatientSnapshot: gender_age: str = "" phone: str = "—" course_text: str = "" - clinical_diagnosis: str = "待选择接诊患者" + clinical_diagnosis: str = "" chief_complaint: str = "" status_code: int = 0 - status_text: str = "待接诊" + status_text: str = "待选择" assistant_name: str = "—" doctor_name: str = "—" appointment_time: str = "" @@ -64,13 +66,13 @@ class PatientSnapshot: part for part in ( self.gender_age, - self.clinical_diagnosis if self.clinical_diagnosis != "—" else "", + self.clinical_diagnosis if self.clinical_diagnosis and self.clinical_diagnosis != "—" else "", f"病程 {self.course_text}" if self.course_text and self.course_text != "—" else "", self.appointment_time, ) if part ] - return " · ".join(parts[:3]) if parts else "从今日门诊计划或挂号队列选择患者" + return " · ".join(parts[:3]) if parts else "已关联当前患者临床上下文" class PatientContextStore(QObject): @@ -148,7 +150,12 @@ class PatientContextStore(QObject): appointment, "patient_name", "name", - default=first_value(patient, "name", "patient_name", default="患者"), + default=first_value( + diagnosis, + "patient_name", + "name", + default=first_value(patient, "name", "patient_name", default="患者"), + ), ) ) raw_gender = next( @@ -195,44 +202,71 @@ class PatientContextStore(QObject): first_value( diagnosis, "clinical_diagnosis", + "diagnosis_type_text", + "syndrome_type_text", "diagnosis_name", "disease_name", - default="中医糖代谢调理", - ) + default=first_value( + appointment, + "clinical_diagnosis", + "diagnosis_type_text", + default="", + ), + ), + "", ) chief = display_text( first_value(diagnosis, "chief_complaint", "complaint", default=""), "", ) + is_consultation_source = ( + str(first_value(appointment, "_queue_source", default="") or "") == "consultation" + ) status_code = _safe_int(first_value(appointment, "status", default=1), 1) status_map = {1: "待接诊", 2: "已取消", 3: "已完成", 4: "已过号"} + default_status = "在管诊单" if is_consultation_source else status_map.get(status_code, "待接诊") status_text = display_text( first_value( appointment, "status_desc", "status_text", - default=status_map.get(status_code, "待接诊"), + default=default_status, ) ) - appt_id = _safe_int(first_value(appointment, "id", "appointment_id", default=0)) + + raw_appt_id = _safe_int( + first_value( + appointment, + "real_appointment_id", + "appointment_id", + default=0 if is_consultation_source else first_value(appointment, "id", default=0), + ) + ) + appt_id = max(0, raw_appt_id) diag_id = _safe_int( first_value( diagnosis, "id", "diagnosis_id", - default=first_value(appointment, "diagnosis_id", "patient_id", default=0), + default=first_value(appointment, "diagnosis_id", default=0), ) ) pat_id = _safe_int( first_value( - appointment, - "source_patient_id", + diagnosis, "patient_id", - default=first_value(patient, "id", "source_patient_id", default=0), + "source_patient_id", + default=first_value( + appointment, + "source_patient_id", + "stable_patient_id", + "patient_id", + default=first_value(patient, "id", "source_patient_id", default=0), + ), ) ) raw: dict[str, Any] = {} - if isinstance(appointment, dict): + if isinstance(appointment, Mapping): raw.update(appointment) snapshot = PatientSnapshot( appointment_id=appt_id, @@ -249,7 +283,14 @@ class PatientContextStore(QObject): assistant_name=display_text(first_value(appointment, "assistant_name", default="—")), doctor_name=display_text(first_value(appointment, "doctor_name", default="—")), appointment_time=display_text( - first_value(appointment, "appointment_time_text", "appointment_time", default=""), + first_value( + appointment, + "appointment_time_text", + "appointment_time", + "appointment_date", + "diagnosis_date", + default="", + ), "", ), raw_record=raw, @@ -258,8 +299,72 @@ class PatientContextStore(QObject): return snapshot def update_from_row(self, row: Any) -> PatientSnapshot: - """Build and publish a lightweight snapshot when selecting a list/table row.""" + """Build and publish an accurate snapshot from Appointment, Consultation, or Patient row.""" if not row: return self._current_patient - return self.update_from_reception(row, row, row) + if isinstance(row, Appointment): + raw_map = dict(row.raw) if isinstance(row.raw, Mapping) else {} + raw_map.setdefault("id", row.id) + raw_map.setdefault("appointment_id", row.id) + raw_map.setdefault("diagnosis_id", row.diagnosis_id) + raw_map.setdefault("patient_id", row.source_patient_id or row.patient_id) + raw_map.setdefault("patient_name", row.patient_name) + return self.update_from_reception(raw_map, raw_map, raw_map) + + if isinstance(row, Consultation): + raw_map = dict(row.raw) if isinstance(row.raw, Mapping) else {} + appt_id = _safe_int( + first_value(raw_map, "latest_appointment_id", "appointment_id", default=0) + ) + synthetic = dict(raw_map) + synthetic["_queue_source"] = "consultation" + synthetic["real_appointment_id"] = appt_id + synthetic["diagnosis_id"] = row.id + synthetic["patient_id"] = _safe_int( + first_value(raw_map, "patient_id", "source_patient_id", default=row.patient_id or 0) + ) + synthetic["patient_name"] = row.patient_name + synthetic["status_desc"] = display_text( + first_value(raw_map, "appointment_status_desc", "status_desc", default="在管诊单") + ) + return self.update_from_reception(synthetic, raw_map, raw_map) + + if isinstance(row, Patient): + raw_map = dict(row.raw) if isinstance(row.raw, Mapping) else {} + appt_id = _safe_int( + first_value(raw_map, "latest_appointment_id", "appointment_id", default=0) + ) + diag_id = _safe_int( + first_value(raw_map, "latest_diagnosis_id", "diagnosis_id", default=row.latest_diagnosis_id or 0) + ) + synthetic = dict(raw_map) + synthetic["_queue_source"] = "consultation" + synthetic["real_appointment_id"] = appt_id + synthetic["diagnosis_id"] = diag_id + synthetic["patient_id"] = row.id + synthetic["patient_name"] = row.name + synthetic["status_desc"] = "在管患者" + diag_seed = dict(raw_map) + diag_seed["id"] = diag_id + diag_seed["patient_id"] = row.id + return self.update_from_reception(synthetic, raw_map, diag_seed) + + # Generic dict row heuristic + has_appt_fields = bool( + first_value(row, "appointment_time", "appointment_date", default="") + and str(first_value(row, "_queue_source", default="")) != "consultation" + ) + if has_appt_fields: + return self.update_from_reception(row, row, {}) + synthetic_dict = dict(row) if isinstance(row, Mapping) else {} + synthetic_dict.setdefault("_queue_source", "consultation") + synthetic_dict.setdefault( + "real_appointment_id", + _safe_int(first_value(row, "latest_appointment_id", "appointment_id", default=0)), + ) + synthetic_dict.setdefault( + "diagnosis_id", + _safe_int(first_value(row, "diagnosis_id", "latest_diagnosis_id", "id", default=0)), + ) + return self.update_from_reception(synthetic_dict, row, row) diff --git a/app/src/doctor_workstation/ui/theme.py b/app/src/doctor_workstation/ui/theme.py index 024e5c360..dd68e1211 100755 --- a/app/src/doctor_workstation/ui/theme.py +++ b/app/src/doctor_workstation/ui/theme.py @@ -899,6 +899,15 @@ QSlider::handle:horizontal { } QSlider::handle:horizontal:hover { border-color: $focus; } +QToolTip { + background-color: #162624; + color: #F2F7F6; + border: 1px solid #2D4A45; + border-radius: 8px; + padding: 7px 11px; + font-size: 12px; +} + QLabel#StatusBadge { padding: 2px 8px; border: 1px solid transparent; @@ -1322,21 +1331,12 @@ def _apply_group( def _register_preferred_cjk_fonts() -> str: - """Prefer the shipped outline font, with native CJK faces as a fallback.""" + """Prefer native ClearType/CoreText CJK UI faces on desktop OSes; use bundled VF as fallback.""" app = QApplication.instance() registered = getattr(app, "_doctor_bundled_font_family", None) if registered: return registered - bundled_font = resource_path("fonts", "NotoSansSC-VF.ttf") - if bundled_font.is_file(): - font_id = QFontDatabase.addApplicationFont(str(bundled_font)) - families = QFontDatabase.applicationFontFamilies(font_id) if font_id >= 0 else [] - if families: - family = families[0] - if app is not None: - app._doctor_bundled_font_family = family - return family platform_families = { "win32": ("Microsoft YaHei UI", "Microsoft YaHei"), @@ -1356,9 +1356,25 @@ def _register_preferred_cjk_fonts() -> str: font_id = QFontDatabase.addApplicationFont(str(font_path)) if font_id >= 0 and QFontDatabase.applicationFontFamilies(font_id): available.update(QFontDatabase.applicationFontFamilies(font_id)) - for family in (*preferred, "Arial Unicode MS"): + + for family in preferred: if family in available: + if app is not None: + app._doctor_bundled_font_family = family return family + + bundled_font = resource_path("fonts", "NotoSansSC-VF.ttf") + if bundled_font.is_file(): + font_id = QFontDatabase.addApplicationFont(str(bundled_font)) + families = QFontDatabase.applicationFontFamilies(font_id) if font_id >= 0 else [] + if families: + family = families[0] + if app is not None: + app._doctor_bundled_font_family = family + return family + + if "Arial Unicode MS" in available: + return "Arial Unicode MS" return QApplication.font().family() @@ -1438,16 +1454,15 @@ def allow_dialog_resize(dialog: QDialog) -> None: def mark_business_dialog(dialog: QDialog, object_name: str | None = None) -> None: - """Opt a business subwindow into the shared visual contract. - - The helper intentionally does not change modality, ownership or result - handling. It only supplies stable styling metadata, semantic button roles - and window affordances, so existing workflows keep their original behavior. - """ + """Opt a business subwindow into the shared visual contract and Spatial Wing engine.""" if object_name and not dialog.objectName(): dialog.setObjectName(object_name) dialog.setProperty("businessDialog", True) + if not isinstance(dialog, (QMessageBox, QInputDialog, QFileDialog)): + from .spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(dialog) allow_dialog_resize(dialog) for button_box in dialog.findChildren(QDialogButtonBox): _polish_dialog_buttons(button_box) @@ -1568,9 +1583,38 @@ class _BusinessDialogStyleFilter(QObject): if isinstance(watched, QDialogButtonBox): _polish_dialog_buttons(watched) elif isinstance(watched, QDialog) and event_type == QEvent.Type.Polish: - # Window flags can only be changed before the dialog is on screen, - # so dynamically-created dialogs get their affordances at polish - # time rather than when they are already visible. + if isinstance(watched, (QMessageBox, QInputDialog)): + from .spatial_wings import find_spatial_shell + + if find_spatial_shell(watched) is not None and not watched.isVisible(): + watched.setProperty("doctorSkipOpenGeometry", True) + watched.setWindowFlags( + Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint + ) + watched.setStyleSheet( + "QMessageBox, QInputDialog {" + " background-color: #FFFFFF;" + " border: 2px solid #B7D4CC;" + " border-radius: 16px;" + " padding: 10px;" + "}" + "QMessageBox QPushButton, QInputDialog QPushButton {" + " min-height: 34px; padding: 0 18px; border-radius: 17px;" + " border: 1px solid #D5E4DF; background-color: #F4F8F7;" + " color: #172B29; font-weight: 600;" + "}" + "QMessageBox QPushButton:hover, QInputDialog QPushButton:hover {" + " background-color: #E3F3EE; border-color: #96CBC0; color: #0E6F5C;" + "}" + ) + elif ( + not isinstance(watched, QFileDialog) + and watched.metaObject().className() != "QPrintDialog" + and not watched.property("skipSpatialWing") + ): + from .spatial_wings import install_wing_dialog_support + + install_wing_dialog_support(watched) if not self._is_native_or_overlay(watched): allow_dialog_resize(watched) elif isinstance(watched, QDialog) and event_type == QEvent.Type.Show: @@ -1601,6 +1645,9 @@ class _BusinessDialogStyleFilter(QObject): def _install_business_dialog_styling(app: QApplication) -> None: + from .spatial_wings import install_global_qdialog_wing_hooks + + install_global_qdialog_wing_hooks() interactions.install_tactile_interactions(app) existing = getattr(app, "_doctor_business_dialog_style_filter", None) if existing is not None: diff --git a/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py b/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py index 04ea25aad..76eda76e9 100644 --- a/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py +++ b/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py @@ -15,7 +15,7 @@ import math import re from collections.abc import Mapping, Sequence from dataclasses import dataclass -from datetime import date, timedelta +from datetime import date, datetime, timedelta from typing import Any from ..widgets import display_text, first_value @@ -74,6 +74,52 @@ def _is_normal_or_negated(text: str) -> bool: return norm.startswith(("无", "否认", "未见", "未发现")) +def _clean_date_iso(raw: Any) -> str: + """Return a valid YYYY-MM-DD string, rejecting 0, '0', 1970-01-01, or placeholders.""" + + if raw in (None, "", 0, "0", False, "—", "-"): + return "" + if isinstance(raw, (int, float)) and raw >= 946684800: + try: + return datetime.fromtimestamp(float(raw)).strftime("%Y-%m-%d") + except (OSError, OverflowError, ValueError): + return "" + text = str(raw).strip() + if text in {"0", "0000-00-00", "1970-01-01", "None", "null", "—", "-"}: + return "" + if text.isdigit() and int(text) >= 946684800: + try: + return datetime.fromtimestamp(int(text)).strftime("%Y-%m-%d") + except (OSError, OverflowError, ValueError): + return "" + if len(text) >= 10 and text[4] in {"-", "/"} and text[7] in {"-", "/"}: + iso = text[:10].replace("/", "-") + return "" if iso.startswith(("0000", "1970-01-01")) else iso + return "" + + +def _extract_intake_kv(raw_text: str) -> dict[str, str]: + """Extract structured key:value pairs pasted into intake text (e.g. '在用药物:没有吃药').""" + + result: dict[str, str] = {} + if not raw_text: + return result + tokens = re.split(r"[\r\n;;]+", raw_text) + for line in tokens: + # Also split inline multi-pair intake lines like '姓名: 王进花 年龄: 67 患病时长: 一年多' + sub_parts = re.split( + r"\s+(?=(?:姓名|年龄|性别|患者空腹血糖|空腹血糖|餐后血糖|在用药物|目前用药|降糖药|患病时长|病程|既往史|过敏史)\s*[::])", + line.strip(), + ) + for seg in sub_parts: + if ":" in seg or ":" in seg: + k, v = re.split(r"[::]", seg, maxsplit=1) + ck, cv = k.strip(), v.strip() + if ck and cv and cv not in {"—", "-", "无记录"}: + result[ck] = cv + return result + + @dataclass(frozen=True) class ProgressionPoint: label: str @@ -82,6 +128,7 @@ class ProgressionPoint: highlight: bool = False alert: bool = False value_hint: str = "" + value_text: str = "" @dataclass(frozen=True) @@ -106,6 +153,7 @@ class DiurnalSlot: height_ratio: float state: str # "empty" | "normal" | "mint" | "alert" tooltip: str = "" + value_text: str = "" @dataclass(frozen=True) @@ -116,6 +164,8 @@ class VitalMiniBrick: unit: str tooltip: str = "" alert: bool = False + date_label: str = "" + field_key: str = "" @dataclass(frozen=True) @@ -134,6 +184,7 @@ class DiurnalStabilityVM: overnight_peak_hint: str slots: tuple[DiurnalSlot, ...] vitals: tuple[VitalMiniBrick, ...] + missing_hint: str = "" @dataclass(frozen=True) @@ -251,30 +302,21 @@ def _build_empty_snapshot(active_ai_model: str = "qwen") -> CockpitSnapshotVM: model_label = MODEL_LABELS.get(active_ai_model, "千问") today = date.today() - start_21 = today - timedelta(days=20) - empty_bars = tuple( - ProgressionPoint(label=f"#{i + 1}", ratio=0.18, recorded=False, value_hint="尚未选择患者") - for i in range(12) - ) - empty_slots = tuple( - DiurnalSlot( - time_label=(today - timedelta(days=13 - i)).strftime("%m-%d"), - height_ratio=0.18, - state="empty", - tooltip="尚未选择患者", - ) - for i in range(14) - ) + start_14 = today - timedelta(days=13) + empty_bars: tuple[ProgressionPoint, ...] = () + empty_slots: tuple[DiurnalSlot, ...] = () empty_days = tuple( JourneyDayCell( day_num=i + 1, - date_iso=(start_21 + timedelta(days=i)).isoformat(), - label_text=str((start_21 + timedelta(days=i)).day), - state="today" if i == 20 else "planned", - tooltip=f"{(start_21 + timedelta(days=i)).isoformat()} · 请先选择患者", + date_iso=(start_14 + timedelta(days=i)).isoformat(), + label_text=f"{(start_14 + timedelta(days=i)).month}/{(start_14 + timedelta(days=i)).day}" + if (start_14 + timedelta(days=i)).day == 1 + else str((start_14 + timedelta(days=i)).day), + state="today" if i == 13 else "planned", + tooltip=f"{(start_14 + timedelta(days=i)).isoformat()} · 请先选择患者", has_dot=False, ) - for i in range(21) + for i in range(14) ) empty_twin = SyndromeTwinVM( has_patient=False, @@ -318,30 +360,26 @@ def _build_empty_snapshot(active_ai_model: str = "qwen") -> CockpitSnapshotVM: overnight_title="近 14 天日常健康打卡记录", overnight_peak_hint="暂无患者数据", slots=empty_slots, - vitals=( - VitalMiniBrick("activity", "血压 (高压/低压)", "—", "mmHg"), - VitalMiniBrick("patients", "身高体重 / BMI", "—", ""), - VitalMiniBrick("prescriptions", "现用西药 / 胰岛素", "—", ""), - ), + vitals=(), + missing_hint="从右侧队列选择患者后展示实测指标与日期", ), twin_sanjiao=empty_twin, twin_organ=SyndromeTwinVM(**{**empty_twin.__dict__, "mode_key": "organ"}), twin_tcm=SyndromeTwinVM(**{**empty_twin.__dict__, "mode_key": "tcm"}), journey=CareJourneyVM( - title="近 21 天健康打卡与复诊", + title="近 14 天健康打卡与复诊", plan_subtitle="关联小程序自录血糖、饮食、运动与复诊药尽提醒", primary_metric_text="—", - total_unit_text="/ 21 天有记录", + total_unit_text="/ 14 天有记录", status_pill="待选患者", status_tone="neutral", end_capsule_text="复诊待查", phases=( - JourneyPhaseSpan("W1", "前第 3 周", f"{start_21.strftime('%m-%d')}起", 1, 7, False), - JourneyPhaseSpan("W2", "前第 2 周", f"{(start_21 + timedelta(days=7)).strftime('%m-%d')}起", 8, 14, False), - JourneyPhaseSpan("W3", "最近 7 天", f"{(start_21 + timedelta(days=14)).strftime('%m-%d')}–今日", 15, 21, True), + JourneyPhaseSpan("W1", "上周基线", f"{start_14.strftime('%m-%d')}起", 1, 7, False), + JourneyPhaseSpan("W2", "本周窗口", f"{(start_14 + timedelta(days=7)).strftime('%m-%d')}–今日", 8, 14, True), ), days=empty_days, - milestones=((1, start_21.strftime("%m-%d")), (11, (start_21 + timedelta(days=10)).strftime("%m-%d")), (21, "今日")), + milestones=((1, start_14.strftime("%m-%d")), (8, (start_14 + timedelta(days=7)).strftime("%m-%d")), (14, "今日")), ), aurora=ObsidianAuroraVM( has_patient=False, @@ -462,55 +500,69 @@ def derive_cockpit_snapshot( sorted_blood = sorted(blood_rows, key=_rec_sort_key) - # ── 1. Left Top Card: REAL Fasting Blood Glucose (mmol/L) ──────────── + # ── 1. Left Top Card: REAL Fasting Blood Glucose (mmol/L) — ONLY Real Points + Dates ── + intake_blob = "\n".join( + p + for p in ( + _clean_text(first_value(diag, "chief_complaint", "complaint", "symptoms")), + _clean_text(first_value(diag, "present_illness", "present_illness_history")), + _clean_text(first_value(appt, "chief_complaint", "symptoms")), + ) + if p + ) + intake_kv = _extract_intake_kv(intake_blob) + + diag_date_str = ( + _clean_date_iso(first_value(diag, "diagnosis_date")) + or _clean_date_iso(first_value(appt, "appointment_date", "latest_appointment_date")) + or _clean_date_iso(first_value(diag, "create_time", "update_time")) + or _clean_date_iso(first_value(appt, "create_time")) + ) + base_date_short = diag_date_str[5:] if len(diag_date_str) >= 10 else "建档" + fasting_points: list[tuple[str, float, str]] = [] diag_fasting_raw = first_value(diag, "fasting_blood_sugar", "fasting_glucose", default=None) + if diag_fasting_raw in (None, "", 0, "0"): + kv_f = intake_kv.get("患者空腹血糖") or intake_kv.get("空腹血糖") or "" + if kv_f: + m_num = re.search(r"(\d+(?:\.\d+)?)", kv_f) + diag_fasting_raw = m_num.group(1) if m_num else kv_f diag_fasting_num = _parse_positive_float(diag_fasting_raw) diag_fasting_text = _clean_text(diag_fasting_raw) - diag_date_str = _clean_text( - first_value(diag, "diagnosis_date", default=first_value(appt, "appointment_date", default="")) - )[:10] for row in sorted_blood: f_num = _parse_positive_float(first_value(row, "fasting_blood_sugar", "fasting_glucose", default=None)) if f_num is not None: - r_date = str(first_value(row, "record_date", "date", default="") or "")[:10] + r_date = _clean_date_iso(first_value(row, "record_date", "date", "create_time")) r_time = str(first_value(row, "record_time", default="") or "")[:5] src_tag = "患者自录" if str(first_value(row, "source", default="0")) == "1" else "随访录入" - label_short = r_date[5:] if len(r_date) >= 10 else "记录" - tip = f"{r_date} {r_time} · 空腹血糖 {f_num:g} mmol/L({src_tag})".strip() + label_short = r_date[5:] if len(r_date) >= 10 else base_date_short + tip = f"{r_date or base_date_short} {r_time} · 空腹血糖 {f_num:g} mmol/L({src_tag})".strip() fasting_points.append((label_short, f_num, tip)) - if not fasting_points and diag_fasting_num is not None: - lbl = diag_date_str[5:] if len(diag_date_str) >= 10 else "建档" - fasting_points.append((lbl, diag_fasting_num, f"病历建档空腹血糖:{diag_fasting_num:g} mmol/L")) + if diag_fasting_num is not None: + lbl = base_date_short + tip_base = f"{diag_date_str or '建档'} · 病历建档空腹血糖:{diag_fasting_num:g} mmol/L" + if not fasting_points: + fasting_points.append((lbl, diag_fasting_num, tip_base)) + elif fasting_points[0][0] != lbl and abs(fasting_points[0][1] - diag_fasting_num) > 0.05: + fasting_points.insert(0, (f"{lbl}建档" if len(lbl) <= 5 else lbl, diag_fasting_num, tip_base)) - # Build 12-slot chart: ONLY real points are filled; unrecorded slots stay empty! - recent_fasting = fasting_points[-12:] - scale_max = max([14.0, *(pt[1] * 1.12 for pt in recent_fasting)]) + # ONLY real recorded measurements — ZERO empty gray placeholder bars! + recent_fasting = fasting_points[-8:] + scale_max = max([14.0, *(pt[1] * 1.15 for pt in recent_fasting)]) bars: list[ProgressionPoint] = [] - pad_empty = 12 - len(recent_fasting) - for idx in range(pad_empty): - bars.append( - ProgressionPoint( - label="", - ratio=0.14, - recorded=False, - highlight=False, - alert=False, - value_hint="无更早空腹血糖打卡记录", - ) - ) for idx, (lbl, val, tip) in enumerate(recent_fasting): is_latest = idx == len(recent_fasting) - 1 bars.append( ProgressionPoint( - label=lbl, - ratio=max(0.18, min(0.96, val / scale_max)), + label=lbl or "建档", + ratio=max(0.20, min(0.92, val / scale_max)), recorded=True, highlight=is_latest, alert=(val >= 7.0), value_hint=tip, + value_text=f"{val:g}", ) ) @@ -525,18 +577,18 @@ def derive_cockpit_snapshot( first_f = recent_fasting[0][1] diff = latest_f - first_f sign = "+" if diff > 0 else "" - f_caption = f"共 {len(fasting_points)} 次 · 较首测 {sign}{diff:.1f}" + f_caption = f"共 {len(fasting_points)} 次实测 · 较首测 {sign}{diff:.1f}" else: - f_caption = "病历实测基线值" - left_foot = recent_fasting[0][0] or "首测" - right_foot = f"最新 ({recent_fasting[-1][0]})" + f_caption = f"{recent_fasting[0][0]} 建档实测" + left_foot = f"首测 {recent_fasting[0][0]}" + right_foot = f"最新 {recent_fasting[-1][0]}" elif diag_fasting_text: f_primary = "有描述" f_unit = "" f_badge = "文本记录" f_tone = "neutral" f_caption = _clip(diag_fasting_text, 14) - left_foot = "无数值打卡" + left_foot = base_date_short right_foot = "见病历描述" else: f_primary = "未记录" @@ -544,8 +596,8 @@ def derive_cockpit_snapshot( f_badge = "待补录" f_tone = "neutral" f_caption = "暂无空腹血糖数值" - left_foot = "近21天无记录" - right_foot = "可在日常记录新增" + left_foot = "暂无实测日期" + right_foot = "点击进入日常记录新增 ↗" hba1c_num = _parse_positive_float(first_value(diag, "hba1c", "glycosylated_hemoglobin", default=None)) top_sub_badge = f"糖化 {hba1c_num:g}%" if hba1c_num is not None else "参考 < 7.0 mmol/L" @@ -559,41 +611,49 @@ def derive_cockpit_snapshot( delta_tone=f_tone, delta_caption=f_caption, target_label="7.0 mmol/L 控制线", - target_ratio=min(0.88, 7.0 / scale_max), + target_ratio=min(0.84, 7.0 / scale_max), bars=tuple(bars), left_foot=left_foot, right_foot=right_foot, ) - # ── 2. Left Bottom Card: REAL Postprandial 2h Glucose & Vitals ─────── + # ── 2. Left Bottom Card: REAL Postprandial 2h Glucose & Dated Clinical Vitals ── post_points: list[tuple[str, float, str]] = [] other_points: list[tuple[str, float, str]] = [] latest_bp_from_blood = "" + latest_bp_date = "" + latest_bp_alert = False latest_west_med = "" + latest_med_date = "" latest_insulin = "" for row in sorted_blood: - r_date = str(first_value(row, "record_date", "date", default="") or "")[:10] + r_date = _clean_date_iso(first_value(row, "record_date", "date", "create_time")) + d_disp = r_date[5:] if len(r_date) >= 10 else base_date_short p_num = _parse_positive_float(first_value(row, "postprandial_blood_sugar", "postprandial_glucose", default=None)) if p_num is not None: - post_points.append((r_date, p_num, f"{r_date} · 餐后2h血糖 {p_num:g} mmol/L")) + post_points.append((d_disp, p_num, f"{r_date or d_disp} · 餐后2h血糖 {p_num:g} mmol/L")) o_num = _parse_positive_float(first_value(row, "other_blood_sugar", default=None)) if o_num is not None: - other_points.append((r_date, o_num, f"{r_date} · 随机/其他血糖 {o_num:g} mmol/L")) + other_points.append((d_disp, o_num, f"{r_date or d_disp} · 随机/其他血糖 {o_num:g} mmol/L")) sp = _parse_positive_float(first_value(row, "systolic_pressure", default=None)) dp = _parse_positive_float(first_value(row, "diastolic_pressure", default=None)) if sp is not None and dp is not None: latest_bp_from_blood = f"{int(sp)}/{int(dp)}" + latest_bp_date = d_disp + latest_bp_alert = sp >= 140 or dp >= 90 wm = _clean_text(first_value(row, "western_medicine", default="")) if wm: latest_west_med = wm + latest_med_date = d_disp ins = _clean_text(first_value(row, "insulin", default="")) if ins: latest_insulin = ins + latest_med_date = d_disp diag_post_num = _parse_positive_float(first_value(diag, "postprandial_blood_sugar", default=None)) if not post_points and diag_post_num is not None: - post_points.append((diag_date_str, diag_post_num, f"病历建档餐后血糖 {diag_post_num:g} mmol/L")) + post_points.append((base_date_short, diag_post_num, f"{diag_date_str or '建档'} · 病历建档餐后血糖 {diag_post_num:g} mmol/L")) if post_points: latest_p = post_points[-1][1] @@ -601,69 +661,73 @@ def derive_cockpit_snapshot( p_unit = "mmol/L" p_high = latest_p >= 11.1 p_badge = "餐后偏高 ↑" if p_high else "餐后达标" - p_caption = f"最近实测 ({post_points[-1][0][5:] or '建档'}) · 共 {len(post_points)} 次" + p_caption = f"最近实测 ({post_points[-1][0]}) · 共 {len(post_points)} 次" has_p_marker = True p_marker_ratio = max(0.06, min(0.95, (latest_p - 4.4) / (13.0 - 4.4))) elif other_points: latest_o = other_points[-1][1] p_primary = f"{latest_o:g}" p_unit = "mmol/L" - p_badge = "其他时段血糖" - p_caption = f"最近随机血糖 ({other_points[-1][0][5:]}) · 未测餐后2h" + p_badge = "随机血糖" + p_caption = f"最近实测 ({other_points[-1][0]}) · 未测餐后2h" has_p_marker = True p_marker_ratio = max(0.06, min(0.95, (latest_o - 4.4) / (13.0 - 4.4))) else: p_primary = "未记录" p_unit = "" p_badge = "参考 < 11.1" - p_caption = "暂无餐后2h血糖记录" + p_caption = "暂无餐后2h血糖实测" has_p_marker = False p_marker_ratio = 0.0 - # Build Real 14-Day Daily Check-in Strip (blood / diet / exercise / tracking) + # Build Real Check-in Records: ONLY dates that actually have recorded data! today = date.today() blood_by_date: dict[str, list[Any]] = {} for r in sorted_blood: - k = str(first_value(r, "record_date", "date", default="") or "")[:10] + k = _clean_date_iso(first_value(r, "record_date", "date", "create_time")) if k: blood_by_date.setdefault(k, []).append(r) diet_dates = { - str(first_value(r, "record_date", "date", default="") or "")[:10] + k for r in diet_rows - if any(_clean_text(first_value(r, m, f"{m}_foods", default="")) for m in ("breakfast", "lunch", "dinner")) + if (k := _clean_date_iso(first_value(r, "record_date", "date", "create_time"))) + and any(_clean_text(first_value(r, m, f"{m}_foods", default="")) for m in ("breakfast", "lunch", "dinner")) } exercise_by_date: dict[str, str] = {} for r in exercise_rows: - k = str(first_value(r, "record_date", "date", default="") or "")[:10] + k = _clean_date_iso(first_value(r, "record_date", "date", "create_time")) ex_t = _clean_text(first_value(r, "exercise_type", default="")) dur = first_value(r, "duration", default=None) if k and (ex_t or dur): exercise_by_date[k] = f"{ex_t} {dur}分钟".strip() if dur else (ex_t or "已运动") note_by_date: dict[str, str] = {} for n in tracking_notes or (): - k = str(first_value(n, "note_date", "record_date", "create_time", default="") or "")[:10] + k = _clean_date_iso(first_value(n, "note_date", "record_date", "create_time")) c = _clean_text(first_value(n, "content", "tracking_content", default="")) if k and c: note_by_date[k] = c - slots_14: list[DiurnalSlot] = [] - high_days_14 = 0 - recorded_days_14 = 0 - for i in range(14): - d_obj = today - timedelta(days=13 - i) - d_iso = d_obj.isoformat() + all_active_dates = sorted( + set(blood_by_date.keys()) | diet_dates | set(exercise_by_date.keys()) | set(note_by_date.keys()) + ) + recorded_slots: list[DiurnalSlot] = [] + high_days_count = 0 + for d_iso in all_active_dates[-7:]: b_list = blood_by_date.get(d_iso, []) f_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "fasting_blood_sugar", default=None))) is not None] p_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "postprandial_blood_sugar", default=None))) is not None] + o_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "other_blood_sugar", default=None))) is not None] has_diet = d_iso in diet_dates ex_txt = exercise_by_date.get(d_iso, "") tr_txt = note_by_date.get(d_iso, "") tip_parts = [d_iso] - if f_vals: - tip_parts.append(f"空腹 {f_vals[-1]:g}") if p_vals: tip_parts.append(f"餐后 {p_vals[-1]:g}") + if f_vals: + tip_parts.append(f"空腹 {f_vals[-1]:g}") + if o_vals: + tip_parts.append(f"随机 {o_vals[-1]:g}") if has_diet: tip_parts.append("已记饮食") if ex_txt: @@ -673,44 +737,57 @@ def derive_cockpit_snapshot( max_f = max(f_vals, default=0.0) max_p = max(p_vals, default=0.0) + val_tag = ( + f"{p_vals[-1]:g}" + if p_vals + else f"{f_vals[-1]:g}" + if f_vals + else f"{o_vals[-1]:g}" + if o_vals + else "运动" + if ex_txt + else "饮食" + if has_diet + else "随访" + ) if max_f >= 7.0 or max_p >= 11.1: - high_days_14 += 1 - recorded_days_14 += 1 + high_days_count += 1 peak_ratio = max(max_f / 14.0, max_p / 18.0) - slots_14.append( - DiurnalSlot(d_iso[5:], max(0.55, min(1.0, peak_ratio)), "alert", " · ".join(tip_parts)) + recorded_slots.append( + DiurnalSlot(d_iso[5:], max(0.54, min(0.96, peak_ratio)), "alert", " · ".join(tip_parts), val_tag) ) - elif f_vals or p_vals: - recorded_days_14 += 1 - norm_ratio = max(max_f / 14.0, max_p / 18.0, 0.48) - slots_14.append( - DiurnalSlot(d_iso[5:], min(0.85, norm_ratio), "mint", " · ".join(tip_parts)) + elif p_vals or f_vals or o_vals: + norm_ratio = max(max_f / 14.0, max_p / 18.0, 0.46) + recorded_slots.append( + DiurnalSlot(d_iso[5:], min(0.86, norm_ratio), "mint", " · ".join(tip_parts), val_tag) ) - elif has_diet or ex_txt or tr_txt: - recorded_days_14 += 1 - slots_14.append(DiurnalSlot(d_iso[5:], 0.42, "normal", " · ".join(tip_parts))) else: - slots_14.append(DiurnalSlot(d_iso[5:], 0.16, "empty", f"{d_iso} · 当日无打卡记录")) + recorded_slots.append( + DiurnalSlot(d_iso[5:], 0.44, "normal", " · ".join(tip_parts), val_tag) + ) - # Real Vitals (BP, Height/Weight/BMI, Current Meds) + # Real Vitals & Clinical Facts: ONLY show items that actually have data + date underneath! sys_num = _parse_positive_float( first_value(diag, "systolic_pressure", "systolic", "high_pressure", default=first_value(pat, "systolic_pressure", default=None)) ) dia_num = _parse_positive_float( first_value(diag, "diastolic_pressure", "diastolic", "low_pressure", default=first_value(pat, "diastolic_pressure", default=None)) ) - if sys_num is not None and dia_num is not None: - bp_val = f"{int(sys_num)}/{int(dia_num)}" - bp_unit = "mmHg" - bp_alert = sys_num >= 140 or dia_num >= 90 - elif latest_bp_from_blood: + if latest_bp_from_blood: bp_val = latest_bp_from_blood bp_unit = "mmHg" - bp_alert = False + bp_date = f"{latest_bp_date} 实测" + bp_alert = latest_bp_alert + elif sys_num is not None and dia_num is not None: + bp_val = f"{int(sys_num)}/{int(dia_num)}" + bp_unit = "mmHg" + bp_date = f"{base_date_short} 建档" + bp_alert = sys_num >= 140 or dia_num >= 90 else: raw_bp = _clean_text(first_value(diag, "blood_pressure", default="")) bp_val = raw_bp if raw_bp else "—" bp_unit = "mmHg" if raw_bp and "mmhg" not in raw_bp.lower() else "" + bp_date = f"{base_date_short} 建档" bp_alert = False h_num = _parse_positive_float(first_value(diag, "height", default=first_value(pat, "height", default=None))) @@ -719,12 +796,12 @@ def derive_cockpit_snapshot( bmi = w_num / ((h_num / 100.0) ** 2) hw_val = f"{bmi:.1f}" hw_unit = f"BMI ({int(w_num)}kg)" - hw_tip = f"身高 {h_num:g} cm · 体重 {w_num:g} kg · BMI {bmi:.1f}" + hw_tip = f"{diag_date_str or '建档'} · 身高 {h_num:g} cm · 体重 {w_num:g} kg · BMI {bmi:.1f}" hw_alert = bmi >= 24.0 or bmi < 18.5 elif w_num: hw_val = f"{w_num:g}" hw_unit = "kg" - hw_tip = f"体重 {w_num:g} kg(身高未填)" + hw_tip = f"{diag_date_str or '建档'} · 体重 {w_num:g} kg(身高未填)" hw_alert = False else: hw_val = "—" @@ -738,10 +815,127 @@ def derive_cockpit_snapshot( "current_medications", "current_medicine", "current_medication", - default=latest_insulin or latest_west_med, + default=latest_insulin + or latest_west_med + or intake_kv.get("在用药物") + or intake_kv.get("目前用药") + or intake_kv.get("降糖药") + or "", ) ) - meds_short = _clip(meds_full, 7) if meds_full else "—" + meds_date = f"{latest_med_date} 随访" if latest_med_date else f"{base_date_short} 问诊" + course_early = _clean_text( + first_value( + diag, + "disease_course_text", + "diabetes_discovery_year_text", + "diabetes_discovery_year", + "diabetes_history_text", + default=intake_kv.get("患病时长") or intake_kv.get("病程") or "", + ) + ) + + real_vitals: list[VitalMiniBrick] = [] + missing_vitals: list[str] = [] + if p_primary == "未记录": + missing_vitals.append("餐后血糖") + if bp_val != "—": + real_vitals.append( + VitalMiniBrick( + "activity", + "实测血压", + bp_val, + bp_unit, + f"{bp_date} · 血压 {bp_val} {bp_unit}".strip(), + bp_alert, + date_label=bp_date, + field_key="systolic_pressure", + ) + ) + else: + missing_vitals.append("血压") + + if hw_val != "—": + real_vitals.append( + VitalMiniBrick( + "patients", + "体质量 BMI", + hw_val, + hw_unit, + hw_tip, + hw_alert, + date_label=f"{base_date_short} 建档", + field_key="weight", + ) + ) + else: + missing_vitals.append("身高体重") + + if meds_full: + real_vitals.append( + VitalMiniBrick( + "prescriptions", + "在用降糖药", + _clip(meds_full, 10), + "", + f"{meds_date} · {meds_full}", + False, + date_label=meds_date, + field_key="current_medications", + ) + ) + else: + missing_vitals.append("在用药物") + + # Surface additional real recorded clinical indicators when core vitals are sparse + if len(real_vitals) < 3 and course_early: + real_vitals.append( + VitalMiniBrick( + "consultations", + "患病病程", + _clip(course_early, 10), + "", + f"{base_date_short} 建档 · 病程:{course_early}", + False, + date_label=f"{base_date_short} 建档", + field_key="diabetes_discovery_year", + ) + ) + if len(real_vitals) < 3 and diag_fasting_num is not None and p_primary == "未记录": + real_vitals.append( + VitalMiniBrick( + "activity", + "空腹血糖基线", + f"{diag_fasting_num:g}", + "mmol/L", + f"{base_date_short} 建档 · 空腹血糖 {diag_fasting_num:g} mmol/L", + diag_fasting_num >= 7.0, + date_label=f"{base_date_short} 建档", + field_key="fasting_blood_sugar", + ) + ) + age_disp = _clean_text(first_value(diag, "age", default=first_value(pat, "age", default=first_value(appt, "age", default=intake_kv.get("年龄", ""))))) + visit_disp = _clean_text(first_value(diag, "diagnosis_type_text", default=first_value(appt, "diagnosis_type_text", "status_desc", default=""))) + if len(real_vitals) < 3 and (age_disp or visit_disp): + demo_v = " · ".join(p for p in (f"{age_disp}岁" if age_disp and not age_disp.endswith("岁") else age_disp, visit_disp) if p) + real_vitals.append( + VitalMiniBrick( + "patients", + "接诊档案", + _clip(demo_v, 10), + "", + f"{base_date_short} · {demo_v}", + False, + date_label=f"{base_date_short} 挂号", + field_key="age", + ) + ) + + missing_hint_txt = ( + f"待补采:{'、'.join(missing_vitals[:3])} · 点击补录 ↗" + if missing_vitals + else "" + ) diurnal_vm = DiurnalStabilityVM( title="餐后2h血糖与体征", @@ -754,18 +948,15 @@ def derive_cockpit_snapshot( range_min_text="4.4", range_target_text="7.8 餐后参考", range_max_text="11.1", - overnight_title="近 14 天日常打卡轨迹", + overnight_title="实测日常打卡记录", overnight_peak_hint=( - f"偏高 {high_days_14} 天 / 已记 {recorded_days_14} 天" - if recorded_days_14 > 0 - else "近 14 天暂无打卡记录" - ), - slots=tuple(slots_14), - vitals=( - VitalMiniBrick("activity", "血压 (高压/低压)", bp_val, bp_unit, f"实测血压:{bp_val} {bp_unit}".strip(), bp_alert), - VitalMiniBrick("patients", "体质量 BMI", hw_val, hw_unit, hw_tip, hw_alert), - VitalMiniBrick("prescriptions", "在用降糖药", meds_short, "", meds_full or "暂未录入在用药物", False), + f"共 {len(all_active_dates)} 天有记录 · 偏高 {high_days_count} 天" + if recorded_slots + else "暂无日常打卡记录" ), + slots=tuple(recorded_slots), + vitals=tuple(real_vitals[:4]), + missing_hint=missing_hint_txt, ) # ── 3. Center Stage: 100% Real Body Symptom & Clinical Case Map ────── @@ -801,7 +992,6 @@ def derive_cockpit_snapshot( if not present: return ("未采集", "neutral", "病历暂未填写该部位问诊项", 0.0) abnormal = [(lbl, val) for lbl, val in present if not _is_normal_or_negated(val)] - full = ";".join(f"{lbl}:{val}" for lbl, val in present) if abnormal: ab_line = " · ".join(f"{lbl}:{val}" for lbl, val in abnormal) return ("阳性体征", "coral", ab_line, 0.85) @@ -1015,15 +1205,24 @@ def derive_cockpit_snapshot( if rx_list: latest_rx = rx_list[0] - herbs = first_value(latest_rx, "herbs", default=[]) or [] + rx_title = _clean_text( + first_value(latest_rx, "prescription_name", "formula_name", "name", default="") + ) + herbs = first_value(latest_rx, "herbs", "medicines", default=[]) or [] herb_names = [ f"{_clean_text(first_value(h, 'name', 'medicine_name'))}{_clean_text(first_value(h, 'dosage', 'amount'))}g" for h in herbs[:5] if _clean_text(first_value(h, "name", "medicine_name")) ] - rx_herbs_summary = "、".join(herb_names) if herb_names else f"共 {len(herbs)} 味中药" - med_days = first_value(latest_rx, "medication_days", "usage_days", "dose_count", default="") - rx_badge = f"已开 {med_days}天" if med_days else f"共 {len(rx_list)} 张处方" + herb_part = "、".join(herb_names) if herb_names else (f"共 {len(herbs)} 味" if herbs else "") + rx_herbs_summary = ( + " · ".join(p for p in (rx_title, herb_part) if p) + or f"已开电子处方 #{first_value(latest_rx, 'id', default=1)}" + ) + med_days = first_value( + latest_rx, "medication_days", "usage_days", "dose_count", "dosage_count", default="" + ) + rx_badge = f"已开 {med_days}剂" if med_days else f"共 {len(rx_list)} 张处方" rx_tone = "emerald" elif has_rx: rx_herbs_summary = "已关联有效电子处方(可在已开处方查看明细)" @@ -1098,12 +1297,12 @@ def derive_cockpit_snapshot( recorded_Zone_flags=(z_head_heat, z_oral_heat, z_abd_heat, z_low_heat), ) - # ── 4. Bottom 21-Day Real Check-in & Revisit Due Track ─────────────── - start_21 = today - timedelta(days=20) - days_21: list[JourneyDayCell] = [] + # ── 4. Bottom 14-Day Real Check-in & Revisit Due Track ─────────────── + start_14 = today - timedelta(days=13) + days_14: list[JourneyDayCell] = [] checked_in_days = 0 - for idx in range(21): - d_obj = start_21 + timedelta(days=idx) + for idx in range(14): + d_obj = start_14 + timedelta(days=idx) d_iso = d_obj.isoformat() b_list = blood_by_date.get(d_iso, []) f_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "fasting_blood_sugar", default=None))) is not None] @@ -1142,25 +1341,29 @@ def derive_cockpit_snapshot( else: cell_state = "planned" - days_21.append( + days_14.append( JourneyDayCell( day_num=idx + 1, date_iso=d_iso, - label_text=str(d_obj.day), + label_text=f"{d_obj.month}/{d_obj.day}" if d_obj.day == 1 else str(d_obj.day), state=cell_state, tooltip="\n".join(tip_lines), - has_dot=is_high_day, + has_dot=is_high_day or (d_obj == today and has_any), ) ) # Parse `revisit_due` (Contract C from `RevisitNodeCell.vue`) if present revisit_due = first_value(diag, "revisit_due", default=first_value(appt, "revisit_due", default=None)) - if isinstance(revisit_due, Mapping) and str(revisit_due.get("state") or "none") not in {"none", ""}: - slot_n = int(revisit_due.get("current_slot") or 0) - med_d = int(revisit_due.get("medication_days") or 0) - due_dt = _clean_text(revisit_due.get("due_date")) - st_txt = _clean_text(revisit_due.get("state_text")) or "复诊跟踪中" - st_code = str(revisit_due.get("state") or "") + st_code = ( + str(first_value(revisit_due, "state", "status", default="none") or "none") + if isinstance(revisit_due, Mapping) + else "none" + ) + if isinstance(revisit_due, Mapping) and st_code not in {"none", ""}: + slot_n = int(first_value(revisit_due, "current_slot", "visit_count", default=0) or 0) + med_d = int(first_value(revisit_due, "medication_days", default=0) or 0) + due_dt = _clean_text(first_value(revisit_due, "due_date", "medication_end_date", default="")) + st_txt = _clean_text(first_value(revisit_due, "state_text", "status_text", default="")) or "复诊跟踪中" j_sub = " · ".join( p for p in (f"第 {slot_n} 诊" if slot_n > 0 else "", f"开药 {med_d} 天" if med_d > 0 else "", f"药尽 {due_dt[5:]}" if len(due_dt) >= 10 else "") if p ) or "复诊用药周期跟踪" @@ -1168,51 +1371,42 @@ def derive_cockpit_snapshot( j_tone = "coral" if st_code in {"overdue", "missed", "warning", "no_days"} else "emerald" end_cap = f"药尽 {due_dt[5:]}" if len(due_dt) >= 10 else st_txt[:4] else: - j_sub = f"{start_21.strftime('%m-%d')} 至 {today.strftime('%m-%d')} 血糖·饮食·运动实录" + j_sub = f"{start_14.strftime('%m-%d')} 至 {today.strftime('%m-%d')} 血糖·饮食·运动实录" j_pill = rx_status_str j_tone = "emerald" if has_rx else "neutral" end_cap = "已开方" if has_rx else "待开方" journey_vm = CareJourneyVM( - title="近 21 天健康打卡与复诊", + title="近 14 天健康打卡与复诊", plan_subtitle=j_sub, primary_metric_text=f"{checked_in_days}", - total_unit_text="/ 21 天有打卡", + total_unit_text="/ 14 天有打卡", status_pill=j_pill, status_tone=j_tone, end_capsule_text=end_cap, phases=( JourneyPhaseSpan( - "第1周", - "早期基线周", - f"{start_21.strftime('%m-%d')}–{(start_21 + timedelta(days=6)).strftime('%m-%d')}", + "上周", + "前7天基线", + f"{start_14.strftime('%m-%d')}–{(start_14 + timedelta(days=6)).strftime('%m-%d')}", 1, 7, False, ), JourneyPhaseSpan( - "第2周", - "中期观察周", - f"{(start_21 + timedelta(days=7)).strftime('%m-%d')}–{(start_21 + timedelta(days=13)).strftime('%m-%d')}", + "本周", + "近7天窗口", + f"{(start_14 + timedelta(days=7)).strftime('%m-%d')}–{today.strftime('%m-%d')}", 8, 14, - False, - ), - JourneyPhaseSpan( - "近7天", - "本周实测窗口", - f"{(start_21 + timedelta(days=14)).strftime('%m-%d')}–{today.strftime('%m-%d')}", - 15, - 21, True, ), ), - days=tuple(days_21), + days=tuple(days_14), milestones=( - (1, start_21.strftime("%m-%d")), - (8, (start_21 + timedelta(days=7)).strftime("%m-%d")), - (15, (start_21 + timedelta(days=14)).strftime("%m-%d")), - (21, "今日"), + (1, start_14.strftime("%m-%d")), + (8, (start_14 + timedelta(days=7)).strftime("%m-%d")), + (14, "今日"), ), ) diff --git a/app/src/doctor_workstation/ui/visuals/ai_report_wing.py b/app/src/doctor_workstation/ui/visuals/ai_report_wing.py new file mode 100644 index 000000000..5d9b65a57 --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/ai_report_wing.py @@ -0,0 +1,880 @@ +"""High-density Clinical AI Report Companion Wing Panel (Clinical OS 4.0). + +Replaces the legacy wide center-blocking `_ReceptionAiAnalysisDialog` in Spatial mode +with a scannable, 520px-optimized clinical evidence companion wing featuring: +- Segmented model pills (`千问` / `OpenAI` / `豆包`) + compact snapshot version selector +- Auto-extracted 3-brick Syndrome / Eight-Principles / Visceral-Locus key takeaways +- 2-column clinical risk stratification grid (zero wasted horizontal whitespace) +- Tagged Four-Examination (`望 / 闻 / 问 / 切`) evidence rows +- Prominent Treatment & Regimen card + non-intrusive inline copy feedback +""" + +from __future__ import annotations + +import html +import re +from collections.abc import Mapping, Sequence +from typing import Any + +from PySide6.QtCore import QSize, Qt, QTimer, Signal +from PySide6.QtGui import QIcon +from PySide6.QtWidgets import ( + QApplication, + QComboBox, + QFrame, + QGridLayout, + QHBoxLayout, + QLabel, + QPushButton, + QScrollArea, + QStackedWidget, + QVBoxLayout, + QWidget, +) + +from .. import icons +from ..reception_style import body_family, heading_family +from ..report_provenance import report_provenance_lines +from ..widgets import clear_layout, display_text, first_value + +AI_MODELS: tuple[tuple[str, str], ...] = ( + ("qwen", "千问"), + ("openai", "OpenAI"), + ("doubao", "豆包"), +) +MODEL_LABELS = dict(AI_MODELS) + +AI_REPORT_WING_QSS = """ +QWidget#ClinicalAiReportWingPanel { + background-color: #FFFFFF; +} +QFrame#AiWingTopBar { + background-color: #F7FAF9; + border: 0; + border-bottom: 1px solid #E4EDE9; +} +QFrame#AiWingModelIsland { + background-color: #EAF1EF; + border-radius: 15px; +} +QPushButton#AiWingModelPill { + min-height: 26px; + max-height: 26px; + padding: 0 13px; + border-radius: 13px; + border: 0; + background-color: transparent; + color: #4F6662; + font-size: 12px; + font-weight: 600; +} +QPushButton#AiWingModelPill:hover { + color: #0E6F5C; +} +QPushButton#AiWingModelPill:checked { + background-color: #111918; + color: #FFFFFF; +} +QComboBox#AiWingVersionCombo { + min-height: 28px; + max-height: 28px; + padding: 0 10px; + border-radius: 14px; + border: 1px solid #D8E5E1; + background-color: #FFFFFF; + color: #263C39; + font-size: 11px; + font-weight: 500; +} +QFrame#AiWingTakeawayTile { + background-color: #F5F9F8; + border: 1px solid #E1ECE8; + border-radius: 14px; +} +QFrame#AiWingTakeawayTile[emphasis="true"] { + background-color: #EAF6F2; + border: 1px solid #C3E3D8; +} +QFrame#AiWingCard { + background-color: #FFFFFF; + border: 1px solid #E2ECE9; + border-radius: 16px; +} +QFrame#AiWingTreatmentCard { + background-color: #F6FBF9; + border: 1px solid #CBE5DC; + border-radius: 16px; +} +QFrame#AiWingBottomBar { + background-color: #F7FAF9; + border: 0; + border-top: 1px solid #E3ECE9; + border-bottom-left-radius: 20px; + border-bottom-right-radius: 20px; +} +QPushButton#AiWingGhostBtn { + min-height: 34px; + max-height: 34px; + padding: 0 14px; + border-radius: 17px; + border: 1px solid #D7E5E1; + background-color: #FFFFFF; + color: #1C322F; + font-size: 12px; + font-weight: 600; +} +QPushButton#AiWingGhostBtn:hover { + background-color: #E7F4F0; + border-color: #9ED0C3; + color: #0E6F5C; +} +QPushButton#AiWingGhostBtn:disabled { + color: #9CB0AC; + background-color: #F4F7F6; +} +QPushButton#AiWingPrimaryBtn { + min-height: 34px; + max-height: 34px; + padding: 0 16px; + border-radius: 17px; + border: 0; + background-color: #0E6F5C; + color: #FFFFFF; + font-size: 12px; + font-weight: 600; +} +QPushButton#AiWingPrimaryBtn:hover { + background-color: #0A5949; +} +""" + +_TAG_PATTERNS: tuple[tuple[str, str, str, str], ...] = ( + ("望诊", "望诊", "#E5F3EE", "#0E6F5C"), + ("闻诊", "闻诊", "#EEF3F2", "#4E6562"), + ("问诊", "问诊", "#E8F1FA", "#1E5C96"), + ("切诊", "切诊", "#FBF4E5", "#986C1B"), + ("八纲", "八纲", "#EAF4F1", "#185E50"), + ("气血津液", "病位病机", "#F4F0E7", "#7E5D20"), + ("脏腑定位", "脏腑病位", "#F4F0E7", "#7E5D20"), + ("证名", "辨证结论", "#DEF2EC", "#0B5E4E"), + ("已知事实", "已知事实", "#E8F1FA", "#1E5C96"), + ("合理推断", "临床推断", "#E5F3EE", "#0E6F5C"), + ("临床推断", "临床推断", "#E5F3EE", "#0E6F5C"), + ("信息缺口", "待补信息", "#FBF4E5", "#986C1B"), + ("核心病机", "核心病机", "#EAF4F1", "#185E50"), + ("辨证分析", "辨证分析", "#EEF5F3", "#2A4A45"), +) + + +def _format_prose_html(text: str, *, color: str = "#223634", size_px: int = 13, line_pct: int = 168) -> str: + """Render clinical prose with true breathing room (`line-height` via HTML since Qt QSS ignores it).""" + + chunks = [c.strip() for c in text.splitlines() if c.strip()] + if not chunks: + return "" + paragraphs: list[str] = [] + for chunk in chunks: + escaped = html.escape(chunk) + # Subtle visual anchor for numbered prefixes ("1. 治法方药:") without shouting + escaped = re.sub( + r"^(\d+[\.、]\s*[^::]{2,8}[::])", + r"\1", + escaped, + ) + paragraphs.append( + f"

{escaped}

" + ) + # Remove bottom margin on last paragraph + if paragraphs: + paragraphs[-1] = paragraphs[-1].replace("margin:0 0 6px 0;", "margin:0;") + return "".join(paragraphs) + + +def _clean_text(value: Any) -> str: + if value in (None, "", [], {}): + return "" + if isinstance(value, (list, tuple)): + parts = [_clean_text(item) for item in value] + return "\n".join(p for p in parts if p) + txt = str(value).strip() + return "" if txt in {"—", "-", "None", "null"} else txt + + +def _extract_key_takeaways(diagnosis_text: str) -> tuple[tuple[str, str], ...]: + """Extract concise (caption, value) takeaways from structured TCM AI output.""" + + syndrome = "" + eight_prin = "" + locus = "" + + for raw_line in diagnosis_text.splitlines(): + line = raw_line.strip().lstrip("•·-*0123456789.、 ") + if not line: + continue + if line.startswith("证名") and (":" in line or ":" in line): + syndrome = re.split(r"[::]", line, maxsplit=1)[1].strip() + elif line.startswith("八纲") and (":" in line or ":" in line): + eight_prin = re.split(r"[::]", line, maxsplit=1)[1].strip() + elif any(line.startswith(k) for k in ("气血津液", "脏腑定位", "病位", "病机")) and ( + ":" in line or ":" in line + ): + val = re.split(r"[::]", line, maxsplit=1)[1].strip() + m_loc = re.search(r"病位[^,。;]*[在属]([^,。;]+)", val) + locus = m_loc.group(1).strip() if m_loc else val + + def _short(text: str, limit: int = 16) -> str: + # Strip parenthetical explanations for the compact headline tile + stripped = re.sub(r"([^)]*)|\([^)]*\)", "", text).strip(" ,。;、") + base = stripped or text + return f"{base[: limit - 1]}…" if len(base) > limit else base + + items: list[tuple[str, str, str]] = [] + if syndrome: + items.append(("辨证证名", _short(syndrome, 15), syndrome)) + if eight_prin: + items.append(("八纲属性", _short(eight_prin, 15), eight_prin)) + if locus: + items.append(("病位病机", _short(locus, 15), locus)) + return tuple(items) # type: ignore[return-value] + + +def _split_evidence_rows(diagnosis_text: str) -> list[tuple[str, str, str, str]]: + """Split `diagnosis_advice` (including inline `【已知事实】` sections) into calm structured rows.""" + + rows: list[tuple[str, str, str, str]] = [] + for raw_line in diagnosis_text.splitlines(): + base = raw_line.strip().lstrip("•·-* ") + if not base: + continue + # Split inline bracketed sections like "【已知事实】...【合理推断】...【信息缺口】..." + segments = [s.strip() for s in re.split(r"(?=【[^】]{2,12}】)", base) if s.strip()] + for line in segments: + # Unwrap leading 【标签】 into prefix matching + m_bracket = re.match(r"^【([^】]{2,12})】\s*(.*)$", line) + if m_bracket: + tag_key = m_bracket.group(1).strip() + rest = m_bracket.group(2).strip() + line = f"{tag_key}:{rest}" if rest else tag_key + if line.startswith(("四诊:", "四诊:")): + line = re.split(r"[::]", line, maxsplit=1)[1].strip() + matched = False + for prefix, badge, bg, fg in _TAG_PATTERNS: + if line.startswith(prefix): + body = line[len(prefix) :].lstrip("::、 ") + if not body: + body = line + rows.append((badge, bg, fg, body)) + matched = True + break + if not matched: + rows.append(("辨证分析", "#EEF5F3", "#2A4A45", line)) + return rows + + +class ClinicalAiReportWingPanel(QWidget): + """High-density companion wing for viewing Qwen / OpenAI / Doubao patient AI reports.""" + + model_selected = Signal(str) + regenerate_requested = Signal() + open_ai_consult_requested = Signal() + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("ClinicalAiReportWingPanel") + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self.setStyleSheet(AI_REPORT_WING_QSS) + + self._histories: dict[str, list[dict[str, Any]]] = {k: [] for k, _ in AI_MODELS} + self._states: dict[str, str] = {k: "empty" for k, _ in AI_MODELS} + self._messages: dict[str, str] = {k: "" for k, _ in AI_MODELS} + self._active_model = "qwen" + self._active_version_idx = 0 + self._patient_name = "" + self._copy_reset_timer = QTimer(self) + self._copy_reset_timer.setSingleShot(True) + self._copy_reset_timer.timeout.connect(self._reset_copy_button) + + root = QVBoxLayout(self) + root.setContentsMargins(0, 0, 0, 0) + root.setSpacing(0) + + # 1. Segmented Model Pill Bar + Compact Version Selector + top_bar = QFrame(self) + top_bar.setObjectName("AiWingTopBar") + top_layout = QHBoxLayout(top_bar) + top_layout.setContentsMargins(16, 10, 16, 10) + top_layout.setSpacing(10) + + island = QFrame(top_bar) + island.setObjectName("AiWingModelIsland") + island_layout = QHBoxLayout(island) + island_layout.setContentsMargins(3, 2, 3, 2) + island_layout.setSpacing(2) + self._model_pills: dict[str, QPushButton] = {} + for m_key, m_label in AI_MODELS: + pill = QPushButton(m_label, island) + pill.setObjectName("AiWingModelPill") + pill.setCheckable(True) + pill.setCursor(Qt.CursorShape.PointingHandCursor) + pill.clicked.connect(lambda _c=False, k=m_key: self._on_model_clicked(k)) + island_layout.addWidget(pill) + self._model_pills[m_key] = pill + top_layout.addWidget(island) + + top_layout.addStretch(1) + + self.version_combo = QComboBox(top_bar) + self.version_combo.setObjectName("AiWingVersionCombo") + self.version_combo.setCursor(Qt.CursorShape.PointingHandCursor) + self.version_combo.setMinimumWidth(178) + self.version_combo.currentIndexChanged.connect(self._on_version_changed) + top_layout.addWidget(self.version_combo) + root.addWidget(top_bar) + + # 2. Content Stack (Page 0: Rich Clinical Evidence Flow | Page 1: Honest Empty/Loading State) + self.stack = QStackedWidget(self) + root.addWidget(self.stack, 1) + + # Page 0: Scrollable Evidence Cards + self.scroll = QScrollArea(self.stack) + self.scroll.setWidgetResizable(True) + self.scroll.setFrameShape(QFrame.Shape.NoFrame) + self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.scroll.setStyleSheet("QScrollArea { background: #FFFFFF; border: 0; }") + + self.body_host = QWidget(self.scroll) + self.body_host.setStyleSheet("background: #FFFFFF;") + self.body_layout = QVBoxLayout(self.body_host) + self.body_layout.setContentsMargins(16, 14, 16, 16) + self.body_layout.setSpacing(12) + + # Row A: 3-Column Syndrome Takeaways Host + self.takeaway_host = QWidget(self.body_host) + self.takeaway_layout = QHBoxLayout(self.takeaway_host) + self.takeaway_layout.setContentsMargins(0, 0, 0, 0) + self.takeaway_layout.setSpacing(8) + self.body_layout.addWidget(self.takeaway_host) + + # Row B: 2-Column Risk Stratification Card + self.risk_card = QFrame(self.body_host) + self.risk_card.setObjectName("AiWingCard") + risk_outer = QVBoxLayout(self.risk_card) + risk_outer.setContentsMargins(14, 12, 14, 12) + risk_outer.setSpacing(8) + risk_head = QHBoxLayout() + risk_head.setSpacing(6) + risk_icon = QLabel(self.risk_card) + risk_icon.setPixmap(icons.pixmap("warning", "#C94534", 15)) + risk_icon.setFixedSize(16, 16) + risk_icon.setAlignment(Qt.AlignmentFlag.AlignCenter) + risk_head.addWidget(risk_icon) + self.risk_title_lbl = QLabel("临床风险分层", self.risk_card) + self.risk_title_lbl.setStyleSheet( + f"color: #132523; font-family: '{heading_family()}'; font-size: 13px; font-weight: 600;" + ) + risk_head.addWidget(self.risk_title_lbl) + risk_head.addStretch(1) + self.risk_count_badge = QLabel("0 项", self.risk_card) + self.risk_count_badge.setStyleSheet( + "background: #FCEBE6; color: #C94534; border-radius: 9px; padding: 1px 8px; font-size: 11px; font-weight: 600;" + ) + risk_head.addWidget(self.risk_count_badge) + risk_outer.addLayout(risk_head) + + self.risk_grid_host = QWidget(self.risk_card) + self.risk_grid = QGridLayout(self.risk_grid_host) + self.risk_grid.setContentsMargins(0, 0, 0, 0) + self.risk_grid.setHorizontalSpacing(8) + self.risk_grid.setVerticalSpacing(7) + risk_outer.addWidget(self.risk_grid_host) + self.body_layout.addWidget(self.risk_card) + + # Row C: Structured Four-Examination & Syndrome Reasoning Card + self.diag_card = QFrame(self.body_host) + self.diag_card.setObjectName("AiWingCard") + diag_outer = QVBoxLayout(self.diag_card) + diag_outer.setContentsMargins(14, 12, 14, 14) + diag_outer.setSpacing(9) + diag_head = QHBoxLayout() + diag_head.setSpacing(6) + diag_icon = QLabel(self.diag_card) + diag_icon.setPixmap(icons.pixmap("report", "#0E6F5C", 15)) + diag_icon.setFixedSize(16, 16) + diag_icon.setAlignment(Qt.AlignmentFlag.AlignCenter) + diag_head.addWidget(diag_icon) + diag_title = QLabel("四诊合参依据与辨证分析", self.diag_card) + diag_title.setStyleSheet( + f"color: #132523; font-family: '{heading_family()}'; font-size: 13px; font-weight: 600;" + ) + diag_head.addWidget(diag_title) + diag_head.addStretch(1) + diag_outer.addLayout(diag_head) + self.diag_rows_host = QWidget(self.diag_card) + self.diag_rows_layout = QVBoxLayout(self.diag_rows_host) + self.diag_rows_layout.setContentsMargins(0, 0, 0, 0) + self.diag_rows_layout.setSpacing(7) + diag_outer.addWidget(self.diag_rows_host) + self.body_layout.addWidget(self.diag_card) + + # Row D: Prominent Treatment & Lifestyle Advice Card + self.treat_card = QFrame(self.body_host) + self.treat_card.setObjectName("AiWingTreatmentCard") + treat_outer = QVBoxLayout(self.treat_card) + treat_outer.setContentsMargins(14, 12, 14, 14) + treat_outer.setSpacing(8) + treat_head = QHBoxLayout() + treat_head.setSpacing(6) + treat_icon = QLabel(self.treat_card) + treat_icon.setPixmap(icons.pixmap("meds", "#0B5949", 15)) + treat_icon.setFixedSize(16, 16) + treat_icon.setAlignment(Qt.AlignmentFlag.AlignCenter) + treat_head.addWidget(treat_icon) + treat_title = QLabel("治法方药与调护建议", self.treat_card) + treat_title.setStyleSheet( + f"color: #0B5949; font-family: '{heading_family()}'; font-size: 13px; font-weight: 600;" + ) + treat_head.addWidget(treat_title) + treat_head.addStretch(1) + treat_outer.addLayout(treat_head) + self.treat_body_lbl = QLabel("—", self.treat_card) + self.treat_body_lbl.setWordWrap(True) + self.treat_body_lbl.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + self.treat_body_lbl.setStyleSheet( + f"color: #172E2B; font-family: '{body_family()}'; font-size: 13px; line-height: 1.5;" + ) + treat_outer.addWidget(self.treat_body_lbl) + self.body_layout.addWidget(self.treat_card) + + # Row E: Subtle 1-Line Provenance & Medical Disclaimer + self.provenance_lbl = QLabel( + "注:仅供临床辅助参考,不可替代医师诊断与处方决策 · 悬停查看报告出处与安全声明", + self.body_host, + ) + self.provenance_lbl.setWordWrap(True) + self.provenance_lbl.setStyleSheet("color: #7D918E; font-size: 11px; padding: 2px 2px;") + self.body_layout.addWidget(self.provenance_lbl) + self.body_layout.addStretch(1) + + self.scroll.setWidget(self.body_host) + self.stack.addWidget(self.scroll) + + # Page 1: Honest State Card (Loading / Missing Snapshot / Error) + state_page = QWidget(self.stack) + state_page.setStyleSheet("background: #FFFFFF;") + state_layout = QVBoxLayout(state_page) + state_layout.setContentsMargins(28, 48, 28, 48) + state_layout.addStretch(1) + state_card = QFrame(state_page) + state_card.setStyleSheet( + "QFrame { background: #F6FAF9; border: 1px solid #DFEBE7; border-radius: 18px; }" + ) + sc_layout = QVBoxLayout(state_card) + sc_layout.setContentsMargins(24, 26, 24, 26) + sc_layout.setSpacing(10) + self.state_title_lbl = QLabel("正在读取 AI 循证报告", state_card) + self.state_title_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.state_title_lbl.setStyleSheet( + f"color: #112220; font-family: '{heading_family()}'; font-size: 15px; font-weight: 600; border: 0;" + ) + sc_layout.addWidget(self.state_title_lbl) + self.state_desc_lbl = QLabel("请稍候或点击下方「重新生成」获取当前模型分析快照。", state_card) + self.state_desc_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.state_desc_lbl.setWordWrap(True) + self.state_desc_lbl.setStyleSheet("color: #667D79; font-size: 12px; border: 0;") + sc_layout.addWidget(self.state_desc_lbl) + state_layout.addWidget(state_card) + state_layout.addStretch(1) + self.stack.addWidget(state_page) + + # 3. Sticky Bottom Action Dock + bottom_bar = QFrame(self) + bottom_bar.setObjectName("AiWingBottomBar") + bottom_bar.setFixedHeight(56) + b_layout = QHBoxLayout(bottom_bar) + b_layout.setContentsMargins(16, 10, 16, 10) + b_layout.setSpacing(8) + + self.regen_btn = QPushButton("重新生成", bottom_bar) + self.regen_btn.setObjectName("AiWingGhostBtn") + self.regen_btn.setIcon(icons.icon("refresh", "#24423E", 14)) + self.regen_btn.setIconSize(QSize(14, 14)) + self.regen_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.regen_btn.clicked.connect(self.regenerate_requested.emit) + b_layout.addWidget(self.regen_btn) + + b_layout.addStretch(1) + + self.copy_btn = QPushButton("复制报告", bottom_bar) + self.copy_btn.setObjectName("AiWingGhostBtn") + self.copy_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.copy_btn.clicked.connect(self._copy_current_report) + b_layout.addWidget(self.copy_btn) + + self.consult_btn = QPushButton("AI 深度追问", bottom_bar) + self.consult_btn.setObjectName("AiWingPrimaryBtn") + self.consult_btn.setIcon(icons.icon("ai", "#FFFFFF", 14)) + self.consult_btn.setIconSize(QSize(14, 14)) + self.consult_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.consult_btn.clicked.connect(self.open_ai_consult_requested.emit) + b_layout.addWidget(self.consult_btn) + root.addWidget(bottom_bar) + + def set_report_context( + self, + *, + histories: Mapping[str, Sequence[Mapping[str, Any]]], + model_states: Mapping[str, str] | None = None, + model_messages: Mapping[str, str] | None = None, + active_model: str = "qwen", + patient_name: str = "", + can_regenerate: bool = True, + ) -> None: + self._patient_name = patient_name + self._histories = { + k: [dict(item) for item in (histories.get(k) or ()) if isinstance(item, Mapping)] + for k, _ in AI_MODELS + } + if model_states is not None: + self._states = {k: str(model_states.get(k, "empty")) for k, _ in AI_MODELS} + if model_messages is not None: + self._messages = {k: str(model_messages.get(k, "")) for k, _ in AI_MODELS} + if active_model in MODEL_LABELS: + self._active_model = active_model + self._active_version_idx = 0 + self.regen_btn.setEnabled(bool(can_regenerate)) + self._refresh_ui() + + def _on_model_clicked(self, model_key: str) -> None: + if model_key not in MODEL_LABELS: + return + self._active_model = model_key + self._active_version_idx = 0 + self._refresh_ui() + self.model_selected.emit(model_key) + + def _on_version_changed(self, index: int) -> None: + if index < 0: + return + self._active_version_idx = index + self._render_active_snapshot() + + def _refresh_ui(self) -> None: + for k, btn in self._model_pills.items(): + has_snap = bool(self._histories.get(k)) + st = self._states.get(k, "empty") + base_lbl = MODEL_LABELS[k] + if st == "loading" and not has_snap: + btn.setText(f"{base_lbl} · 生成中") + elif has_snap: + btn.setText(base_lbl) + else: + btn.setText(base_lbl) + btn.setChecked(k == self._active_model) + + snapshots = self._histories.get(self._active_model, []) + blocked = self.version_combo.blockSignals(True) + try: + self.version_combo.clear() + total = len(snapshots) + for idx, snap in enumerate(snapshots): + ver = first_value(snap, "version", default=total - idx) + ts = display_text(first_value(snap, "generated_at", "created_at", default=""), "")[:16] + label = f"第 {ver} 版 · {ts[5:]}" if len(ts) >= 10 else f"第 {ver} 版" + self.version_combo.addItem(label) + self.version_combo.setVisible(total > 0) + if total > 0: + self._active_version_idx = min(self._active_version_idx, total - 1) + self.version_combo.setCurrentIndex(self._active_version_idx) + finally: + self.version_combo.blockSignals(blocked) + + self._render_active_snapshot() + + def _current_snapshot(self) -> dict[str, Any] | None: + snapshots = self._histories.get(self._active_model, []) + if not snapshots: + return None + idx = max(0, min(self._active_version_idx, len(snapshots) - 1)) + return snapshots[idx] + + def _render_active_snapshot(self) -> None: + snap = self._current_snapshot() + model_label = MODEL_LABELS.get(self._active_model, self._active_model) + if snap is None: + st = self._states.get(self._active_model, "missing") + msg = self._messages.get(self._active_model, "") + if st == "loading": + self.state_title_lbl.setText(f"正在生成 {model_label} 循证分析报告…") + self.state_desc_lbl.setText("正在结合患者实采四诊病历、近期血糖与用药信息进行推理,完成后将自动刷新。") + elif st == "error": + self.state_title_lbl.setText(f"{model_label} 报告加载未成功") + self.state_desc_lbl.setText(msg or "请检查网络或点击左下方「↻ 重新生成」重试。") + else: + self.state_title_lbl.setText(f"尚无已保存的 {model_label} 报告快照") + self.state_desc_lbl.setText( + msg or f"当前患者暂无 {model_label} 历史快照,可切换上方其他模型或点击左下角「↻ 重新生成」。" + ) + self.copy_btn.setEnabled(False) + self.stack.setCurrentIndex(1) + return + + self.copy_btn.setEnabled(True) + self.stack.setCurrentIndex(0) + + diag_advice = _clean_text(first_value(snap, "diagnosis_advice", "diagnosis_suggestion")) + treat_advice = _clean_text(first_value(snap, "treatment_advice", "treatment_suggestion")) + raw_risks = first_value(snap, "risk_assessment", "risk_warning", default=[]) or [] + + # A. Takeaways Strip + clear_layout(self.takeaway_layout) + takeaways = _extract_key_takeaways(diag_advice) + self.takeaway_host.setVisible(bool(takeaways)) + for idx, (cap, short_val, full_val) in enumerate(takeaways[:3]): + tile = QFrame(self.takeaway_host) + tile.setObjectName("AiWingTakeawayTile") + tile.setProperty("emphasis", idx == 0) + tile.setMinimumWidth(0) + tile.setToolTip(f"{cap}:{full_val}") + tl = QVBoxLayout(tile) + tl.setContentsMargins(11, 8, 11, 9) + tl.setSpacing(3) + c_lbl = QLabel(cap, tile) + c_lbl.setStyleSheet("color: #67807C; font-size: 11px; border: 0; background: transparent;") + v_lbl = QLabel(short_val, tile) + v_lbl.setWordWrap(True) + v_lbl.setStyleSheet( + f"color: {'#0B5949' if idx == 0 else '#132624'};" + " font-size: 12px; font-weight: 600; border: 0; background: transparent;" + ) + tl.addWidget(c_lbl) + tl.addWidget(v_lbl) + self.takeaway_layout.addWidget(tile, 1) + + # B. 2-Column Risk Matrix + clear_layout(self.risk_grid) + norm_risks: list[tuple[str, str]] = [] + level_aliases = { + "high": "high", + "danger": "high", + "critical": "high", + "medium": "medium", + "warning": "medium", + "warn": "medium", + "low": "low", + "info": "low", + } + if isinstance(raw_risks, Sequence) and not isinstance(raw_risks, (str, bytes)): + for r in raw_risks: + if isinstance(r, Mapping): + r_lbl = _clean_text(first_value(r, "label", "text", "name", "title")) + raw_lvl = str(first_value(r, "level", "severity", default="medium") or "medium").strip().lower() + if r_lbl: + norm_risks.append((level_aliases.get(raw_lvl, "medium"), r_lbl)) + elif isinstance(r, str) and _clean_text(r): + norm_risks.append(("medium", _clean_text(r))) + + self.risk_count_badge.setText(f"共 {len(norm_risks)} 项" if norm_risks else "未见显著高危") + if not norm_risks: + self.risk_count_badge.setStyleSheet( + "background: #E2F3EE; color: #0E6F5C; border-radius: 9px; padding: 1px 8px; font-size: 11px; font-weight: 600;" + ) + safe_lbl = QLabel("当前病历快照未提示特殊高危项,请结合临床实测指标动态复核。", self.risk_grid_host) + safe_lbl.setWordWrap(True) + safe_lbl.setStyleSheet("color: #5C7470; font-size: 12px;") + self.risk_grid.addWidget(safe_lbl, 0, 0, 1, 2) + else: + has_high = any(lvl == "high" for lvl, _ in norm_risks) + self.risk_count_badge.setStyleSheet( + f"background: {'#FCEBE6' if has_high else '#FBF5E6'};" + f" color: {'#C94534' if has_high else '#9A6B16'};" + " border-radius: 9px; padding: 1px 8px; font-size: 11px; font-weight: 600;" + ) + palette_map = { + "high": ("高危", "#FDF3F1", "#D94F3D", "#C43E2D"), + "medium": ("关注", "#FCF8EE", "#C98E24", "#966914"), + "low": ("提示", "#EFF7F4", "#1B856E", "#0E6F5C"), + } + # Use calm full-width structured rows when risks carry clinical explanations (> 22 chars), + # avoiding cramped 2-column pink/yellow walls of text! + use_single_column = any(len(txt) > 22 for _, txt in norm_risks) + for idx, (lvl, lbl_txt) in enumerate(norm_risks): + tag_txt, pill_bg, left_accent, fg = palette_map[lvl] + chip = QFrame(self.risk_grid_host) + chip.setStyleSheet( + "QFrame {" + " background: #FAFCFB;" + " border: 1px solid #E5EEEC;" + f" border-left: 3px solid {left_accent};" + " border-radius: 10px;" + "}" + ) + if use_single_column: + cv = QVBoxLayout(chip) + cv.setContentsMargins(12, 9, 12, 10) + cv.setSpacing(5) + # Split "风险标题:具体临床解释..." cleanly into Headline + Calm Body + if ":" in lbl_txt or ":" in lbl_txt: + head_part, detail_part = re.split(r"[::]", lbl_txt, maxsplit=1) + head_part = head_part.strip() + detail_part = detail_part.strip() + else: + head_part, detail_part = lbl_txt, "" + + top_r = QHBoxLayout() + top_r.setContentsMargins(0, 0, 0, 0) + top_r.setSpacing(8) + tag = QLabel(tag_txt, chip) + tag.setFixedWidth(36) + tag.setAlignment(Qt.AlignmentFlag.AlignCenter) + tag.setStyleSheet( + f"background: {pill_bg}; color: {fg}; border-radius: 6px;" + " font-size: 11px; font-weight: 600; padding: 1px 0; border: 0;" + ) + top_r.addWidget(tag, 0, Qt.AlignmentFlag.AlignVCenter) + h_lbl = QLabel(head_part, chip) + h_lbl.setWordWrap(True) + h_lbl.setStyleSheet( + "color: #152624; font-size: 13px; font-weight: 600; border: 0; background: transparent;" + ) + top_r.addWidget(h_lbl, 1) + cv.addLayout(top_r) + + if detail_part: + d_lbl = QLabel(_format_prose_html(detail_part, color="#425855", size_px=13, line_pct=162), chip) + d_lbl.setTextFormat(Qt.TextFormat.RichText) + d_lbl.setWordWrap(True) + d_lbl.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + d_lbl.setStyleSheet("border: 0; background: transparent;") + cv.addWidget(d_lbl) + self.risk_grid.addWidget(chip, idx, 0, 1, 2) + else: + cl = QHBoxLayout(chip) + cl.setContentsMargins(10, 8, 10, 8) + cl.setSpacing(8) + tag = QLabel(tag_txt, chip) + tag.setFixedWidth(36) + tag.setAlignment(Qt.AlignmentFlag.AlignCenter) + tag.setStyleSheet( + f"background: {pill_bg}; color: {fg}; border-radius: 6px;" + " font-size: 11px; font-weight: 600; padding: 1px 0; border: 0;" + ) + cl.addWidget(tag, 0, Qt.AlignmentFlag.AlignVCenter) + txt = QLabel(lbl_txt, chip) + txt.setWordWrap(True) + txt.setStyleSheet( + "color: #182B29; font-size: 13px; font-weight: 500; border: 0; background: transparent;" + ) + cl.addWidget(txt, 1) + row, col = divmod(idx, 2) + col_span = 2 if (idx == len(norm_risks) - 1 and col == 0) else 1 + self.risk_grid.addWidget(chip, row, col, 1, col_span) + self.risk_grid.setColumnStretch(0, 1) + self.risk_grid.setColumnStretch(1, 1) + + # C. Structured Four-Examination & Syndrome Reasoning Rows + clear_layout(self.diag_rows_layout) + evidence_rows = _split_evidence_rows(diag_advice) if diag_advice else [] + if not evidence_rows: + empty_d = QLabel("暂无结构化辨证说明。", self.diag_rows_host) + empty_d.setStyleSheet("color: #7A908C; font-size: 13px;") + self.diag_rows_layout.addWidget(empty_d) + else: + for r_idx, (badge_txt, bg_hex, fg_hex, body_txt) in enumerate(evidence_rows): + if r_idx > 0: + sep = QFrame(self.diag_rows_host) + sep.setFixedHeight(1) + sep.setStyleSheet("background-color: #EEF3F1; border: 0;") + self.diag_rows_layout.addWidget(sep) + row_w = QWidget(self.diag_rows_host) + rl = QHBoxLayout(row_w) + rl.setContentsMargins(0, 4, 0, 4) + rl.setSpacing(10) + b_lbl = QLabel(badge_txt, row_w) + b_lbl.setFixedWidth(62) + b_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter) + b_lbl.setStyleSheet( + f"background: {bg_hex}; color: {fg_hex}; border-radius: 7px;" + " padding: 3px 4px; font-size: 11.5px; font-weight: 600;" + ) + rl.addWidget(b_lbl, 0, Qt.AlignmentFlag.AlignTop) + + is_missing_hint = "未采集" in body_txt + val_lbl = QLabel( + _format_prose_html( + body_txt, + color="#9A6B16" if is_missing_hint else "#213533", + size_px=13, + line_pct=168, + ), + row_w, + ) + val_lbl.setTextFormat(Qt.TextFormat.RichText) + val_lbl.setWordWrap(True) + val_lbl.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop) + val_lbl.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + val_lbl.setStyleSheet("background: transparent; border: 0;") + rl.addWidget(val_lbl, 1) + self.diag_rows_layout.addWidget(row_w) + + # D. Treatment & Regimen Card + treat_source = treat_advice or "服务端该版快照暂未附带治疗建议。" + self.treat_body_lbl.setTextFormat(Qt.TextFormat.RichText) + self.treat_body_lbl.setText( + _format_prose_html( + treat_source, + color="#1E3431" if treat_advice else "#6E8581", + size_px=13, + line_pct=168, + ) + ) + + # E. Provenance Tooltip + prov_lines = report_provenance_lines(snap) + self.provenance_lbl.setToolTip( + "\n".join( + [ + *prov_lines, + "", + "医疗安全声明:仅供临床辅助参考,不可替代执业医师诊断,不得直接用于开方或调药。", + ] + ) + ) + + def _copy_current_report(self) -> None: + snap = self._current_snapshot() + if snap is None: + return + model_label = MODEL_LABELS.get(self._active_model, self._active_model) + diag_advice = _clean_text(first_value(snap, "diagnosis_advice", "diagnosis_suggestion")) + treat_advice = _clean_text(first_value(snap, "treatment_advice", "treatment_suggestion")) + raw_risks = first_value(snap, "risk_assessment", "risk_warning", default=[]) or [] + risk_str = "、".join( + _clean_text(first_value(r, "label", "text", "name", "title") if isinstance(r, Mapping) else r) + for r in raw_risks + if _clean_text(first_value(r, "label", "text", "name", "title") if isinstance(r, Mapping) else r) + ) + header = f"【{self._patient_name or '当前患者'} · {model_label} AI 循证报告】" + formatted = "\n\n".join( + part + for part in ( + header, + f"■ 辨证分析:\n{diag_advice}" if diag_advice else "", + f"■ 风险分层:{risk_str}" if risk_str else "", + f"■ 治疗建议:\n{treat_advice}" if treat_advice else "", + ) + if part + ) + clipboard = QApplication.clipboard() + if clipboard is not None: + clipboard.setText(formatted) + self.copy_btn.setIcon(icons.icon("check", "#0E6F5C", 14)) + self.copy_btn.setIconSize(QSize(14, 14)) + self.copy_btn.setText("已复制结论") + self._copy_reset_timer.start(1800) + + def _reset_copy_button(self) -> None: + self.copy_btn.setIcon(QIcon()) + self.copy_btn.setText("复制报告") + + +__all__ = ["ClinicalAiReportWingPanel"] diff --git a/app/src/doctor_workstation/ui/visuals/aurora_sheet.py b/app/src/doctor_workstation/ui/visuals/aurora_sheet.py index ef17c2dfa..db02a3724 100644 --- a/app/src/doctor_workstation/ui/visuals/aurora_sheet.py +++ b/app/src/doctor_workstation/ui/visuals/aurora_sheet.py @@ -39,9 +39,9 @@ class AuroraGlassCardWidget(QWidget): super().__init__(parent) self.setObjectName("AuroraGlassCardWidget") self.setCursor(Qt.CursorShape.PointingHandCursor) - self.setMinimumSize(196, 152) + self.setMinimumSize(132, 148) self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) - self.setFixedHeight(162) + self.setFixedHeight(156) self._vm: AuroraCardVM | None = None self._hovered = False @@ -117,38 +117,43 @@ class AuroraGlassCardWidget(QWidget): painter.setBrush(accent_c) painter.drawEllipse(QPointF(left + 5, rect.top() + 21), 4.0, 4.0) - t_font = QFont(heading_family()) - t_font.setPixelSize(14) - t_font.setWeight(QFont.Weight.DemiBold) - painter.setFont(t_font) - painter.setPen(QColor("#F6FAF9")) - painter.drawText( - QRectF(left + 15, rect.top() + 11, avail_w - 86, 20), - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - vm.title, - ) - b_font = QFont(body_family()) b_font.setPixelSize(10) b_font.setWeight(QFont.Weight.DemiBold) painter.setFont(b_font) - bw = float(painter.fontMetrics().horizontalAdvance(vm.badge_text) + 16) + bw = min(avail_w * 0.44, float(painter.fontMetrics().horizontalAdvance(vm.badge_text) + 14)) b_rect = QRectF(right - bw, rect.top() + 12, bw, 19) bp = QPainterPath() bp.addRoundedRect(b_rect, 9.5, 9.5) painter.setBrush(Qt.BrushStyle.NoBrush) painter.fillPath(bp, QColor(255, 255, 255, 28)) painter.setPen(accent_c) - painter.drawText(b_rect, Qt.AlignmentFlag.AlignCenter, vm.badge_text) + painter.drawText( + b_rect, + Qt.AlignmentFlag.AlignCenter, + painter.fontMetrics().elidedText(vm.badge_text, Qt.TextElideMode.ElideRight, int(max(24, bw - 8))), + ) + + t_font = QFont(heading_family()) + t_font.setPixelSize(13 if avail_w < 170 else 14) + t_font.setWeight(QFont.Weight.DemiBold) + painter.setFont(t_font) + painter.setPen(QColor("#F6FAF9")) + title_max_w = max(40.0, avail_w - bw - 22.0) + painter.drawText( + QRectF(left + 14, rect.top() + 11, title_max_w, 20), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + painter.fontMetrics().elidedText(vm.title, Qt.TextElideMode.ElideRight, int(title_max_w)), + ) s_font = QFont(body_family()) s_font.setPixelSize(11) painter.setFont(s_font) painter.setPen(QColor(215, 230, 227, 160)) painter.drawText( - QRectF(left + 15, rect.top() + 31, avail_w - 16, 15), + QRectF(left + 14, rect.top() + 31, max(40.0, avail_w - 16), 15), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - vm.subtitle, + painter.fontMetrics().elidedText(vm.subtitle, Qt.TextElideMode.ElideRight, int(max(40, avail_w - 16))), ) # Divider line @@ -160,25 +165,25 @@ class AuroraGlassCardWidget(QWidget): body_font.setPixelSize(12) painter.setFont(body_font) painter.setPen(QColor("#EEF5F3")) - body_box = QRectF(left, rect.top() + 57, avail_w, 74) + body_box = QRectF(left, rect.top() + 55, avail_w, 66) opt = QTextOption(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop) opt.setWrapMode(QTextOption.WrapMode.WordWrap) text_to_draw = vm.body_text - if len(text_to_draw) > 108: - text_to_draw = f"{text_to_draw[:106]}…" + if len(text_to_draw) > 96: + text_to_draw = f"{text_to_draw[:94]}…" painter.drawText(body_box, text_to_draw, opt) # Footer metadata painter.setFont(s_font) - painter.setPen(QColor(210, 226, 223, 155)) + painter.setPen(QColor(210, 226, 223, 165)) painter.drawText( - QRectF(left, rect.bottom() - 23, avail_w * 0.62, 16), + QRectF(left, rect.bottom() - 26, avail_w * 0.62, 18), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, vm.foot_left, ) painter.setPen(accent_c) painter.drawText( - QRectF(right - avail_w * 0.38, rect.bottom() - 23, avail_w * 0.38, 16), + QRectF(right - avail_w * 0.38, rect.bottom() - 26, avail_w * 0.38, 18), Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, vm.foot_right, ) @@ -191,7 +196,7 @@ class ArcRhythmGaugeWidget(QWidget): super().__init__(parent) self.setObjectName("ArcRhythmGaugeWidget") self.setMouseTracking(True) - self.setFixedSize(202, 162) + self.setFixedSize(202, 156) self._value_text = "0/6" self._unit_text = "项" self._caption = "病历实采完备度" @@ -226,8 +231,8 @@ class ArcRhythmGaugeWidget(QWidget): rect = QRectF(self.rect()) cx = rect.center().x() - cy = rect.top() + 92.0 - radius = 66.0 + cy = rect.top() + 86.0 + radius = 62.0 arc_box = QRectF(cx - radius, cy - radius, radius * 2.0, radius * 2.0) hemi = QRadialGradient(QPointF(cx, cy), radius) @@ -305,7 +310,7 @@ class CollapsibleObsidianSheet(QWidget): self._vm: ObsidianAuroraVM | None = None root = QVBoxLayout(self) - root.setContentsMargins(22, 24, 22, 14) + root.setContentsMargins(22, 18, 22, 14) root.setSpacing(10) top_bar = QHBoxLayout() @@ -319,10 +324,11 @@ class CollapsibleObsidianSheet(QWidget): top_bar.addWidget(self.title_label) self.summary_label = QLabel("选择患者后自动读取千问 / OpenAI / 豆包实采病历分析报告", self) + self.summary_label.setMinimumWidth(0) self.summary_label.setStyleSheet( "color: rgba(220, 234, 231, 185); font-size: 12px; background: transparent;" ) - self.summary_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) + self.summary_label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) top_bar.addWidget(self.summary_label, 1) self._model_buttons: dict[str, QPushButton] = {} @@ -376,7 +382,8 @@ class CollapsibleObsidianSheet(QWidget): body_layout.setSpacing(14) left_col = QWidget(self.body_widget) - left_col.setFixedWidth(196) + left_col.setFixedWidth(188) + self.left_meta_col = left_col left_layout = QVBoxLayout(left_col) left_layout.setContentsMargins(0, 0, 0, 0) left_layout.setSpacing(8) @@ -452,10 +459,25 @@ class CollapsibleObsidianSheet(QWidget): def toggle_expanded(self) -> None: self.set_expanded(not self._expanded) + def _sync_responsive_columns(self) -> None: + w = self.width() + if w <= 0: + return + self.summary_label.setVisible(w >= 720) + if hasattr(self, "left_meta_col"): + self.left_meta_col.setVisible(w >= 1060) + if hasattr(self, "gauge"): + self.gauge.setVisible(w >= 860) + + def resizeEvent(self, event: object) -> None: # noqa: N802 + super().resizeEvent(event) # type: ignore[arg-type] + self._sync_responsive_columns() + def _apply_expanded_geometry(self) -> None: self.body_widget.setVisible(self._expanded) self.toggle_button.setText("收起分析舱 ▼" if self._expanded else "展开分析舱 ▲") self.setFixedHeight(238 if self._expanded else 64) + self._sync_responsive_columns() self.update() def set_view_model(self, vm: ObsidianAuroraVM) -> None: diff --git a/app/src/doctor_workstation/ui/visuals/diurnal_strip.py b/app/src/doctor_workstation/ui/visuals/diurnal_strip.py index 1ce5bb856..272629baf 100644 --- a/app/src/doctor_workstation/ui/visuals/diurnal_strip.py +++ b/app/src/doctor_workstation/ui/visuals/diurnal_strip.py @@ -1,8 +1,10 @@ -"""Real postprandial 2h blood glucose, 14-day check-in strip, and 3 vital bricks.""" +"""Real postprandial 2h blood glucose & dated clinical indicators — ONLY Real Data + Dates.""" from __future__ import annotations -from PySide6.QtCore import QPointF, QRectF, QSize, Qt +import html + +from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen from PySide6.QtWidgets import QToolTip, QWidget @@ -11,16 +13,21 @@ from ..viewmodels.cockpit_vm import DiurnalSlot, DiurnalStabilityVM, VitalMiniBr class DiurnalStabilityCard(QWidget): - """Render real 2h postprandial glucose, 14-day daily records, and BP/BMI/Meds bricks.""" + """Render real 2h postprandial glucose, real dated check-in bars, and real dated clinical bricks.""" + + open_daily_requested = Signal() + vital_clicked = Signal(str) def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) self.setObjectName("DiurnalStabilityCard") self.setMouseTracking(True) - self.setMinimumHeight(218) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setMinimumHeight(168) self._vm: DiurnalStabilityVM | None = None self._slot_rects: list[tuple[QRectF, DiurnalSlot]] = [] self._brick_rects: list[tuple[QRectF, VitalMiniBrick]] = [] + self._missing_rect = QRectF() def sizeHint(self) -> QSize: # noqa: N802 return QSize(330, 300) @@ -32,16 +39,51 @@ class DiurnalStabilityCard(QWidget): def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 pos = event.position() for rect, slot in self._slot_rects: - if rect.adjusted(-1, -6, 1, 6).contains(pos) and slot.tooltip: - QToolTip.showText(event.globalPosition().toPoint(), slot.tooltip, self) + if rect.adjusted(-3, -14, 3, 16).contains(pos) and slot.tooltip: + safe_tip = "
".join( + html.escape(p.strip()) for p in slot.tooltip.split(" · ") if p.strip() + ) + QToolTip.showText( + event.globalPosition().toPoint(), + f"
{safe_tip}
", + self, + ) super().mouseMoveEvent(event) return for rect, brick in self._brick_rects: if rect.contains(pos) and brick.tooltip: - QToolTip.showText(event.globalPosition().toPoint(), brick.tooltip, self) + safe_tip = "
".join( + html.escape(p.strip()) for p in brick.tooltip.split(" · ") if p.strip() + ) + QToolTip.showText( + event.globalPosition().toPoint(), + f"
{safe_tip}
", + self, + ) break super().mouseMoveEvent(event) + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + pos = event.position() + for rect, brick in self._brick_rects: + if rect.contains(pos): + self.vital_clicked.emit(brick.field_key or "systolic_pressure") + event.accept() + return + if self._missing_rect.contains(pos): + vm = self._vm + if vm is not None and vm.missing_hint.startswith("待补采:餐后血糖") and len(vm.vitals) >= 2: + self.open_daily_requested.emit() + else: + self.vital_clicked.emit("systolic_pressure") + event.accept() + return + self.open_daily_requested.emit() + event.accept() + return + super().mousePressEvent(event) + def paintEvent(self, _event: object) -> None: # noqa: N802 painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) @@ -55,217 +97,304 @@ class DiurnalStabilityCard(QWidget): painter.setPen(QPen(QColor("#E3ECE9"), 1.0)) painter.drawPath(card_path) + self._slot_rects.clear() + self._brick_rects.clear() + self._missing_rect = QRectF() + vm = self._vm if vm is None: return - compact = rect.height() < 262.0 + compact = rect.height() < 252.0 pad_x = 18.0 - pad_y = 11.0 if compact else 15.0 + pad_y = 12.0 if compact else 15.0 left = rect.left() + pad_x right = rect.right() - pad_x avail_w = max(120.0, right - left) # 1. Title + Reference / Alert Badge - title_font = QFont(heading_family()) - title_font.setPixelSize(14 if compact else 15) - title_font.setWeight(QFont.Weight.DemiBold) - painter.setFont(title_font) - painter.setPen(QColor("#111F1D")) - painter.drawText( - QRectF(left, rect.top() + pad_y, 175, 22), - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - vm.title, - ) - badge_font = QFont(body_family()) - badge_font.setPixelSize(11) + badge_font.setPixelSize(10 if avail_w < 205 else 11) badge_font.setWeight(QFont.Weight.Medium) painter.setFont(badge_font) - badge_w = min(132.0, float(painter.fontMetrics().horizontalAdvance(vm.mode_badge) + 18)) - badge_rect = QRectF(right - badge_w, rect.top() + pad_y, badge_w, 22) + badge_w = min(124.0, float(painter.fontMetrics().horizontalAdvance(vm.mode_badge) + 16)) + badge_rect = QRectF(right - badge_w, rect.top() + pad_y, badge_w, 21) badge_path = QPainterPath() - badge_path.addRoundedRect(badge_rect, 11.0, 11.0) + badge_path.addRoundedRect(badge_rect, 10.5, 10.5) is_high_badge = "偏高" in vm.mode_badge painter.fillPath(badge_path, QColor("#FCEBE6" if is_high_badge else "#E2F3EE")) painter.setPen(QColor("#D96243" if is_high_badge else "#0E6F5C")) painter.drawText(badge_rect, Qt.AlignmentFlag.AlignCenter, vm.mode_badge) - # 2. Primary Value + unit + caption - is_numeric = any(ch.isdigit() for ch in vm.primary_value) - num_font = QFont(number_family() if is_numeric else heading_family()) - num_font.setPixelSize((29 if compact else 34) if is_numeric else (21 if compact else 24)) - num_font.setWeight(QFont.Weight.DemiBold) - painter.setFont(num_font) - painter.setPen(QColor("#0F1D1B") if vm.primary_value not in {"—", "未记录"} else QColor("#7D918E")) - num_w = float(painter.fontMetrics().horizontalAdvance(vm.primary_value)) - metric_y = rect.top() + (34.0 if compact else 44.0) + title_font = QFont(heading_family()) + title_font.setPixelSize(13 if avail_w < 205 else (14 if compact else 15)) + title_font.setWeight(QFont.Weight.DemiBold) + painter.setFont(title_font) + painter.setPen(QColor("#111F1D")) + title_w = max(60.0, avail_w - badge_w - 8.0) painter.drawText( - QRectF(left, metric_y, num_w + 4, 36 if compact else 40), + QRectF(left, rect.top() + pad_y, title_w, 21), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - vm.primary_value, + painter.fontMetrics().elidedText(vm.title, Qt.TextElideMode.ElideRight, int(title_w)), ) - unit_w = 0.0 - if vm.unit: - unit_font = QFont(body_family()) - unit_font.setPixelSize(13 if compact else 14) - painter.setFont(unit_font) - painter.setPen(QColor("#5C726F")) - unit_w = float(painter.fontMetrics().horizontalAdvance(vm.unit)) - painter.drawText( - QRectF(left + num_w + 4, metric_y + (5 if compact else 8), unit_w + 6, 26), - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - vm.unit, - ) - + # 2. Primary Value + Unit + Caption small_font = QFont(body_family()) small_font.setPixelSize(11) - painter.setFont(small_font) - painter.setPen(QColor("#7D918E")) - cap_x = left + num_w + unit_w + (10 if vm.unit else 8) - if right - cap_x > 50: - elided_cap = painter.fontMetrics().elidedText( - vm.caption, Qt.TextElideMode.ElideRight, int(right - cap_x) - ) + tiny_font = QFont(body_family()) + tiny_font.setPixelSize(10) + + is_numeric = any(ch.isdigit() for ch in vm.primary_value) + cursor_y = rect.top() + pad_y + 26.0 + if is_numeric: + num_font = QFont(number_family()) + num_font.setPixelSize(26 if compact else 31) + num_font.setWeight(QFont.Weight.DemiBold) + painter.setFont(num_font) + painter.setPen(QColor("#0F1D1B")) + num_w = float(painter.fontMetrics().horizontalAdvance(vm.primary_value)) painter.drawText( - QRectF(cap_x, metric_y + (6 if compact else 10), right - cap_x, 24), + QRectF(left, cursor_y, num_w + 4, 34), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - elided_cap, + vm.primary_value, ) - - # 3. Clinical Glycemic Range Track (4.4 — 7.8 — 11.1 mmol/L) - track_y = metric_y + (38.0 if compact else 48.0) - track_rect = QRectF(left, track_y, avail_w, 6.0) - track_bg = QPainterPath() - track_bg.addRoundedRect(track_rect, 3.0, 3.0) - painter.fillPath(track_bg, QColor("#EDF2F0")) - - safe_track = QRectF(left, track_y, avail_w * 0.78, 6.0) - safe_path = QPainterPath() - safe_path.addRoundedRect(safe_track, 3.0, 3.0) - painter.fillPath(safe_path, QColor("#C6E8DF" if vm.has_marker else "#E2ECE9")) - - if vm.has_marker: - dot_x = left + avail_w * max(0.06, min(0.95, vm.range_marker_ratio)) - painter.setPen(QPen(QColor("#FFFFFF"), 2.0)) - painter.setBrush(QColor("#E06D4C" if is_high_badge else "#111918")) - painter.drawEllipse(QPointF(dot_x, track_y + 3.0), 5.2, 5.2) - - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.setPen(QColor("#7D918E")) - painter.drawText(QRectF(left, track_y + 9, 45, 14), Qt.AlignmentFlag.AlignLeft, vm.range_min_text) - painter.drawText( - QRectF(left + avail_w * 0.25, track_y + 9, avail_w * 0.50, 14), - Qt.AlignmentFlag.AlignCenter, - vm.range_target_text, - ) - painter.drawText(QRectF(right - 45, track_y + 9, 45, 14), Qt.AlignmentFlag.AlignRight, vm.range_max_text) - - # 4. Real 14-Day Check-In Strip - strip_header_y = track_y + (24.0 if compact else 30.0) - sub_bold = QFont(body_family()) - sub_bold.setPixelSize(11) - sub_bold.setWeight(QFont.Weight.DemiBold) - painter.setFont(sub_bold) - painter.setPen(QColor("#243735")) - painter.drawText( - QRectF(left, strip_header_y, avail_w * 0.54, 16), - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - vm.overnight_title, - ) - painter.setFont(small_font) - has_alert = any(s.state == "alert" for s in vm.slots) - painter.setPen(QColor("#D96243") if has_alert else QColor("#6E8380")) - painter.drawText( - QRectF(left + avail_w * 0.44, strip_header_y, avail_w * 0.56, 16), - Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, - vm.overnight_peak_hint, - ) - - strip_top = strip_header_y + (16.0 if compact else 20.0) - strip_h = 20.0 if compact else 26.0 - n_slots = max(1, len(vm.slots)) - s_gap = 4.0 - s_w = max(5.0, (avail_w - s_gap * (n_slots - 1)) / n_slots) - self._slot_rects.clear() - for idx, slot in enumerate(vm.slots): - sx = left + idx * (s_w + s_gap) - sh = max(5.0, strip_h * max(0.16, min(1.0, slot.height_ratio))) - sy = strip_top + (strip_h - sh) - s_rect = QRectF(sx, sy, s_w, sh) - self._slot_rects.append((s_rect, slot)) - spath = QPainterPath() - spath.addRoundedRect(s_rect, 3.0, 3.0) - if slot.state == "alert": - s_color = QColor("#E06D4C") - elif slot.state == "mint": - s_color = QColor("#52B69E") - elif slot.state == "normal": - s_color = QColor("#BCE3D9") - else: - s_color = QColor("#E7EFED") - painter.fillPath(spath, s_color) - - time_y = strip_top + strip_h + 3 - painter.setPen(QColor("#829692")) - first_lbl = vm.slots[0].time_label if vm.slots else "14天前" - mid_lbl = vm.slots[len(vm.slots) // 2].time_label if vm.slots else "7天前" - for ratio_pos, label_txt in ((0.0, first_lbl), (0.5, mid_lbl), (1.0, "今日")): - tx = left + (avail_w - 42) * ratio_pos - align = ( - Qt.AlignmentFlag.AlignLeft - if ratio_pos == 0.0 - else (Qt.AlignmentFlag.AlignRight if ratio_pos == 1.0 else Qt.AlignmentFlag.AlignCenter) - ) - painter.drawText(QRectF(tx, time_y, 42, 14), align, label_txt) - - # 5. Bottom 3 Real Vital Mini-Bricks (BP, Height/Weight/BMI, Medications) - brick_top = time_y + (15.0 if compact else 20.0) - brick_h = max(44.0 if compact else 52.0, rect.bottom() - brick_top - (10.0 if compact else 13.0)) - b_gap = 8.0 - b_w = (avail_w - b_gap * 2) / 3.0 - - self._brick_rects.clear() - for idx, brick in enumerate(vm.vitals[:3]): - bx = left + idx * (b_w + b_gap) - b_rect = QRectF(bx, brick_top, b_w, brick_h) - self._brick_rects.append((b_rect, brick)) - b_path = QPainterPath() - b_path.addRoundedRect(b_rect, 13.0, 13.0) - painter.fillPath(b_path, QColor("#FDF2EE") if brick.alert else QColor("#F5F8F7")) - - painter.setFont(small_font) - painter.setPen(QColor("#6A7F7C")) - painter.drawText( - QRectF(bx + 9, brick_top + 6, b_w - 12, 15), - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - brick.label, - ) - - has_digit = any(ch.isdigit() for ch in brick.value) - b_val_font = QFont(number_family() if has_digit else body_family()) - b_val_font.setPixelSize(15 if has_digit else 12) - b_val_font.setWeight(QFont.Weight.DemiBold) - painter.setFont(b_val_font) - painter.setPen(QColor("#D15839") if brick.alert else QColor("#11201E")) - elided_val = painter.fontMetrics().elidedText( - brick.value, Qt.TextElideMode.ElideRight, int(b_w - 14) - ) - val_w = float(painter.fontMetrics().horizontalAdvance(elided_val)) - painter.drawText( - QRectF(bx + 9, brick_top + 23, b_w - 14, 22), - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - elided_val, - ) - if brick.unit and val_w + 26 < b_w: + unit_w = 0.0 + if vm.unit: painter.setFont(small_font) - painter.setPen(QColor("#7D918E")) - elided_unit = painter.fontMetrics().elidedText( - brick.unit, Qt.TextElideMode.ElideRight, int(b_w - val_w - 14) - ) + painter.setPen(QColor("#5C726F")) + unit_w = float(painter.fontMetrics().horizontalAdvance(vm.unit)) painter.drawText( - QRectF(bx + 11 + val_w, brick_top + 25, b_w - val_w - 14, 18), + QRectF(left + num_w + 4, cursor_y + 6, unit_w + 6, 22), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - elided_unit, + vm.unit, ) + painter.setFont(small_font) + painter.setPen(QColor("#7D918E")) + cap_x = left + num_w + unit_w + 10.0 + if right - cap_x > 46: + painter.drawText( + QRectF(cap_x, cursor_y + 6, right - cap_x, 22), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + painter.fontMetrics().elidedText(vm.caption, Qt.TextElideMode.ElideRight, int(right - cap_x)), + ) + cursor_y += 38.0 + else: + # Unrecorded postprandial: compact 1-line status bar instead of wasting 70px! + bar_r = QRectF(left, cursor_y + 2, avail_w, 28.0) + bp = QPainterPath() + bp.addRoundedRect(bar_r, 9.0, 9.0) + painter.fillPath(bp, QColor("#F5F9F8")) + painter.setFont(small_font) + painter.setPen(QColor("#5E7572")) + status_line = ( + "餐后2h血糖:暂未实测(点击录入日常血糖 ↗)" + if vm.primary_value == "未记录" + else "选择患者后展示实测血糖与已采体征" + ) + painter.drawText( + bar_r.adjusted(10, 0, -10, 0), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + painter.fontMetrics().elidedText(status_line, Qt.TextElideMode.ElideRight, int(avail_w - 20)), + ) + cursor_y += 36.0 + + # 3. ONLY Render Real Check-In Bars When Recorded Dates Exist (Value Above + Date Below) + if vm.slots: + sub_bold = QFont(body_family()) + sub_bold.setPixelSize(11) + sub_bold.setWeight(QFont.Weight.DemiBold) + painter.setFont(sub_bold) + painter.setPen(QColor("#213633")) + painter.drawText( + QRectF(left, cursor_y, avail_w * 0.50, 15), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + "实测打卡记录", + ) + painter.setFont(tiny_font) + painter.setPen(QColor("#6E8380")) + painter.drawText( + QRectF(left + avail_w * 0.50, cursor_y, avail_w * 0.50, 15), + Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, + painter.fontMetrics().elidedText(vm.overnight_peak_hint, Qt.TextElideMode.ElideLeft, int(avail_w * 0.50)), + ) + cursor_y += 18.0 + + bar_area_top = cursor_y + 13.0 + bar_area_h = 24.0 if compact else 30.0 + n_slots = len(vm.slots) + s_gap = 8.0 if n_slots <= 5 else 5.0 + s_w = min(34.0, max(16.0, (avail_w - s_gap * (n_slots - 1)) / n_slots)) + pitch = s_w + s_gap + val_font = QFont(number_family()) + val_font.setPixelSize(10) + val_font.setWeight(QFont.Weight.DemiBold) + + for idx, slot in enumerate(vm.slots): + sx = left + idx * pitch + sh = max(8.0, bar_area_h * max(0.28, min(1.0, slot.height_ratio))) + sy = bar_area_top + (bar_area_h - sh) + s_rect = QRectF(sx, sy, s_w, sh) + self._slot_rects.append((s_rect, slot)) + spath = QPainterPath() + spath.addRoundedRect(s_rect, 5.0, 5.0) + s_color = ( + QColor("#E06D4C") + if slot.state == "alert" + else QColor("#0E6F5C") + if slot.state == "mint" + else QColor("#8BCABB") + ) + painter.fillPath(spath, s_color) + + if slot.value_text and pitch >= 28.0: + painter.setFont(val_font) + painter.setPen(QColor("#C84E2E") if slot.state == "alert" else QColor("#18322F")) + painter.drawText( + QRectF(sx - 8, sy - 13, s_w + 16, 12), + Qt.AlignmentFlag.AlignCenter, + slot.value_text, + ) + + if pitch >= 30.0 or idx in {0, n_slots - 1}: + painter.setFont(tiny_font) + painter.setPen(QColor("#4F6663")) + painter.drawText( + QRectF(sx - 10, bar_area_top + bar_area_h + 2, s_w + 20, 13), + Qt.AlignmentFlag.AlignCenter, + slot.time_label, + ) + cursor_y = bar_area_top + bar_area_h + 18.0 + + # 4. ONLY Render Real Recorded Clinical Indicators (with Date Underneath — Zero Empty '—' Boxes!) + bottom_reserve = 28.0 if vm.missing_hint else 8.0 + vitals_avail_h = max(36.0, rect.bottom() - cursor_y - bottom_reserve) + + if vm.vitals: + if not vm.slots: + # Spacious horizontal dated rows when check-in chart is absent (e.g. 王进花) + sub_hdr = QFont(body_family()) + sub_hdr.setPixelSize(11) + sub_hdr.setWeight(QFont.Weight.DemiBold) + painter.setFont(sub_hdr) + painter.setPen(QColor("#213633")) + painter.drawText( + QRectF(left, cursor_y, avail_w, 16), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + "已采临床体征与问诊实录", + ) + cursor_y += 20.0 + vitals_avail_h = max(36.0, rect.bottom() - cursor_y - bottom_reserve) + + max_rows = min(len(vm.vitals), max(1, int((vitals_avail_h + 6.0) // 40.0))) + row_gap = 6.0 + row_h = min(46.0, max(34.0, (vitals_avail_h - row_gap * (max_rows - 1)) / max_rows)) + for brick in vm.vitals[:max_rows]: + r_rect = QRectF(left, cursor_y, avail_w, row_h) + self._brick_rects.append((r_rect, brick)) + rp = QPainterPath() + rp.addRoundedRect(r_rect, 11.0, 11.0) + painter.fillPath(rp, QColor("#FDF3EF") if brick.alert else "#F6FAF9") + painter.setPen(QPen(QColor("#F2D4CA" if brick.alert else "#E3ECE9"), 1.0)) + painter.drawPath(rp) + + # Left: Label + Date underneath + painter.setFont(small_font) + painter.setPen(QColor("#48605C")) + painter.drawText( + QRectF(r_rect.left() + 11, r_rect.top() + 4, avail_w * 0.44, 15), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + brick.label, + ) + painter.setFont(tiny_font) + painter.setPen(QColor("#829793")) + painter.drawText( + QRectF(r_rect.left() + 11, r_rect.bottom() - 16, avail_w * 0.46, 13), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + brick.date_label or "病历实录", + ) + + # Right: Bold Real Value + Unit + full_v = f"{brick.value} {brick.unit}".strip() + has_d = any(ch.isdigit() for ch in brick.value) + v_font = QFont(number_family() if has_d else heading_family()) + v_font.setPixelSize(13 if has_d else 12) + v_font.setWeight(QFont.Weight.DemiBold) + painter.setFont(v_font) + painter.setPen(QColor("#C84E2E") if brick.alert else QColor("#112220")) + v_w = avail_w * 0.52 + painter.drawText( + QRectF(r_rect.right() - v_w - 11, r_rect.top(), v_w, row_h), + Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, + painter.fontMetrics().elidedText(full_v, Qt.TextElideMode.ElideRight, int(v_w)), + ) + cursor_y += row_h + row_gap + else: + # Compact fixed-height grid bricks with Date Underneath (NEVER stretched to 150px!) + cols = min(3, len(vm.vitals)) + b_gap = 7.0 + b_w = (avail_w - b_gap * (cols - 1)) / cols + b_h = min(58.0, max(46.0, vitals_avail_h)) + for idx, brick in enumerate(vm.vitals[:cols]): + bx = left + idx * (b_w + b_gap) + b_rect = QRectF(bx, cursor_y, b_w, b_h) + self._brick_rects.append((b_rect, brick)) + bp = QPainterPath() + bp.addRoundedRect(b_rect, 12.0, 12.0) + painter.fillPath(bp, QColor("#FDF2EE") if brick.alert else "#F5F9F8") + painter.setPen(QPen(QColor("#F2D4CA" if brick.alert else "#E3ECE9"), 1.0)) + painter.drawPath(bp) + + in_pad = 7.0 if b_w < 80 else 9.0 + raw_lbl = brick.label + if b_w < 88: + if "血压" in raw_lbl: + raw_lbl = "血压" + elif "BMI" in raw_lbl or "体质量" in raw_lbl: + raw_lbl = "BMI" + elif "降糖" in raw_lbl or "用药" in raw_lbl: + raw_lbl = "现用药" + painter.setFont(tiny_font) + painter.setPen(QColor("#687E7B")) + painter.drawText( + QRectF(bx + in_pad, b_rect.top() + 5, b_w - in_pad * 2, 13), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + painter.fontMetrics().elidedText(raw_lbl, Qt.TextElideMode.ElideRight, int(max(22, b_w - in_pad * 2))), + ) + + has_d = any(ch.isdigit() for ch in brick.value) + v_font = QFont(number_family() if has_d else body_family()) + v_font.setPixelSize(13 if (has_d and b_w >= 76) else 12) + v_font.setWeight(QFont.Weight.DemiBold) + painter.setFont(v_font) + painter.setPen(QColor("#C84E2E") if brick.alert else QColor("#11201E")) + val_disp = ( + f"{brick.value} {brick.unit.split('(')[0].strip()}".strip() + if brick.unit and b_w >= 96 + else brick.value + ) + painter.drawText( + QRectF(bx + in_pad, b_rect.top() + 19, b_w - in_pad * 2, 18), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + painter.fontMetrics().elidedText(val_disp, Qt.TextElideMode.ElideRight, int(max(22, b_w - in_pad * 2))), + ) + + if b_h >= 48.0 and brick.date_label: + painter.setFont(tiny_font) + painter.setPen(QColor("#829793")) + painter.drawText( + QRectF(bx + in_pad, b_rect.bottom() - 14, b_w - in_pad * 2, 12), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + painter.fontMetrics().elidedText(brick.date_label, Qt.TextElideMode.ElideRight, int(max(22, b_w - in_pad * 2))), + ) + + # 5. Compact Actionable Footer for Unrecorded Vitals (Replaces Empty '—' Tombstones!) + if vm.missing_hint: + m_rect = QRectF(left, rect.bottom() - 25.0, avail_w, 19.0) + self._missing_rect = m_rect + painter.setFont(tiny_font) + painter.setPen(QColor("#0E6F5C") if "点击" in vm.missing_hint else QColor("#7D918E")) + painter.drawText( + m_rect, + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + painter.fontMetrics().elidedText(vm.missing_hint, Qt.TextElideMode.ElideRight, int(avail_w)), + ) diff --git a/app/src/doctor_workstation/ui/visuals/journey_track.py b/app/src/doctor_workstation/ui/visuals/journey_track.py index 3915a71b9..4dcd89b7a 100644 --- a/app/src/doctor_workstation/ui/visuals/journey_track.py +++ b/app/src/doctor_workstation/ui/visuals/journey_track.py @@ -2,6 +2,9 @@ from __future__ import annotations +import html +from datetime import date + from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen from PySide6.QtWidgets import QToolTip, QWidget @@ -48,7 +51,14 @@ class CareJourneyCard(QWidget): for rect, cell in self._day_rects: if rect.contains(pos): hover_day = cell.day_num - QToolTip.showText(event.globalPosition().toPoint(), cell.tooltip, self) + safe_tip = "
".join( + html.escape(p.strip()) for p in cell.tooltip.split(" · ") if p.strip() + ) + QToolTip.showText( + event.globalPosition().toPoint(), + f"
{safe_tip}
", + self, + ) break self.setCursor( Qt.CursorShape.PointingHandCursor @@ -173,120 +183,169 @@ class CareJourneyCard(QWidget): painter.setPen(QPen(QColor("#ECF2F0"), 1.0)) painter.drawLine(QPointF(div_x, rect.top() + 16), QPointF(div_x, rect.bottom() - 16)) - # Right 21-Day Real Calendar Matrix Column - rx = div_x + 18.0 - rw = max(260.0, rect.right() - rx - 18.0) + # Right Responsive Calendar Strip (14 days full-width / 7 days when Companion Wing narrows stage) + rx = div_x + 20.0 + rw = max(240.0, rect.right() - rx - 20.0) - painter.setFont(sub_font) - painter.setPen(QColor("#839794")) - painter.drawText(QRectF(rx, rect.top() + 13, 175, 16), Qt.AlignmentFlag.AlignLeft, "逐日实测日历(悬停查看明细)") + all_days = list(vm.days) + # Keep every date card comfortably wide (>= 36px) — never squeeze into thin barcode slivers + visible_days = all_days[-7:] if (rw < 640.0 and len(all_days) > 7) else all_days + n_days = max(1, len(visible_days)) + has_week_split = n_days >= 14 - legend_items = ( - ("#0E6F5C", True, "血糖达标"), - ("#E06D4C", True, "血糖偏高"), - ("#CBE8E0", True, "饮食/运动"), - ("#111918", True, "今日"), - ("#DCE6E3", False, "无打卡"), + first_iso = visible_days[0].date_iso[5:] if visible_days and len(visible_days[0].date_iso) >= 10 else "" + last_iso = visible_days[-1].date_iso[5:] if visible_days and len(visible_days[-1].date_iso) >= 10 else "" + span_title = ( + f"本周近 7 天打卡日历 · {first_iso} 至 {last_iso}" + if n_days <= 7 + else f"近 {n_days} 天实测打卡日历 · {first_iso} 至 {last_iso}" ) - lx = rect.right() - 348 - for color_hex, filled, text in legend_items: - sw = QRectF(lx, rect.top() + 16, 9, 9) - sp = QPainterPath() - sp.addRoundedRect(sw, 2.5, 2.5) - painter.setBrush(Qt.BrushStyle.NoBrush) - if filled: - painter.fillPath(sp, QColor(color_hex)) - else: - painter.setPen(QPen(QColor(color_hex), 1.1)) - painter.drawPath(sp) - painter.setPen(QColor("#5C726F")) - painter.drawText(QRectF(lx + 12, rect.top() + 13, 56, 15), Qt.AlignmentFlag.AlignLeft, text) - lx += 68 - n_days = max(1, len(vm.days)) - followup_w = 58.0 - gap = 5.0 - pills_avail = max(180.0, rw - followup_w - 10.0) - pill_w = max(18.0, (pills_avail - gap * (n_days - 1)) / n_days) - - # Weekly spans + horizontal span bars - phase_y = rect.top() + 34 - bar_y = phase_y + 29 - for ph in vm.phases: - px1 = rx + (ph.start_day - 1) * (pill_w + gap) - px2 = rx + ph.end_day * pill_w + (ph.end_day - 1) * gap - pw = max(40.0, px2 - px1 - 4.0) - - p_font = QFont(body_family()) - p_font.setPixelSize(11) - p_font.setWeight(QFont.Weight.DemiBold if ph.active else QFont.Weight.Medium) - painter.setFont(p_font) - painter.setPen(QColor("#0E6F5C") if ph.active else QColor("#354A47")) - painter.drawText(QRectF(px1, phase_y, pw, 15), Qt.AlignmentFlag.AlignLeft, f"{ph.code} · {ph.title}") + hdr_font = QFont(heading_family()) + hdr_font.setPixelSize(12) + hdr_font.setWeight(QFont.Weight.DemiBold) + painter.setFont(hdr_font) + painter.setPen(QColor("#1E3330")) + painter.drawText( + QRectF(rx, rect.top() + 18, min(280.0, rw), 18), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + span_title, + ) + if rw >= 500.0: + legend_items = ( + ("#0E6F5C", True, "达标"), + ("#E06D4C", True, "偏高"), + ("#CBE8E0", True, "饮食/运动"), + ("#111918", True, "今日"), + ) painter.setFont(sub_font) - painter.setPen(QColor("#829692")) - painter.drawText(QRectF(px1, phase_y + 14, pw, 14), Qt.AlignmentFlag.AlignLeft, ph.date_span) + lx = rect.right() - 252.0 + for color_hex, filled, text in legend_items: + sw = QRectF(lx, rect.top() + 22, 8.5, 8.5) + sp = QPainterPath() + sp.addRoundedRect(sw, 2.5, 2.5) + painter.setBrush(Qt.BrushStyle.NoBrush) + if filled: + painter.fillPath(sp, QColor(color_hex)) + else: + painter.setPen(QPen(QColor(color_hex), 1.1)) + painter.drawPath(sp) + painter.setPen(QColor("#5C726F")) + item_w = 56.0 if len(text) > 2 else 38.0 + painter.drawText( + QRectF(lx + 12, rect.top() + 18, item_w, 17), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + text, + ) + lx += item_w + 18.0 - line_color = QColor("#111918") if ph.active else QColor("#CFE0DC") - painter.setPen(QPen(line_color, 2.0, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap)) - painter.drawLine(QPointF(px1, bar_y), QPointF(px1 + pw, bar_y)) + followup_w = 68.0 + gap = 8.0 if n_days >= 14 else 10.0 + week_split_extra = 12.0 if has_week_split else 0.0 + pills_avail = max(180.0, rw - followup_w - 14.0 - week_split_extra) + pill_w = min(64.0, max(32.0, (pills_avail - gap * (n_days - 1)) / n_days)) - # 21 Real Date Pills - pill_top = bar_y + 7 - pill_h = 38.0 + # Spacious Rounded Date Cards (Weekday + Date + Dot — zero redundant multi-row clutter) + pill_top = rect.top() + 52.0 + pill_h = min(68.0, max(54.0, rect.height() - 74.0)) self._day_rects.clear() - num_pill_font = QFont(number_family()) - num_pill_font.setPixelSize(12) - num_pill_font.setWeight(QFont.Weight.DemiBold) - painter.setFont(num_pill_font) - today_center_x = rx - for idx, cell in enumerate(vm.days): - dx = rx + idx * (pill_w + gap) - d_rect = QRectF(dx, pill_top, pill_w, pill_h) + wk_names = ("周一", "周二", "周三", "周四", "周五", "周六", "周日") + wk_font = QFont(body_family()) + wk_font.setPixelSize(10) + wk_font.setWeight(QFont.Weight.Medium) + + num_pill_font = QFont(number_family()) + num_pill_font.setPixelSize(14) + num_pill_font.setWeight(QFont.Weight.DemiBold) + + cursor_x = rx + for idx, cell in enumerate(visible_days): + if has_week_split and idx == 7: + mid_x = cursor_x + week_split_extra * 0.5 - gap * 0.5 + painter.setPen(QPen(QColor("#E3ECE9"), 1.0, Qt.PenStyle.DashLine)) + painter.drawLine(QPointF(mid_x, pill_top + 6), QPointF(mid_x, pill_top + pill_h - 6)) + cursor_x += week_split_extra + + d_rect = QRectF(cursor_x, pill_top, pill_w, pill_h) self._day_rects.append((d_rect, cell)) dp = QPainterPath() - dp.addRoundedRect(d_rect, 9.0, 9.0) + dp.addRoundedRect(d_rect, 13.0, 13.0) is_hover = cell.day_num == self._hover_day painter.setBrush(Qt.BrushStyle.NoBrush) if cell.state == "completed": painter.fillPath(dp, QColor("#0B5B4B" if is_hover else "#0E6F5C")) - fg = QColor("#FFFFFF") + top_fg = QColor(255, 255, 255, 200) + num_fg = QColor("#FFFFFF") elif cell.state == "alert": painter.fillPath(dp, QColor("#CC5738" if is_hover else "#E06D4C")) - fg = QColor("#FFFFFF") + top_fg = QColor(255, 255, 255, 210) + num_fg = QColor("#FFFFFF") elif cell.state == "stage": - painter.fillPath(dp, QColor("#B4DFD4" if is_hover else "#CBE8E0")) - fg = QColor("#11352E") + painter.fillPath(dp, QColor("#B4DFD4" if is_hover else "#D4EDE6")) + top_fg = QColor("#295E52") + num_fg = QColor("#0F332B") elif cell.state == "today": - today_center_x = d_rect.center().x() painter.fillPath(dp, QColor("#111918")) - fg = QColor("#FFFFFF") + top_fg = QColor("#7CE2C8") + num_fg = QColor("#FFFFFF") else: - painter.fillPath(dp, QColor("#F3F7F6" if is_hover else "#FFFFFF")) - painter.setPen(QPen(QColor("#DCE6E3"), 1.0)) + painter.fillPath(dp, QColor("#EDF4F2" if is_hover else "#F8FBFA")) + painter.setPen(QPen(QColor("#DCE7E4"), 1.0)) painter.drawPath(dp) - fg = QColor("#7E928F") + top_fg = QColor("#8A9E9A") + num_fg = QColor("#3E5451") - painter.setPen(fg) - text_rect = d_rect.adjusted(0, -3, 0, -3) if cell.has_dot else d_rect - painter.drawText(text_rect, Qt.AlignmentFlag.AlignCenter, cell.label_text) - if cell.has_dot: + wk_txt = "今日" if cell.state == "today" else "" + if not wk_txt and len(cell.date_iso) >= 10: + try: + wk_txt = wk_names[date.fromisoformat(cell.date_iso[:10]).weekday()] + except ValueError: + wk_txt = "" + + painter.setFont(wk_font) + painter.setPen(top_fg) + painter.drawText( + QRectF(d_rect.left(), d_rect.top() + 7, pill_w, 14), + Qt.AlignmentFlag.AlignCenter, + wk_txt, + ) + + painter.setFont(num_pill_font) + painter.setPen(num_fg) + painter.drawText( + QRectF(d_rect.left(), d_rect.top() + 22, pill_w, 22), + Qt.AlignmentFlag.AlignCenter, + cell.label_text, + ) + + if cell.has_dot or cell.state in {"completed", "alert", "stage"}: painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor("#FFFFFF" if cell.state != "today" else "#E06D4C")) - painter.drawEllipse(QPointF(d_rect.center().x(), d_rect.bottom() - 7.5), 2.2, 2.2) + dot_c = ( + QColor("#E06D4C") + if cell.state == "today" and cell.has_dot + else QColor("#7CE2C8") + if cell.state == "today" + else QColor("#0E6F5C") + if cell.state == "stage" + else QColor(255, 255, 255, 220) + ) + painter.setBrush(dot_c) + painter.drawEllipse(QPointF(d_rect.center().x(), d_rect.bottom() - 7.5), 2.3, 2.3) + + cursor_x += pill_w + gap # End Revisit / Prescription Status Capsule - f_rect = QRectF(rx + n_days * (pill_w + gap) + 4.0, pill_top, followup_w, pill_h) + f_rect = QRectF(cursor_x + 6.0, pill_top, followup_w, pill_h) fp = QPainterPath() - fp.addRoundedRect(f_rect, 10.0, 10.0) + fp.addRoundedRect(f_rect, 13.0, 13.0) painter.setBrush(Qt.BrushStyle.NoBrush) - painter.fillPath(fp, QColor("#FCEEE9" if vm.status_tone == "coral" else "#F4FAF8")) + painter.fillPath(fp, QColor("#FCEEE9" if vm.status_tone == "coral" else "#EFF8F5")) painter.setPen( QPen( - QColor("#D96243" if vm.status_tone == "coral" else "#6BAE9E"), + QColor("#D96243" if vm.status_tone == "coral" else "#86C3B4"), 1.1, Qt.PenStyle.DashLine, ) @@ -295,20 +354,3 @@ class CareJourneyCard(QWidget): painter.setFont(badge_font) painter.setPen(QColor("#C85232" if vm.status_tone == "coral" else "#0E6F5C")) painter.drawText(f_rect, Qt.AlignmentFlag.AlignCenter, vm.end_capsule_text) - - # Bottom Date Anchors + Black '今日' Pill - mile_y = pill_top + pill_h + 6 - for day_idx, m_text in vm.milestones: - mx = rx + (day_idx - 1) * (pill_w + gap) + pill_w * 0.5 - if day_idx == n_days: - t_pill = QRectF(today_center_x - 20, mile_y, 40, 17) - tp = QPainterPath() - tp.addRoundedRect(t_pill, 8.5, 8.5) - painter.fillPath(tp, QColor("#111918")) - painter.setFont(badge_font) - painter.setPen(QColor("#FFFFFF")) - painter.drawText(t_pill, Qt.AlignmentFlag.AlignCenter, "今日") - else: - painter.setFont(sub_font) - painter.setPen(QColor("#788E8A")) - painter.drawText(QRectF(mx - 28, mile_y, 56, 15), Qt.AlignmentFlag.AlignCenter, m_text) diff --git a/app/src/doctor_workstation/ui/visuals/pill_chart.py b/app/src/doctor_workstation/ui/visuals/pill_chart.py index bdfe58461..1e4af3612 100644 --- a/app/src/doctor_workstation/ui/visuals/pill_chart.py +++ b/app/src/doctor_workstation/ui/visuals/pill_chart.py @@ -1,8 +1,10 @@ -"""Real fasting blood glucose progression Bento card (mmol/L) rendered with QPainter.""" +"""Real fasting blood glucose progression Bento card (mmol/L) — ONLY Real Points + Dates.""" from __future__ import annotations -from PySide6.QtCore import QPointF, QRectF, QSize, Qt +import html + +from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen from PySide6.QtWidgets import QToolTip, QWidget @@ -11,13 +13,16 @@ from ..viewmodels.cockpit_vm import GlycemicProgressionVM, ProgressionPoint class PillProgressionCard(QWidget): - """Plot up to 12 real fasting blood glucose measurements against the 7.0 mmol/L line.""" + """Plot ONLY real recorded fasting blood glucose measurements with value above & date below.""" + + open_daily_requested = Signal() def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) self.setObjectName("PillProgressionCard") self.setMouseTracking(True) - self.setMinimumHeight(172) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setMinimumHeight(140) self._vm: GlycemicProgressionVM | None = None self._hover_index: int = -1 self._bar_rects: list[tuple[QRectF, ProgressionPoint]] = [] @@ -39,16 +44,30 @@ class PillProgressionCard(QWidget): pos = event.position() hit = -1 for idx, (rect, point) in enumerate(self._bar_rects): - if rect.adjusted(-2, -10, 2, 6).contains(pos): + if rect.adjusted(-4, -18, 4, 20).contains(pos): hit = idx if point.value_hint: - QToolTip.showText(event.globalPosition().toPoint(), point.value_hint, self) + safe_tip = "
".join( + html.escape(p.strip()) for p in point.value_hint.split(" · ") if p.strip() + ) + QToolTip.showText( + event.globalPosition().toPoint(), + f"
{safe_tip}
", + self, + ) break if hit != self._hover_index: self._hover_index = hit self.update() super().mouseMoveEvent(event) + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + self.open_daily_requested.emit() + event.accept() + return + super().mousePressEvent(event) + def paintEvent(self, _event: object) -> None: # noqa: N802 painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) @@ -72,40 +91,43 @@ class PillProgressionCard(QWidget): right = rect.right() - pad_x # 1. Header row: Title + Reference badge - title_font = QFont(heading_family()) - title_font.setPixelSize(14 if compact else 15) - title_font.setWeight(QFont.Weight.DemiBold) - painter.setFont(title_font) - painter.setPen(QColor("#111F1D")) - painter.drawText( - QRectF(left, rect.top() + (12 if compact else 15), 160, 22), - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - vm.title, - ) - + avail_w = max(120.0, right - left) badge_font = QFont(body_family()) - badge_font.setPixelSize(11) + badge_font.setPixelSize(10 if avail_w < 205 else 11) badge_font.setWeight(QFont.Weight.Medium) painter.setFont(badge_font) - badge_w = min(142.0, float(painter.fontMetrics().horizontalAdvance(vm.subtitle_badge) + 18)) + badge_txt = vm.subtitle_badge.replace("参考 ", "") if avail_w < 205 else vm.subtitle_badge + badge_w = min(132.0, float(painter.fontMetrics().horizontalAdvance(badge_txt) + 14)) badge_rect = QRectF(right - badge_w, rect.top() + (12 if compact else 15), badge_w, 22) badge_path = QPainterPath() badge_path.addRoundedRect(badge_rect, 11.0, 11.0) painter.fillPath(badge_path, QColor("#F2F6F5")) painter.setPen(QColor("#4E6662")) - painter.drawText(badge_rect, Qt.AlignmentFlag.AlignCenter, vm.subtitle_badge) + painter.drawText(badge_rect, Qt.AlignmentFlag.AlignCenter, badge_txt) + + title_font = QFont(heading_family()) + title_font.setPixelSize(13 if avail_w < 205 else (14 if compact else 15)) + title_font.setWeight(QFont.Weight.DemiBold) + painter.setFont(title_font) + painter.setPen(QColor("#111F1D")) + title_max_w = max(50.0, avail_w - badge_w - 8.0) + painter.drawText( + QRectF(left, rect.top() + (12 if compact else 15), title_max_w, 22), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + painter.fontMetrics().elidedText(vm.title, Qt.TextElideMode.ElideRight, int(title_max_w)), + ) # 2. Primary Real Fasting Value + Unit + Status Pill is_numeric = any(ch.isdigit() for ch in vm.primary_value) num_font = QFont(number_family() if is_numeric else heading_family()) - num_font.setPixelSize((32 if compact else 38) if is_numeric else (22 if compact else 25)) + num_font.setPixelSize((30 if compact else 36) if is_numeric else (21 if compact else 24)) num_font.setWeight(QFont.Weight.DemiBold) painter.setFont(num_font) painter.setPen(QColor("#0F1D1B") if vm.primary_value not in {"—", "未记录"} else QColor("#7D918E")) num_w = float(painter.fontMetrics().horizontalAdvance(vm.primary_value)) - metric_y = rect.top() + (38 if compact else 44) + metric_y = rect.top() + (37 if compact else 43) painter.drawText( - QRectF(left, metric_y, num_w + 6, 42), + QRectF(left, metric_y, num_w + 6, 40), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, vm.primary_value, ) @@ -116,14 +138,13 @@ class PillProgressionCard(QWidget): painter.setFont(unit_font) painter.setPen(QColor("#6C827E")) painter.drawText( - QRectF(left + num_w + 5, metric_y + 8, 66, 28), + QRectF(left + num_w + 5, metric_y + 7, 66, 26), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, vm.unit, ) - # Right status pill painter.setFont(badge_font) - delta_w = float(painter.fontMetrics().horizontalAdvance(vm.delta_badge) + 20) + delta_w = float(painter.fontMetrics().horizontalAdvance(vm.delta_badge) + 18) delta_rect = QRectF(right - delta_w, metric_y + 3, delta_w, 22) delta_path = QPainterPath() delta_path.addRoundedRect(delta_rect, 11.0, 11.0) @@ -143,78 +164,170 @@ class PillProgressionCard(QWidget): painter.setFont(sub_caption_font) painter.setPen(QColor("#7D918E")) painter.drawText( - QRectF(right - 138, metric_y + 27, 138, 15), + QRectF(right - 148, metric_y + 27, 148, 15), Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, - vm.delta_caption, + painter.fontMetrics().elidedText(vm.delta_caption, Qt.TextElideMode.ElideLeft, 146), ) - # 3. 7.0 mmol/L Threshold Dashed Line + 12 Real Measurement Bars - chart_top = metric_y + (48 if compact else 54) - chart_bottom = rect.bottom() - 28 - chart_h = max(36.0, chart_bottom - chart_top) - - target_y = chart_bottom - chart_h * max(0.25, min(0.88, vm.target_ratio)) - painter.setPen(QPen(QColor("#C8D8D4"), 1.1, Qt.PenStyle.DashLine)) - painter.drawLine(QPointF(left, target_y), QPointF(right, target_y)) - - painter.setFont(sub_caption_font) - painter.setPen(QColor("#6E8380")) - painter.drawText( - QRectF(left, max(chart_top - 2, target_y - 15), 130, 14), - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - vm.target_label, - ) - - bars = vm.bars - count = max(1, len(bars)) - gap = 5.5 - avail_w = max(80.0, right - left) - bar_w = max(8.0, (avail_w - gap * (count - 1)) / count) - + # 3. Real Recorded Bars ONLY (with Value Above + Date Underneath) self._bar_rects.clear() - for idx, pt in enumerate(bars): - bx = left + idx * (bar_w + gap) - bh = max(8.0, chart_h * max(0.14, min(0.98, pt.ratio))) + real_bars = [b for b in vm.bars if b.recorded] + area_top = metric_y + (46 if compact else 52) + area_bottom = rect.bottom() - (12 if compact else 15) + area_h = max(46.0, area_bottom - area_top) + + if not real_bars: + # Honest, actionable empty card — NEVER draw 12 meaningless gray placeholder bars + empty_box = QRectF(left, area_top + 4, avail_w, max(44.0, area_h - 6.0)) + ep = QPainterPath() + ep.addRoundedRect(empty_box, 13.0, 13.0) + painter.fillPath(ep, QColor("#F7FAF9")) + painter.setPen(QPen(QColor("#DCE8E4"), 1.0, Qt.PenStyle.DashLine)) + painter.drawPath(ep) + painter.setFont(sub_caption_font) + painter.setPen(QColor("#5C7470")) + msg = ( + "暂未采集空腹血糖数值\n点击进入「日常记录」新增实测血糖 ↗" + if vm.primary_value != "—" + else "从右侧队列选择患者后展示实测血糖序列与日期" + ) + painter.drawText(empty_box.adjusted(10, 4, -10, -4), Qt.AlignmentFlag.AlignCenter, msg) + return + + chart_top = area_top + 16.0 + chart_bottom = area_bottom - 19.0 + chart_h = max(26.0, chart_bottom - chart_top) + + target_y = chart_bottom - chart_h * max(0.24, min(0.84, vm.target_ratio)) + painter.setPen(QPen(QColor("#CBE0DA"), 1.1, Qt.PenStyle.DashLine)) + + val_font = QFont(number_family()) + val_font.setPixelSize(11) + val_font.setWeight(QFont.Weight.DemiBold) + + date_font = QFont(body_family()) + date_font.setPixelSize(10 if len(real_bars) >= 6 else 11) + + if len(real_bars) == 1: + # Single baseline measurement: clean dated bar on left + clinical insight card on right + pt = real_bars[0] + bar_w = min(36.0, max(26.0, avail_w * 0.16)) + bx = left + 8.0 + bh = max(14.0, chart_h * max(0.24, min(0.92, pt.ratio))) by = chart_bottom - bh bar_rect = QRectF(bx, by, bar_w, bh) self._bar_rects.append((bar_rect, pt)) - radius = min(5.5, bar_w * 0.42) + painter.drawLine(QPointF(left, target_y), QPointF(bx + bar_w + 14.0, target_y)) + + bpath = QPainterPath() + bpath.addRoundedRect(bar_rect, 8.0, 8.0) + fill = QColor("#E06D4C") if pt.alert else QColor("#0E6F5C") + painter.fillPath(bpath, fill) + + painter.setFont(val_font) + painter.setPen(QColor("#C84E2E") if pt.alert else QColor("#0E6F5C")) + painter.drawText( + QRectF(bx - 12, by - 16, bar_w + 24, 15), + Qt.AlignmentFlag.AlignCenter, + pt.value_text or vm.primary_value, + ) + + painter.setFont(date_font) + painter.setPen(QColor("#233835")) + painter.drawText( + QRectF(bx - 16, chart_bottom + 3, bar_w + 32, 16), + Qt.AlignmentFlag.AlignCenter, + pt.label, + ) + + # Clinical Baseline Summary Box beside the single bar + info_x = bx + bar_w + 18.0 + info_w = max(80.0, right - info_x) + if info_w >= 92.0: + info_rect = QRectF(info_x, area_top + 2, info_w, area_h - 4) + ip = QPainterPath() + ip.addRoundedRect(info_rect, 13.0, 13.0) + painter.fillPath(ip, QColor("#FDF5F2" if pt.alert else "#F5FAF8")) + painter.setPen(QPen(QColor("#F2D5CB" if pt.alert else "#D8EAE4"), 1.0)) + painter.drawPath(ip) + + h_f = QFont(heading_family()) + h_f.setPixelSize(11) + h_f.setWeight(QFont.Weight.DemiBold) + painter.setFont(h_f) + painter.setPen(QColor("#B84627") if pt.alert else QColor("#0E6F5C")) + head_t = "高于 7.0 控制线" if pt.alert else "处于 < 7.0 达标区间" + painter.drawText( + QRectF(info_rect.left() + 11, info_rect.top() + 8, info_w - 20, 16), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + head_t, + ) + + painter.setFont(sub_caption_font) + painter.setPen(QColor("#566E6A")) + sub_t = f"实测日期:{pt.label}\n当前仅 1 次记录,点击补录复测 ↗" + painter.drawText( + QRectF(info_rect.left() + 11, info_rect.top() + 26, info_w - 18, info_rect.height() - 30), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop | Qt.TextFlag.TextWordWrap, + sub_t, + ) + return + + # Multiple (2..8) real recorded measurements: plot each bar with value above & date below! + painter.drawLine(QPointF(left, target_y), QPointF(right, target_y)) + painter.setFont(sub_caption_font) + painter.setPen(QColor("#788E8A")) + painter.drawText( + QRectF(right - 96, max(area_top - 2, target_y - 14), 96, 13), + Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, + "7.0 控制线", + ) + + n = len(real_bars) + gap = 10.0 if n <= 5 else 6.0 + bar_w = min(34.0, max(14.0, (avail_w - gap * (n - 1)) / n)) + total_span = n * bar_w + (n - 1) * gap + start_x = left + max(0.0, (avail_w - total_span) * 0.5) if n <= 4 else left + + # Show every date when spacing permits (>= 34px pitch), otherwise alternate + first/last + pitch = bar_w + gap + date_step = 1 if pitch >= 33.0 else 2 + + for idx, pt in enumerate(real_bars): + bx = start_x + idx * pitch + bh = max(12.0, chart_h * max(0.20, min(0.94, pt.ratio))) + by = chart_bottom - bh + bar_rect = QRectF(bx, by, bar_w, bh) + self._bar_rects.append((bar_rect, pt)) + + radius = min(7.5, bar_w * 0.38) bpath = QPainterPath() bpath.addRoundedRect(bar_rect, radius, radius) - - if not pt.recorded: - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.fillPath(bpath, QColor("#F3F7F6")) - painter.setPen(QPen(QColor("#E3ECE9"), 1.0)) - painter.drawPath(bpath) + if pt.alert: + fill = QColor("#E06D4C") if pt.highlight else QColor("#EDA089") + elif pt.highlight: + fill = QColor("#0E6F5C") + elif idx == self._hover_index: + fill = QColor("#4EB09B") else: - if pt.alert: - fill = QColor("#E06D4C") if pt.highlight else QColor("#EFA48E") - elif pt.highlight: - fill = QColor("#0E6F5C") - elif idx == self._hover_index: - fill = QColor("#5AB6A3") - else: - fill = QColor("#AEDCD0") - painter.fillPath(bpath, fill) + fill = QColor("#9FD8CA") + painter.fillPath(bpath, fill) - # 4. Bottom labels - foot_y = rect.bottom() - 22 - painter.setFont(sub_caption_font) - painter.setPen(QColor("#7C908D")) - painter.drawText( - QRectF(left, foot_y, 120, 15), - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - vm.left_foot, - ) - foot_right_font = QFont(body_family()) - foot_right_font.setPixelSize(11) - foot_right_font.setWeight(QFont.Weight.DemiBold) - painter.setFont(foot_right_font) - painter.setPen(QColor("#1A2D2B")) - painter.drawText( - QRectF(right - 135, foot_y, 135, 15), - Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, - vm.right_foot, - ) + if pt.value_text and (pitch >= 26.0 or pt.highlight or idx == 0 or idx == self._hover_index): + painter.setFont(val_font) + painter.setPen(QColor("#C84E2E") if pt.alert else QColor("#18322F")) + painter.drawText( + QRectF(bx - 10, by - 15, bar_w + 20, 14), + Qt.AlignmentFlag.AlignCenter, + pt.value_text, + ) + + if idx % date_step == 0 or idx == n - 1: + painter.setFont(date_font) + painter.setPen(QColor("#112220") if pt.highlight else QColor("#69807C")) + painter.drawText( + QRectF(bx - 14, chart_bottom + 3, bar_w + 28, 15), + Qt.AlignmentFlag.AlignCenter, + pt.label, + ) diff --git a/app/src/doctor_workstation/ui/visuals/reception_cockpit.py b/app/src/doctor_workstation/ui/visuals/reception_cockpit.py index 04e461c9f..af2842025 100644 --- a/app/src/doctor_workstation/ui/visuals/reception_cockpit.py +++ b/app/src/doctor_workstation/ui/visuals/reception_cockpit.py @@ -1,4 +1,4 @@ -"""Three-column Alveo × Serene Clinical Digital Twin Cockpit for ReceptionPage.""" +"""Three-column Alveo × Serene Clinical Cockpit for ReceptionPage (100% Real Data).""" from __future__ import annotations @@ -23,7 +23,7 @@ from ...core.appointment_modes import appointment_type_description, appointment_ from .. import icons from ..reception_style import body_family, heading_family from ..viewmodels.cockpit_vm import CockpitSnapshotVM, derive_cockpit_snapshot -from ..widgets import clear_layout, display_text, first_value +from ..widgets import clear_layout, display_text, first_value, gender_text from .diurnal_strip import DiurnalStabilityCard from .journey_track import CareJourneyCard from .pill_chart import PillProgressionCard @@ -39,14 +39,15 @@ QFrame#CockpitBentoCard { border-radius: 22px; } QPushButton#CockpitFilterPill { + min-width: 0px; min-height: 24px; max-height: 24px; - padding: 0 10px; + padding: 0 6px; border-radius: 12px; border: 0; background-color: #F2F6F5; color: #5E7471; - font-size: 11px; + font-size: 10.5px; font-weight: 500; } QPushButton#CockpitFilterPill:hover { @@ -109,7 +110,7 @@ QLabel#TimelineWaitBadge { font-size: 12px; } QPushButton#CareTeamActionPill { - min-width: 32px; + min-width: 68px; min-height: 30px; max-height: 30px; padding: 0 11px; @@ -131,6 +132,13 @@ QPushButton#CareTeamActionPill:disabled { } """ +QUEUE_SCOPE_LABELS: tuple[tuple[str, str], ...] = ( + ("today_pending", "今日待诊"), + ("today_all", "今日全部"), + ("recent_all", "近期挂号"), + ("consultations", "在管诊单"), +) + def _safe_int(val: Any, default: int = 0) -> int: try: @@ -139,8 +147,13 @@ def _safe_int(val: Any, default: int = 0) -> int: return default +def _clean_line(val: Any) -> str: + txt = display_text(val, "").strip() + return "" if txt in {"", "—", "-", "None", "null"} else txt + + class _TimelineRowWidget(QFrame): - """Single appointment row inside Today's Plan (Alveo solid-emerald active pill).""" + """Single queue row inside Outpatient Queue (Alveo solid-emerald active pill).""" row_clicked = Signal(object) play_clicked = Signal(object) @@ -167,26 +180,42 @@ class _TimelineRowWidget(QFrame): ) layout = QHBoxLayout(self) - layout.setContentsMargins(14, 8, 12, 8) + layout.setContentsMargins(13, 8, 11, 8) layout.setSpacing(10) - # Time + Mode column - time_raw = display_text( - first_value(record, "appointment_time_text", "appointment_time", "time", default="待排期") + is_consultation = str(first_value(record, "_queue_source", default="") or "") == "consultation" + rec_date = _clean_line( + first_value(record, "appointment_date", "diagnosis_date", "latest_appointment_date", "create_time") + )[:10] + time_raw = _clean_line( + first_value(record, "appointment_time_text", "appointment_time", "time") ) - short_time = time_raw.split("-")[0][:5] if ":" in time_raw else time_raw[:6] - mode_txt = appointment_type_description(appointment_type_value(record))[:4] + today_iso = date.today().isoformat() + + if is_consultation: + top_time = rec_date[5:] if len(rec_date) >= 10 else "在管" + sub_mode = _clean_line(first_value(record, "diagnosis_type_text", default="诊单档案"))[:4] + elif rec_date and rec_date != today_iso: + top_time = rec_date[5:] if len(rec_date) >= 10 else rec_date[:6] + sub_mode = ( + time_raw.split("-")[0][:5] + if ":" in time_raw + else appointment_type_description(appointment_type_value(record))[:4] + ) + else: + top_time = time_raw.split("-")[0][:5] if ":" in time_raw else (time_raw[:5] or "今日") + sub_mode = appointment_type_description(appointment_type_value(record))[:4] t_col = QVBoxLayout() t_col.setContentsMargins(0, 0, 0, 0) t_col.setSpacing(1) - t_lbl = QLabel(short_time, self) - t_lbl.setFixedWidth(48) + t_lbl = QLabel(top_time, self) + t_lbl.setFixedWidth(50) t_lbl.setStyleSheet( - f"color: {'#FFFFFF' if active else '#152725'}; font-size: 13px; font-weight: 600; background: transparent;" + f"color: {'#FFFFFF' if active else '#152725'}; font-size: 12px; font-weight: 600; background: transparent;" ) - m_lbl = QLabel(mode_txt, self) - m_lbl.setFixedWidth(48) + m_lbl = QLabel(sub_mode, self) + m_lbl.setFixedWidth(50) m_lbl.setStyleSheet( f"color: {'rgba(255,255,255,195)' if active else '#7A908C'}; font-size: 10px; background: transparent;" ) @@ -194,28 +223,35 @@ class _TimelineRowWidget(QFrame): t_col.addWidget(m_lbl) layout.addLayout(t_col) - # Patient Name + Chief Complaint / Condition - p_name = display_text(first_value(record, "patient_name", "name", default="患者")) - diag_sub = first_value(record, "diagnosis", default={}) or {} - chief = display_text( - first_value( - record, - "chief_complaint", - "clinical_diagnosis", - default=first_value(diag_sub, "chief_complaint", "clinical_diagnosis", default="点击载入四诊详情"), - ) + # Patient Name + Real Clinical Summary + p_name = _clean_line(first_value(record, "patient_name", "name")) or "患者" + gender_raw = first_value(record, "gender_desc", "gender", default=None) + gender = gender_text(gender_raw) if gender_raw not in (None, "") else "" + age = _clean_line(first_value(record, "age")) + demo_tag = "·".join( + part for part in (gender if gender and gender != "—" else "", f"{age}岁" if age else "") if part ) - if len(chief) > 15: - chief = f"{chief[:14]}…" + name_display = f"{p_name} {demo_tag}" if demo_tag else p_name + + diag_sub = first_value(record, "diagnosis", default={}) or {} + clinical_sub = ( + _clean_line(first_value(record, "clinical_diagnosis", "syndrome_type_text", "chief_complaint")) + or _clean_line(first_value(diag_sub, "clinical_diagnosis", "syndrome_type_text", "chief_complaint")) + or _clean_line(first_value(record, "present_illness", "symptoms", "diagnosis_type_text")) + or _clean_line(first_value(record, "status_desc")) + or "点击读取病历详情" + ) + if len(clinical_sub) > 16: + clinical_sub = f"{clinical_sub[:15]}…" c_col = QVBoxLayout() c_col.setContentsMargins(0, 0, 0, 0) c_col.setSpacing(1) - n_lbl = QLabel(p_name, self) + n_lbl = QLabel(name_display, self) n_lbl.setStyleSheet( f"color: {'#FFFFFF' if active else '#11201E'}; font-size: 13px; font-weight: 600; background: transparent;" ) - s_lbl = QLabel(chief, self) + s_lbl = QLabel(clinical_sub, self) s_lbl.setStyleSheet( f"color: {'rgba(255,255,255,205)' if active else '#6E8380'}; font-size: 11px; background: transparent;" ) @@ -223,25 +259,26 @@ class _TimelineRowWidget(QFrame): c_col.addWidget(s_lbl) layout.addLayout(c_col, 1) - # Right Status / Play Action (Alveo circular white play button on active emerald row!) status = _safe_int(first_value(record, "status", default=1), 1) if active: - play_btn = QPushButton("▷", self) + play_btn = QPushButton("", self) play_btn.setObjectName("TimelinePlayCircle") play_btn.setFixedSize(30, 30) + play_btn.setIcon(icons.icon("play", "#0E6F5C", 14)) + play_btn.setIconSize(QSize(14, 14)) play_btn.setStyleSheet( "QPushButton#TimelinePlayCircle {" " min-width: 30px; max-width: 30px; min-height: 30px; max-height: 30px;" - " border-radius: 15px; background-color: #FFFFFF; border: 0;" - " color: #0E6F5C; font-size: 12px; font-weight: 700; padding: 0; }" + " border-radius: 15px; background-color: #FFFFFF; border: 0; padding: 0; }" "QPushButton#TimelinePlayCircle:hover { background-color: #E6F6F1; }" ) - play_btn.setToolTip("立即发起视频 / IM 问诊") + play_btn.setToolTip("打开患者会话 / 视频问诊") play_btn.clicked.connect(lambda: self.play_clicked.emit(self.record)) layout.addWidget(play_btn) elif status == 3: - done_lbl = QLabel("✓", self) + done_lbl = QLabel(self) done_lbl.setObjectName("TimelineDoneBadge") + done_lbl.setPixmap(icons.pixmap("check_circle", "#0E6F5C", 16)) done_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter) layout.addWidget(done_lbl) else: @@ -259,13 +296,15 @@ class _TimelineRowWidget(QFrame): class ReceptionDigitalTwinCockpit(QWidget): - """Full Alveo × Serene 3-column Digital Twin Cockpit + 21-Day Journey Track.""" + """Full Alveo × Serene 3-column Clinical Cockpit + 21-Day Real Check-in Track.""" appointment_selected = Signal(object) filter_status_requested = Signal(object) + queue_scope_requested = Signal(str) refresh_requested = Signal() start_video_requested = Signal() edit_diagnosis_requested = Signal() + locus_selected = Signal(str) notify_assistant_requested = Signal() complete_visit_requested = Signal() open_chart_tab_requested = Signal(int) @@ -284,30 +323,39 @@ class ReceptionDigitalTwinCockpit(QWidget): cockpit_row.setContentsMargins(0, 0, 0, 0) cockpit_row.setSpacing(14) - # Column 1 (Left 25%): Glycemic Progression + Diurnal TIR & Mini Vitals + # Column 1 (Left 26%): Real Fasting Glucose + Postprandial & Real Vitals left_wing = QWidget(self) - left_wing.setMinimumWidth(276) + left_wing.setMinimumWidth(214) left_wing.setMaximumWidth(390) left_layout = QVBoxLayout(left_wing) left_layout.setContentsMargins(0, 0, 0, 0) left_layout.setSpacing(12) self.progression_card = PillProgressionCard(left_wing) + self.progression_card.open_daily_requested.connect( + lambda: self.locus_selected.emit("daily_glucose") + ) self.diurnal_card = DiurnalStabilityCard(left_wing) + self.diurnal_card.open_daily_requested.connect( + lambda: self.locus_selected.emit("daily_glucose") + ) + self.diurnal_card.vital_clicked.connect( + lambda fk: self.locus_selected.emit(f"vital:{fk}") + ) left_layout.addWidget(self.progression_card, 44) left_layout.addWidget(self.diurnal_card, 56) cockpit_row.addWidget(left_wing, 26) - # Column 2 (Center 47%): Translucent Jade-Crystal Three-Jiao Digital Twin Stage + # Column 2 (Center 46%): Human Body & Metabolic Visceral Symptom Stage self.twin_stage = ClinicalTwinStageWidget(self) - self.twin_stage.locus_clicked.connect(lambda _locus: self.edit_diagnosis_requested.emit()) + self.twin_stage.locus_clicked.connect(self.locus_selected.emit) self.twin_stage.open_chart_requested.connect(lambda: self.open_chart_tab_requested.emit(0)) cockpit_row.addWidget(self.twin_stage, 46) - # Column 3 (Right 28%): Today's Plan Timeline + Care Team Collaboration + # Column 3 (Right 28%): Outpatient Queue + Care Team Actions right_wing = QWidget(self) - right_wing.setMinimumWidth(286) - right_wing.setMaximumWidth(400) + right_wing.setMinimumWidth(256) + right_wing.setMaximumWidth(404) right_layout = QVBoxLayout(right_wing) right_layout.setContentsMargins(0, 0, 0, 0) right_layout.setSpacing(12) @@ -320,25 +368,25 @@ class ReceptionDigitalTwinCockpit(QWidget): root.addLayout(cockpit_row, 1) - # ── Layer 4A: Bottom 21-Day Care Journey Rounded-Pill Matrix ─────── + # ── Layer 4A: Bottom 21-Day Real Daily Check-in Matrix ───────────── self.journey_card = CareJourneyCard(self) - self.journey_card.open_full_plan_requested.connect(lambda: self.open_chart_tab_requested.emit(4)) + self.journey_card.open_full_plan_requested.connect(lambda: self.open_chart_tab_requested.emit(3)) self.journey_card.day_selected.connect(lambda _d: self.open_chart_tab_requested.emit(3)) root.addWidget(self.journey_card) - # Seed default visual state immediately so screen is rich even while async loads + # Initialize with honest empty snapshot until a patient is loaded self.set_snapshot(derive_cockpit_snapshot()) def _build_today_plan_card(self, parent: QWidget) -> QFrame: card = QFrame(parent) card.setObjectName("CockpitBentoCard") layout = QVBoxLayout(card) - layout.setContentsMargins(18, 15, 18, 14) - layout.setSpacing(10) + layout.setContentsMargins(16, 14, 16, 14) + layout.setSpacing(9) head = QHBoxLayout() - head.setSpacing(8) - title = QLabel("今日门诊计划", card) + head.setSpacing(6) + title = QLabel("门诊接诊队列", card) t_font = QFont(heading_family()) t_font.setPixelSize(15) t_font.setWeight(QFont.Weight.DemiBold) @@ -347,8 +395,8 @@ class ReceptionDigitalTwinCockpit(QWidget): head.addWidget(title) head.addStretch(1) - self.plan_date_label = QLabel(date.today().strftime("%m月%d日"), card) - self.plan_date_label.setStyleSheet("color: #788E8A; font-size: 12px; background: transparent;") + self.plan_date_label = QLabel(date.today().strftime("%m-%d"), card) + self.plan_date_label.setStyleSheet("color: #6B827E; font-size: 11px; background: transparent;") head.addWidget(self.plan_date_label) refresh_btn = QPushButton(card) @@ -356,7 +404,7 @@ class ReceptionDigitalTwinCockpit(QWidget): refresh_btn.setIcon(icons.icon("refresh", "#5A706D", 14)) refresh_btn.setIconSize(QSize(14, 14)) refresh_btn.setCursor(Qt.CursorShape.PointingHandCursor) - refresh_btn.setToolTip("刷新今日接诊队列") + refresh_btn.setToolTip("刷新当前接诊队列与患者病历") refresh_btn.setStyleSheet( "QPushButton { background: #F3F7F6; border: 0; border-radius: 13px; }" "QPushButton:hover { background: #E3F2EE; }" @@ -365,19 +413,19 @@ class ReceptionDigitalTwinCockpit(QWidget): head.addWidget(refresh_btn) layout.addLayout(head) - # Compact status filter chips + # 4 Real Data Scope Chips: 今日待诊 / 今日全部 / 近期挂号 / 在管诊单 chip_row = QHBoxLayout() - chip_row.setSpacing(6) - self._status_pills: dict[int | None, QPushButton] = {} - for st_val, st_label in ((1, "待接诊"), (None, "全部"), (3, "已完成")): - pill = QPushButton(st_label, card) + chip_row.setSpacing(3) + self._scope_pills: dict[str, QPushButton] = {} + for scope_key, scope_label in QUEUE_SCOPE_LABELS: + pill = QPushButton(scope_label, card) pill.setObjectName("CockpitFilterPill") pill.setCheckable(True) pill.setCursor(Qt.CursorShape.PointingHandCursor) - pill.clicked.connect(lambda _c=False, v=st_val: self._on_filter_pill_clicked(v)) - self._status_pills[st_val] = pill + pill.clicked.connect(lambda _c=False, k=scope_key: self._on_scope_pill_clicked(k)) + self._scope_pills[scope_key] = pill chip_row.addWidget(pill) - self._status_pills[1].setChecked(True) + self._scope_pills["today_all"].setChecked(True) chip_row.addStretch(1) layout.addLayout(chip_row) @@ -402,11 +450,11 @@ class ReceptionDigitalTwinCockpit(QWidget): card = QFrame(parent) card.setObjectName("CockpitBentoCard") layout = QVBoxLayout(card) - layout.setContentsMargins(18, 14, 18, 14) + layout.setContentsMargins(16, 14, 16, 14) layout.setSpacing(8) head = QHBoxLayout() - title = QLabel("诊疗协作组", card) + title = QLabel("诊疗协作与归档", card) t_font = QFont(heading_family()) t_font.setPixelSize(15) t_font.setWeight(QFont.Weight.DemiBold) @@ -414,19 +462,18 @@ class ReceptionDigitalTwinCockpit(QWidget): title.setStyleSheet("color: #11201E; background: transparent;") head.addWidget(title) head.addStretch(1) - shift_lbl = QLabel("3 席在线协同", card) - shift_lbl.setStyleSheet("color: #7A908C; font-size: 11px; background: transparent;") - head.addWidget(shift_lbl) + self.team_hint_lbl = QLabel("当前接诊职责", card) + self.team_hint_lbl.setStyleSheet("color: #7A908C; font-size: 11px; background: transparent;") + head.addWidget(self.team_hint_lbl) layout.addLayout(head) - # 3 Alveo Care Team Rows: Lead Doctor, Assigned Assistant, Clinical Completion self.doctor_name_lbl, self.doctor_role_lbl, self.edit_diag_btn = self._add_team_row( layout, avatar_text="医", avatar_bg="#E2F3EE", avatar_fg="#0E6F5C", name="主诊中医师", - role="辨证施治 · 四诊合参", + role="四诊病历录入与辨证修订", action_text="编辑病历", callback=self.edit_diagnosis_requested.emit, ) @@ -435,8 +482,8 @@ class ReceptionDigitalTwinCockpit(QWidget): avatar_text="助", avatar_bg="#EDF4F2", avatar_fg="#2B524C", - name="专属医助", - role="诊前采集 · 院外随访", + name="待分配医助", + role="诊前资料采集 · 院外随访", action_text="通知医助", callback=self.notify_assistant_requested.emit, ) @@ -446,7 +493,7 @@ class ReceptionDigitalTwinCockpit(QWidget): avatar_bg="#FAF4E6", avatar_fg="#9E7425", name="门诊闭环核验", - role="病历归档 · 完成本次接诊", + role="病历归档 · 完成本次挂号接诊", action_text="完成接诊", callback=self.complete_visit_requested.emit, ) @@ -484,6 +531,7 @@ class ReceptionDigitalTwinCockpit(QWidget): n_lbl = QLabel(name, row) n_lbl.setStyleSheet("color: #122220; font-size: 13px; font-weight: 600; background: transparent;") r_lbl = QLabel(role, row) + r_lbl.setMinimumWidth(0) r_lbl.setStyleSheet("color: #788E8A; font-size: 11px; background: transparent;") r_lbl.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) meta.addWidget(n_lbl) @@ -498,10 +546,10 @@ class ReceptionDigitalTwinCockpit(QWidget): parent_layout.addWidget(row) return n_lbl, r_lbl, btn - def _on_filter_pill_clicked(self, status_val: int | None) -> None: - for k, btn in self._status_pills.items(): - btn.setChecked(k == status_val) - self.filter_status_requested.emit(status_val) + def _on_scope_pill_clicked(self, scope_key: str) -> None: + for k, btn in self._scope_pills.items(): + btn.setChecked(k == scope_key) + self.queue_scope_requested.emit(scope_key) def set_snapshot(self, snapshot: CockpitSnapshotVM) -> None: self.progression_card.set_view_model(snapshot.progression) @@ -520,7 +568,7 @@ class ReceptionDigitalTwinCockpit(QWidget): ) -> None: self.doctor_name_lbl.setText(doctor_name if doctor_name and doctor_name != "—" else "主诊中医师") self.assistant_name_lbl.setText( - f"{assistant_name}(医助)" if assistant_name and assistant_name != "—" else "待分配医助" + f"{assistant_name}(医助)" if assistant_name and assistant_name != "—" else "未分配医助" ) self.edit_diag_btn.setEnabled(can_edit) self.notify_asst_btn.setEnabled(can_notify) @@ -531,19 +579,41 @@ class ReceptionDigitalTwinCockpit(QWidget): records: Sequence[Any], selected_appointment_id: int | None, *, - active_filter_status: int | None = 1, + active_scope: str = "today_all", + active_filter_status: int | None = None, queue_date: str = "", + scope_notice: str = "", ) -> None: - for k, btn in self._status_pills.items(): - btn.setChecked(k == active_filter_status) - if queue_date: + resolved_scope = active_scope + if resolved_scope not in self._scope_pills: + resolved_scope = "today_pending" if active_filter_status == 1 else "today_all" + for k, btn in self._scope_pills.items(): + btn.setChecked(k == resolved_scope) + + if scope_notice: + full_txt = f"{scope_notice} · {len(records)}人" + short_txt = f"自动回溯 · {len(records)}人" if len(full_txt) > 12 else full_txt + self.plan_date_label.setText(short_txt) + self.plan_date_label.setToolTip(full_txt) + elif resolved_scope == "recent_all": + self.plan_date_label.setText(f"近期 · {len(records)}人") + self.plan_date_label.setToolTip(f"近期挂号 · 共 {len(records)} 人") + elif resolved_scope == "consultations": + self.plan_date_label.setText(f"在管 · {len(records)}人") + self.plan_date_label.setToolTip(f"在管诊单 · 共 {len(records)} 人") + elif queue_date: self.plan_date_label.setText(f"{queue_date[5:]} · {len(records)}人") + self.plan_date_label.setToolTip(f"{queue_date} · 共 {len(records)} 人") else: self.plan_date_label.setText(f"共 {len(records)} 人") + self.plan_date_label.setToolTip("") clear_layout(self.timeline_layout) if not records: - empty = QLabel("当前筛选下暂无门诊挂号\n可切换上方「全部」查看历史接诊", self.timeline_host) + empty = QLabel( + "当前范围暂无患者记录\n可切换上方「近期挂号」或「在管诊单」加载历史病历", + self.timeline_host, + ) empty.setAlignment(Qt.AlignmentFlag.AlignCenter) empty.setStyleSheet( f"color: #7D918E; font-size: 12px; font-family: '{body_family()}';" @@ -554,8 +624,8 @@ class ReceptionDigitalTwinCockpit(QWidget): return for rec in records[:25]: - rec_id = _safe_int(first_value(rec, "id", "appointment_id", default=0)) - is_active = bool(selected_appointment_id and rec_id == selected_appointment_id) + rec_id = _safe_int(first_value(rec, "id", "appointment_id", default=0), 0) + is_active = bool(selected_appointment_id is not None and rec_id == selected_appointment_id) row_widget = _TimelineRowWidget(rec, active=is_active, parent=self.timeline_host) row_widget.row_clicked.connect(self.appointment_selected.emit) row_widget.play_clicked.connect(lambda _r: self.start_video_requested.emit()) diff --git a/app/src/doctor_workstation/ui/visuals/twin_stage.py b/app/src/doctor_workstation/ui/visuals/twin_stage.py index 546d6bbaa..0a78546df 100644 --- a/app/src/doctor_workstation/ui/visuals/twin_stage.py +++ b/app/src/doctor_workstation/ui/visuals/twin_stage.py @@ -14,8 +14,9 @@ from PySide6.QtGui import ( QPainterPath, QPen, QRadialGradient, + QTextOption, ) -from PySide6.QtWidgets import QToolTip, QWidget +from PySide6.QtWidgets import QWidget from .. import motion from ..reception_style import body_family, heading_family @@ -39,17 +40,20 @@ class ClinicalTwinStageWidget(QWidget): super().__init__(parent) self.setObjectName("ClinicalTwinStageWidget") self.setMouseTracking(True) - self.setMinimumSize(400, 320) + self.setMinimumSize(244, 260) self._snapshot: CockpitSnapshotVM | None = None self._mode_key = "sanjiao" self._phase = 0.0 self._mode_rects: list[tuple[str, QRectF]] = [] self._callout_rects: list[tuple[str, QRectF, str]] = [] self._open_chart_rect = QRectF() + self._scan_badge_rect = QRectF() + self._bottom_capsule_rect = QRectF() + self._active_popover: tuple[str, QRectF] | None = None self._hover_target = "" self._anim_timer = QTimer(self) - self._anim_timer.setInterval(100) + self._anim_timer.setInterval(900) self._anim_timer.timeout.connect(self._tick_breath) def sizeHint(self) -> QSize: # noqa: N802 @@ -79,23 +83,33 @@ class ClinicalTwinStageWidget(QWidget): self.mode_changed.emit(mode_key) self.update() + def leaveEvent(self, event: object) -> None: # noqa: N802 + if self._hover_target: + self._hover_target = "" + self.update() + super().leaveEvent(event) # type: ignore[arg-type] + def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 pos = event.position() target = "" if self._open_chart_rect.contains(pos): target = "open_chart" + elif self._scan_badge_rect.contains(pos): + target = "scan_date" if not target: for key, r in self._mode_rects: if r.contains(pos): target = f"mode:{key}" break + if not target and self._active_popover is not None and self._active_popover[1].contains(pos): + target = f"locus:{self._active_popover[0]}" if not target: - for locus_id, r, tip in self._callout_rects: + for locus_id, r, _tip in self._callout_rects: if r.contains(pos): target = f"locus:{locus_id}" - if tip: - QToolTip.showText(event.globalPosition().toPoint(), tip, self) break + if not target and self._bottom_capsule_rect.contains(pos): + target = "summary_capsule" self.setCursor( Qt.CursorShape.PointingHandCursor if target else Qt.CursorShape.ArrowCursor ) @@ -108,7 +122,16 @@ class ClinicalTwinStageWidget(QWidget): if event.button() == Qt.MouseButton.LeftButton: pos = event.position() if self._open_chart_rect.contains(pos): - self.open_chart_requested.emit() + if self._mode_key == "organ": + self.locus_clicked.emit("past_history") + elif self._mode_key == "tcm": + self.locus_clicked.emit("rx_summary") + else: + self.open_chart_requested.emit() + event.accept() + return + if self._scan_badge_rect.contains(pos): + self.locus_clicked.emit("local_diagnosis") event.accept() return for key, r in self._mode_rects: @@ -116,11 +139,19 @@ class ClinicalTwinStageWidget(QWidget): self.set_mode(key) event.accept() return + if self._active_popover is not None and self._active_popover[1].contains(pos): + self.locus_clicked.emit(self._active_popover[0]) + event.accept() + return for locus_id, r, _tip in self._callout_rects: if r.contains(pos): self.locus_clicked.emit(locus_id) event.accept() return + if self._bottom_capsule_rect.contains(pos): + self.locus_clicked.emit("summary_capsule") + event.accept() + return super().mousePressEvent(event) def _draw_human_metabolic_twin( @@ -136,7 +167,9 @@ class ClinicalTwinStageWidget(QWidget): cx = rect.center().x() cy = rect.center().y() + 4.0 h = rect.height() - scale = max(0.68, min(1.15, (h - 110.0) / 340.0)) + scale = max(0.58, min(1.15, (h - 110.0) / 340.0)) + if rect.width() < 430.0: + scale *= 0.82 alpha_mul = 0.42 if dimmed else 1.0 def _c(r_v: int, g_v: int, b_v: int, a_v: int) -> QColor: @@ -307,15 +340,21 @@ class ClinicalTwinStageWidget(QWidget): ay = stage_rect.top() + stage_rect.height() * node.anchor_y anchor = QPointF(ax, ay) - card_w = min(204.0, max(154.0, stage_rect.width() * 0.32)) - card_h = 76.0 + compact = stage_rect.width() < 445.0 + edge_pad = 8.0 if compact else 16.0 + card_w = ( + min(126.0, max(92.0, stage_rect.width() * 0.34)) + if compact + else min(204.0, max(150.0, stage_rect.width() * 0.32)) + ) + card_h = 56.0 if compact else 76.0 cy = stage_rect.top() + stage_rect.height() * node.card_y - card_h * 0.5 - cy = max(stage_rect.top() + 58.0, min(stage_rect.bottom() - card_h - 54.0, cy)) + cy = max(stage_rect.top() + 54.0, min(stage_rect.bottom() - card_h - 50.0, cy)) if node.side == "left": - cx = stage_rect.left() + 16.0 + cx = stage_rect.left() + edge_pad line_start = QPointF(cx + card_w, cy + card_h * 0.5) else: - cx = stage_rect.right() - card_w - 16.0 + cx = stage_rect.right() - card_w - edge_pad line_start = QPointF(cx, cy + card_h * 0.5) card_rect = QRectF(cx, cy, card_w, card_h) @@ -329,21 +368,56 @@ class ClinicalTwinStageWidget(QWidget): dot_hex, pill_bg_hex, pill_fg_hex = tone_map.get(node.status_tone, tone_map["neutral"]) painter.setBrush(Qt.BrushStyle.NoBrush) - painter.setPen(QPen(QColor("#8BA29E"), 1.1, Qt.PenStyle.DashLine)) + painter.setPen(QPen(QColor("#8BA29E"), 1.0, Qt.PenStyle.DashLine)) painter.drawLine(line_start, anchor) painter.setPen(QPen(QColor("#FFFFFF"), 2.0)) painter.setBrush(QColor(dot_hex)) - painter.drawEllipse(anchor, 5.2, 5.2) + painter.drawEllipse(anchor, 4.6 if compact else 5.2, 4.6 if compact else 5.2) hovered = self._hover_target == f"locus:{node.locus_id}" cpath = QPainterPath() - cpath.addRoundedRect(card_rect, 15.0, 15.0) + cpath.addRoundedRect(card_rect, 12.0 if compact else 15.0, 12.0 if compact else 15.0) painter.setBrush(Qt.BrushStyle.NoBrush) painter.fillPath(cpath, QColor(255, 255, 255, 248 if hovered else 238)) painter.setPen(QPen(QColor("#0E6F5C" if hovered else "#DFEAE7"), 1.3 if hovered else 1.0)) painter.drawPath(cpath) + if compact: + # Compact 2-line callout: colored dot + short title + elided finding + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(dot_hex)) + painter.drawEllipse(QPointF(card_rect.left() + 10, card_rect.top() + 15), 3.6, 3.6) + + t_font = QFont(heading_family()) + t_font.setPixelSize(11) + t_font.setWeight(QFont.Weight.DemiBold) + painter.setFont(t_font) + painter.setPen(QColor("#11201E")) + short_title = node.title.split("·")[0].strip() if len(node.title) > 7 else node.title + elided_t = painter.fontMetrics().elidedText( + short_title, Qt.TextElideMode.ElideRight, int(max(36, card_w - 22)) + ) + painter.drawText( + QRectF(card_rect.left() + 17, card_rect.top() + 6, max(36.0, card_w - 23), 18), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + elided_t, + ) + + d_font = QFont(body_family()) + d_font.setPixelSize(10) + painter.setFont(d_font) + painter.setPen(QColor(pill_fg_hex if node.status_tone == "coral" else "#627875")) + elided_d = painter.fontMetrics().elidedText( + node.detail, Qt.TextElideMode.ElideRight, int(max(36, card_w - 16)) + ) + painter.drawText( + QRectF(card_rect.left() + 8, card_rect.top() + 29, max(36.0, card_w - 16), 18), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + elided_d, + ) + return card_rect + badge_font = QFont(body_family()) badge_font.setPixelSize(10) badge_font.setWeight(QFont.Weight.DemiBold) @@ -361,10 +435,13 @@ class ClinicalTwinStageWidget(QWidget): t_font.setWeight(QFont.Weight.DemiBold) painter.setFont(t_font) painter.setPen(QColor("#11201E")) + elided_title = painter.fontMetrics().elidedText( + node.title, Qt.TextElideMode.ElideRight, int(max(40, card_w - 22)) + ) painter.drawText( QRectF(card_rect.left() + 11, card_rect.top() + 32, card_w - 22, 18), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - node.title, + elided_title, ) d_font = QFont(body_family()) @@ -417,7 +494,9 @@ class ClinicalTwinStageWidget(QWidget): painter.drawEllipse(QPointF(cx, cy), r, r) # Top Segmented Mode Pill Island: [全身症候 / 病史用药 / 四诊处方] - pill_host = QRectF(rect.left() + 16, rect.top() + 14, 246, 34) + narrow_bar = rect.width() < 395.0 + pill_w = 198.0 if narrow_bar else 246.0 + pill_host = QRectF(rect.left() + (10 if narrow_bar else 16), rect.top() + 14, pill_w, 34) pill_host_path = QPainterPath() pill_host_path.addRoundedRect(pill_host, 17.0, 17.0) painter.fillPath(pill_host_path, QColor("#FFFFFF")) @@ -425,7 +504,7 @@ class ClinicalTwinStageWidget(QWidget): painter.drawPath(pill_host_path) mode_font = QFont(body_family()) - mode_font.setPixelSize(12) + mode_font.setPixelSize(11 if narrow_bar else 12) self._mode_rects.clear() seg_w = (pill_host.width() - 8.0) / len(_MODES) for idx, (m_key, m_label) in enumerate(_MODES): @@ -442,8 +521,10 @@ class ClinicalTwinStageWidget(QWidget): painter.drawText(m_rect, Qt.AlignmentFlag.AlignCenter, m_label) vm = self._snapshot.twin_for_mode(self._mode_key) if self._snapshot else None - chart_btn_w = 108.0 - self._open_chart_rect = QRectF(rect.right() - chart_btn_w - 16, rect.top() + 15, chart_btn_w, 32) + chart_btn_w = 82.0 if narrow_bar else 108.0 + self._open_chart_rect = QRectF( + rect.right() - chart_btn_w - (10 if narrow_bar else 16), rect.top() + 15, chart_btn_w, 32 + ) cb_path = QPainterPath() cb_path.addRoundedRect(self._open_chart_rect, 16.0, 16.0) cb_hover = self._hover_target == "open_chart" @@ -455,19 +536,26 @@ class ClinicalTwinStageWidget(QWidget): mode_font.setWeight(QFont.Weight.DemiBold) painter.setFont(mode_font) painter.setPen(QColor("#0E6F5C" if cb_hover else "#233836")) - painter.drawText(self._open_chart_rect, Qt.AlignmentFlag.AlignCenter, "原始详单 ↗") + painter.drawText( + self._open_chart_rect, + Qt.AlignmentFlag.AlignCenter, + "详单 ↗" if narrow_bar else "原始详单 ↗", + ) + self._scan_badge_rect = QRectF() if vm is not None and rect.width() >= 520: badge_w = 148.0 scan_rect = QRectF(self._open_chart_rect.left() - badge_w - 8, rect.top() + 15, badge_w, 32) + self._scan_badge_rect = scan_rect sp = QPainterPath() sp.addRoundedRect(scan_rect, 16.0, 16.0) - painter.fillPath(sp, QColor("#FFFFFF")) - painter.setPen(QPen(QColor("#E3ECE9"), 1.0)) + scan_hover = self._hover_target == "scan_date" + painter.fillPath(sp, QColor("#EBF6F3" if scan_hover else "#FFFFFF")) + painter.setPen(QPen(QColor("#9ED0C3" if scan_hover else "#E3ECE9"), 1.0)) painter.drawPath(sp) mode_font.setWeight(QFont.Weight.Normal) painter.setFont(mode_font) - painter.setPen(QColor("#5C7270")) + painter.setPen(QColor("#0E6F5C" if scan_hover else "#5C7270")) painter.drawText(scan_rect, Qt.AlignmentFlag.AlignCenter, vm.scan_badge) has_pat = bool(vm and vm.has_patient) @@ -509,24 +597,33 @@ class ClinicalTwinStageWidget(QWidget): vm.empty_subtitle if vm else "请在右侧队列点击任意患者以载入真实病历", ) elif vm is not None: + hovered_pair: tuple[TwinCalloutNode, QRectF] | None = None for node in vm.nodes: c_rect = self._draw_callout(painter, rect, node) self._callout_rects.append((node.locus_id, c_rect, node.full_tooltip)) + if self._hover_target == f"locus:{node.locus_id}" and node.full_tooltip: + hovered_pair = (node, c_rect) # Bottom Legend + Real Clinical Summary Capsule - leg_font = QFont(body_family()) - leg_font.setPixelSize(10) - painter.setFont(leg_font) - ly = rect.bottom() - 42 - for dot_c, txt, dy in (("#E06D4C", "实采阳性症状", 0.0), ("#0E6F5C", "已核未见异常", 16.0)): - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor(dot_c)) - painter.drawEllipse(QPointF(rect.left() + 22, ly + dy + 6), 3.4, 3.4) - painter.setPen(QColor("#5C726F")) - painter.drawText(QRectF(rect.left() + 31, ly + dy - 1, 86, 15), Qt.AlignmentFlag.AlignLeft, txt) - - cap_w = min(380.0, max(220.0, rect.width() - 180.0)) - cap_rect = QRectF(cx - cap_w * 0.5 + 24.0, rect.bottom() - 44, cap_w, 32) + show_legend = rect.width() >= 435.0 + if show_legend: + leg_font = QFont(body_family()) + leg_font.setPixelSize(10) + painter.setFont(leg_font) + ly = rect.bottom() - 42 + for dot_c, txt, dy in (("#E06D4C", "实采阳性症状", 0.0), ("#0E6F5C", "已核未见异常", 16.0)): + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(dot_c)) + painter.drawEllipse(QPointF(rect.left() + 22, ly + dy + 6), 3.4, 3.4) + painter.setPen(QColor("#5C726F")) + painter.drawText(QRectF(rect.left() + 31, ly + dy - 1, 86, 15), Qt.AlignmentFlag.AlignLeft, txt) + cap_w = min(380.0, max(180.0, rect.width() - 180.0)) + cap_rect = QRectF(cx - cap_w * 0.5 + 24.0, rect.bottom() - 44, cap_w, 32) + else: + cap_w = max(160.0, rect.width() - 24.0) + cap_rect = QRectF(rect.left() + 12.0, rect.bottom() - 42, cap_w, 30) + self._bottom_capsule_rect = cap_rect + self._active_popover = None wpath = QPainterPath() wpath.addRoundedRect(cap_rect, 16.0, 16.0) painter.setBrush(Qt.BrushStyle.NoBrush) @@ -554,3 +651,121 @@ class ClinicalTwinStageWidget(QWidget): Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, elided_bar, ) + + if vm is not None and vm.has_patient and "hovered_pair" in locals() and hovered_pair is not None: + self._draw_hover_popover(painter, rect, hovered_pair[0], hovered_pair[1]) + + def _draw_hover_popover( + self, + painter: QPainter, + stage_rect: QRectF, + node: TwinCalloutNode, + anchor_card: QRectF, + ) -> None: + """Paint an in-stage structured clinical detail card (never crosses outside the stage!).""" + + raw_parts = [ + p.strip() + for line in node.full_tooltip.splitlines() + for p in line.split(" · ") + if p.strip() + ] + if not raw_parts: + return + + pop_w = min(256.0, max(190.0, stage_rect.width() - 28.0)) + inner_w = pop_w - 28.0 + + body_font = QFont(body_family()) + body_font.setPixelSize(12) + painter.setFont(body_font) + fm = painter.fontMetrics() + + # Measure wrapped height for each structured bullet item + measured_items: list[tuple[str, float]] = [] + total_body_h = 0.0 + for part in raw_parts[:5]: + normalized = part.replace(":", ":") + bullet = f"• {normalized}" + bound = fm.boundingRect( + 0, 0, int(inner_w), 400, Qt.TextFlag.TextWordWrap, bullet + ) + item_h = max(18.0, float(bound.height()) + 4.0) + measured_items.append((bullet, item_h)) + total_body_h += item_h + 4.0 + + pop_h = 38.0 + total_body_h + 24.0 + # Place in center corridor ONLY when wide enough that opposite column callout is never touched; + # otherwise place cleanly below/above on the hovered card's own side! + corridor_w = stage_rect.width() - anchor_card.width() * 2.0 - 44.0 + if corridor_w >= pop_w + 16.0: + if node.side == "left": + px = anchor_card.right() + 10.0 + else: + px = anchor_card.left() - pop_w - 10.0 + px = max(stage_rect.left() + 14.0, min(stage_rect.right() - pop_w - 14.0, px)) + py = max( + stage_rect.top() + 52.0, + min(anchor_card.top(), stage_rect.bottom() - pop_h - 46.0), + ) + else: + px = anchor_card.left() if node.side == "left" else anchor_card.right() - pop_w + px = max(stage_rect.left() + 12.0, min(stage_rect.right() - pop_w - 12.0, px)) + if anchor_card.bottom() + 6.0 + pop_h <= stage_rect.bottom() - 44.0: + py = anchor_card.bottom() + 6.0 + else: + py = max(stage_rect.top() + 52.0, anchor_card.top() - pop_h - 6.0) + + pop_rect = QRectF(px, py, pop_w, pop_h) + self._active_popover = (node.locus_id, pop_rect) + + # Soft ambient drop shadow + shadow_path = QPainterPath() + shadow_path.addRoundedRect(pop_rect.adjusted(-1.0, 2.0, 1.0, 4.0), 15.0, 15.0) + painter.setPen(Qt.PenStyle.NoPen) + painter.fillPath(shadow_path, QColor(12, 26, 24, 38)) + + card_path = QPainterPath() + card_path.addRoundedRect(pop_rect, 14.0, 14.0) + painter.fillPath(card_path, QColor(20, 36, 34, 248)) + painter.setPen(QPen(QColor("#325D55"), 1.0)) + painter.drawPath(card_path) + + # Header + h_font = QFont(heading_family()) + h_font.setPixelSize(12) + h_font.setWeight(QFont.Weight.DemiBold) + painter.setFont(h_font) + painter.setPen(QColor("#8EE2CC")) + painter.drawText( + QRectF(pop_rect.left() + 14, pop_rect.top() + 9, inner_w, 18), + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + node.title, + ) + + painter.setPen(QPen(QColor(255, 255, 255, 28), 1.0)) + painter.drawLine( + QPointF(pop_rect.left() + 14, pop_rect.top() + 31), + QPointF(pop_rect.right() - 14, pop_rect.top() + 31), + ) + + # Structured bullet items + painter.setFont(body_font) + painter.setPen(QColor("#F1F7F5")) + opt = QTextOption(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop) + opt.setWrapMode(QTextOption.WrapMode.WordWrap) + cur_y = pop_rect.top() + 37.0 + for bullet_txt, item_h in measured_items: + painter.drawText(QRectF(pop_rect.left() + 14, cur_y, inner_w, item_h), bullet_txt, opt) + cur_y += item_h + 4.0 + + # Subtle action hint + f_font = QFont(body_family()) + f_font.setPixelSize(10) + painter.setFont(f_font) + painter.setPen(QColor("#88B2AA")) + painter.drawText( + QRectF(pop_rect.left() + 14, pop_rect.bottom() - 20, inner_w, 14), + Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, + "点击卡片编辑该部位病历 ↗", + ) diff --git a/app/src/doctor_workstation/video/window.py b/app/src/doctor_workstation/video/window.py index da074fb09..a85cf409f 100755 --- a/app/src/doctor_workstation/video/window.py +++ b/app/src/doctor_workstation/video/window.py @@ -58,6 +58,7 @@ try: # Optional by design: core-only builds must still import this module. QMainWindow, QPlainTextEdit, QPushButton, + QSizePolicy, QVBoxLayout, QWidget, ) @@ -452,8 +453,8 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration 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.resize(520 if self.open_im else 820, 740) + self.setMinimumSize(420, 480) self._profile = QWebEngineProfile(self) if not self._profile.isOffTheRecord(): @@ -480,28 +481,49 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration hud = QFrame(shell) hud.setObjectName("VideoCockpitHud") - hud.setFixedHeight(44) + hud.setFixedHeight(48) hud.setStyleSheet( - "QFrame#VideoCockpitHud { background: qlineargradient(x1:0,y1:0,x2:1,y2:0,stop:0 #0E2B2A,stop:1 #071919);" - " border-bottom: 1px solid rgba(223,199,147,96); }" - "QLabel { color: #EFF9F8; font-size: 13px; font-weight: 600; }" - "QPushButton { min-height: 28px; max-height: 28px; padding: 0 11px; border-radius: 7px;" - " background: rgba(255,255,255,22); border: 1px solid rgba(223,199,147,96);" - " color: #DFC793; font-size: 12px; font-weight: 600; }" - "QPushButton:hover { background: rgba(24,176,165,86); color: #FFFFFF; }" + "QFrame#VideoCockpitHud {" + " background: #F7FAF9;" + " border-top: 3px solid #0E6F5C;" + " border-bottom: 1px solid #DDEAE6;" + "}" + "QLabel#VideoHudModeBadge {" + " background: #E2F3EE; color: #0E6F5C; border-radius: 10px;" + " padding: 2px 9px; font-size: 11px; font-weight: 700;" + "}" + "QLabel#VideoHudPatientLabel {" + " color: #102422; font-size: 13px; font-weight: 600;" + "}" + "QPushButton {" + " min-height: 28px; max-height: 28px; padding: 0 11px; border-radius: 14px;" + " background: #FFFFFF; border: 1px solid #CFE2DD;" + " color: #18322F; font-size: 11.5px; font-weight: 600;" + "}" + "QPushButton:hover { background: #E3F3EE; border-color: #95CBC0; color: #0E6F5C; }" + "QPushButton:checked { background: #0E6F5C; border-color: #0E6F5C; color: #FFFFFF; }" ) hud_row = QHBoxLayout(hud) - hud_row.setContentsMargins(14, 0, 14, 0) - hud_row.setSpacing(10) - mode_tag = "IM 会话" if self.open_im else "高清视频面诊" - hud_row.addWidget(QLabel(f"● {mode_tag} · {self.patient_name}", hud)) - hud_row.addStretch(1) + hud_row.setContentsMargins(12, 0, 12, 0) + hud_row.setSpacing(8) + mode_tag = "IM 会话" if self.open_im else "视频面诊" + mode_badge = QLabel(f"● {mode_tag}", hud) + mode_badge.setObjectName("VideoHudModeBadge") + hud_row.addWidget(mode_badge) + + pat_lbl = QLabel(self.patient_name, hud) + pat_lbl.setObjectName("VideoHudPatientLabel") + pat_lbl.setToolTip(self.patient_name) + pat_lbl.setMinimumWidth(40) + pat_lbl.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) + hud_row.addWidget(pat_lbl, 1) + if callable(self._on_open_diagnosis): - diag_btn = QPushButton("打开完整诊单", hud) + diag_btn = QPushButton("四诊病历", hud) diag_btn.setCursor(Qt.CursorShape.PointingHandCursor) - diag_btn.clicked.connect(self._on_open_diagnosis) + diag_btn.clicked.connect(lambda _checked=False: self._open_diagnosis_safely()) hud_row.addWidget(diag_btn) - self._companion_toggle = QPushButton("四诊速记侧栏", hud) + self._companion_toggle = QPushButton("速记侧栏", hud) self._companion_toggle.setCheckable(True) self._companion_toggle.setCursor(Qt.CursorShape.PointingHandCursor) hud_row.addWidget(self._companion_toggle) @@ -513,7 +535,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration stage_row.addWidget(self.web_view, 1) self._companion_rail = QFrame(shell) - self._companion_rail.setFixedWidth(320) + self._companion_rail.setFixedWidth(248) self._companion_rail.setStyleSheet( "QFrame { background: #F4F9F8; border-left: 1px solid #C6DAD6; }" "QLabel { color: #102625; }" diff --git a/app/tests/test_spatial_cockpit_v3.py b/app/tests/test_spatial_cockpit_v3.py index 4837993d7..4762aa01c 100644 --- a/app/tests/test_spatial_cockpit_v3.py +++ b/app/tests/test_spatial_cockpit_v3.py @@ -1,9 +1,10 @@ -"""End-to-end verification of Clinical OS 3.0 Spatial Shell & Digital Twin Cockpit.""" +"""End-to-end verification of Clinical OS 3.0 Real-Data Cockpit & Spatial Shell.""" from __future__ import annotations import os from datetime import date, timedelta +from typing import Any os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") @@ -20,7 +21,7 @@ from doctor_workstation.ui.theme import apply_theme from doctor_workstation.ui.viewmodels import derive_cockpit_snapshot -def _settle(app: QApplication, rounds: int = 14) -> None: +def _settle(app: QApplication, rounds: int = 16) -> None: for _ in range(rounds): app.processEvents() QTest.qWait(8) @@ -61,45 +62,190 @@ def test_patient_context_store_broadcasts_snapshots_and_modes() -> None: assert seen_names[-1] == "未选择患者" -def test_cockpit_viewmodel_derives_three_jiao_journey_and_aurora_cards() -> None: +def test_empty_cockpit_snapshot_contains_zero_fabricated_metrics() -> None: + empty_vm = derive_cockpit_snapshot(active_ai_model="doubao") + assert empty_vm.has_patient is False + assert empty_vm.progression.primary_value == "—" + assert all(not bar.recorded for bar in empty_vm.progression.bars) + assert empty_vm.diurnal.primary_value == "—" + assert empty_vm.diurnal.has_marker is False + assert all(slot.state == "empty" for slot in empty_vm.diurnal.slots) + assert all(vital.value == "—" for vital in empty_vm.diurnal.vitals) + assert empty_vm.journey.primary_metric_text == "—" + assert empty_vm.aurora.active_model_key == "doubao" + assert empty_vm.aurora.gauge_value in {"0", "0/6", "—"} + + # Ensure zero legacy fake texts leak into empty state + serialized = repr(empty_vm) + for forbidden in ("76%", "84%", "92%", "-24%", "76 bpm", "舌红少津", "清热生津期"): + assert forbidden not in serialized + + +def test_cockpit_viewmodel_maps_real_clinical_records_and_ai_payload() -> None: + today = date.today() + d_minus_2 = (today - timedelta(days=2)).isoformat() + d_minus_1 = (today - timedelta(days=1)).isoformat() + today_iso = today.isoformat() + vm = derive_cockpit_snapshot( {"id": 11, "patient_name": "张建国", "status": 1}, {"height": 172, "weight": 78}, { "id": 511, - "hba1c": 7.6, + "clinical_diagnosis": "2型糖尿病(气阴两虚证)", "fasting_blood_sugar": 7.8, - "chief_complaint": "晨起口渴多饮,伴乏力夜尿频", - "tongue": "舌红少津", - "pulse": "脉弦细", - "diagnosis_date": (date.today() - timedelta(days=11)).isoformat(), + "postprandial_blood_sugar": 10.6, + "glycated_hemoglobin": 7.4, + "systolic_pressure": 136, + "diastolic_pressure": 84, + "chief_complaint": "口干多饮半年,加重两周", + "sleep_condition_text": "入睡困难、易醒", + "eye_condition_text": "视物模糊", + "water_intake_text": "2500ml以上", + "fatty_liver_degree_text": "中度脂肪肝", + "urine_condition_text": "夜尿3次", + "body_feeling_text": "双足末梢麻木", + "past_history_text": "高血压5年", + "current_medications": "二甲双胍缓释片 0.5g bid", + "allergy_history_text": "青霉素过敏", + "tongue": "舌质暗红苔薄黄", + "pulse": "脉弦细数", + "revisit_due": { + "visit_count": 2, + "medication_days": 14, + "medication_end_date": (today + timedelta(days=5)).isoformat(), + "days_offset": 5, + "status": "upcoming", + }, }, + daily_window={ + "blood_records": [ + { + "record_date": d_minus_2, + "fasting_blood_sugar": 8.4, + "postprandial_blood_sugar": 11.8, + }, + { + "record_date": d_minus_1, + "fasting_blood_sugar": 7.2, + "postprandial_blood_sugar": 9.6, + }, + { + "record_date": today_iso, + "fasting_blood_sugar": 6.6, + "postprandial_blood_sugar": 8.9, + "systolic_pressure": 128, + "diastolic_pressure": 78, + }, + ], + "diet_records": [{"record_date": d_minus_1, "breakfast_foods": ["燕麦", "鸡蛋"]}], + "exercise_records": [{"record_date": today_iso, "exercise_type": "快走", "duration": 35}], + }, + doctor_notes=[ + { + "content": "嘱晚间控主食,复查空腹。", + "tongue_images": ["/uploads/tongue1.jpg"], + "report_files": ["/uploads/lab1.pdf"], + } + ], + prescriptions=[ + { + "prescription_name": "生脉玉女煎加减", + "dosage_count": 14, + "audit_status_desc": "已双签通过", + } + ], ai_payload={ - "diagnosis_advice": "气阴两虚夹肝郁燥热,宜益气生津疏肝。", - "treatment_advice": "玉女煎合生脉散加减", - "risk_assessment": [{"label": "黎明血糖抬升", "level": "medium"}], + "diagnosis_advice": "患者口干多饮、夜尿频伴双足麻木,属气阴两虚夹瘀阻络。", + "treatment_advice": "益气养阴、活血通络,配合餐后30分钟中等强度步行。", + "risk_assessment": [ + {"label": "青霉素过敏史,严禁相关制剂", "level": "high"}, + {"label": "合并中度脂肪肝与周围神经麻木", "level": "medium"}, + ], + "generated_at": f"{today_iso} 09:20:00", }, - active_ai_model="qwen", + ai_state="success", + active_ai_model="doubao", ) + + assert vm.has_patient is True assert vm.patient_name == "张建国" - assert len(vm.progression.bars) == 12 - assert vm.progression.bars[-1].highlight is True - assert len(vm.diurnal.slots) == 16 - assert any(s.state == "alert" for s in vm.diurnal.slots) - assert len(vm.diurnal.vitals) == 3 + assert vm.progression.primary_value == "6.6" + assert vm.progression.unit == "mmol/L" + recorded_bars = [b for b in vm.progression.bars if b.recorded] + unrecorded_bars = [b for b in vm.progression.bars if not b.recorded] + assert len(recorded_bars) == 3 + assert len(unrecorded_bars) == 0 + assert all(bool(b.label) and bool(b.value_text) for b in recorded_bars) + assert recorded_bars[-1].highlight is True - sanjiao = vm.twin_for_mode("sanjiao") - assert sanjiao.upper_heat_intensity > 0.5 - assert sanjiao.middle_heat_intensity > 0.5 - assert sanjiao.lower_heat_intensity > 0.5 - assert len(vm.twin_for_mode("organ").nodes) == 2 - assert len(vm.twin_for_mode("tcm").nodes) == 2 + assert vm.diurnal.primary_value == "8.9" + assert vm.diurnal.has_marker is True + assert vm.diurnal.vitals[0].value == "128/78" + assert vm.diurnal.vitals[1].value == "26.4" + assert "二甲双胍" in vm.diurnal.vitals[2].value - assert vm.journey.total_days == 21 - assert vm.journey.current_day == 12 - assert sum(1 for d in vm.journey.days if d.state == "today") == 1 - assert len(vm.aurora.cards) == 3 - assert "气阴两虚" in vm.aurora.ai_summary_line + symptoms_stage = vm.twin_for_mode("sanjiao") + assert len(symptoms_stage.nodes) == 4 + assert any("双足末梢麻木" in n.detail for n in symptoms_stage.nodes) + + history_stage = vm.twin_for_mode("organ") + assert any("青霉素过敏" in n.detail for n in history_stage.nodes) + + tcm_stage = vm.twin_for_mode("tcm") + assert any("生脉玉女煎加减" in n.detail for n in tcm_stage.nodes) + + assert "3" in vm.journey.primary_metric_text + assert "第2诊" in vm.journey.end_capsule_text or "药尽" in vm.journey.end_capsule_text + assert vm.aurora.active_model_key == "doubao" + assert "6" in vm.aurora.gauge_value + assert "气阴两虚" in vm.aurora.cards[0].body_text + assert len(vm.aurora.cards[2].risk_items) == 2 + + +def test_spatial_shell_auto_fallback_to_consultations_when_appointments_empty( + application: QApplication, +) -> None: + """Verify admin account with 0 appointments automatically loads real clinic consultations.""" + + class AdminNoAppointmentsRepo(DemoDoctorRepository): + def list_appointments(self, *, page_no: int = 1, page_size: int = 20, **filters: Any): # type: ignore[override] + del filters + from doctor_workstation.core.models import PageResult + + return PageResult(items=(), total=0, page_no=page_no, page_size=page_size) + + repo = AdminNoAppointmentsRepo() + session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) + shell = SpatialShellWindow( + repo, + {"session": session, "user": session.user, "demo_mode": True}, + PermissionSet(DEMO_PERMISSIONS), + ) + shell.resize(1440, 900) + shell.show() + _settle(application, 28) + try: + rec_page = shell.pages["reception"] + assert rec_page._cockpit_queue_scope == "consultations" + assert len(rec_page._queue_records) > 0 + assert shell.patient_context_store.current_patient.has_patient + assert shell.patient_context_store.current_patient.diagnosis_id > 0 + + # Switch AI model tabs on bottom sheet and confirm immediate synchronization + shell.ai_bottom_sheet.model_selected.emit("doubao") + _settle(application, 6) + assert rec_page._ai_analysis_active_model == "doubao" + finally: + for page in shell.pages.values(): + poll = getattr(page, "poll_timer", None) + if poll is not None: + poll.stop() + shell.chat_notifications.stop() + shell.close() + shell.deleteLater() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + application.processEvents() def test_spatial_shell_zero_sidebar_cockpit_and_cross_page_flow( @@ -112,44 +258,50 @@ def test_spatial_shell_zero_sidebar_cockpit_and_cross_page_flow( {"session": session, "user": session.user, "demo_mode": True}, PermissionSet(DEMO_PERMISSIONS), ) - shell.resize(1600, 940) + shell.resize(1440, 920) shell.show() _settle(application, 24) try: - # 1. Zero-sidebar floating capsule nav defaults to reception Digital Twin Cockpit assert not hasattr(shell, "sidebar") assert shell._active_page_key == "reception" assert shell.nav_buttons["reception"].isChecked() + # Verify AI 辨证师 button has full sizeHint width & never overlaps search_capsule + assert shell.ai_nav_button.width() >= shell.ai_nav_button.sizeHint().width() + assert shell.nav_island.geometry().right() < shell.search_capsule.geometry().left() + rec_page = shell.pages["reception"] assert rec_page._workspace_mode == "cockpit" assert rec_page.view_mode_stack.currentWidget() is rec_page.cockpit_view assert shell.patient_context_store.current_patient.has_patient - active_name = shell.patient_context_store.current_patient.patient_name - assert active_name in shell.context_patient_name.text() - # Paint-test all custom QPainter widgets via grab() cockpit_img = shell.grab().toImage() assert not cockpit_img.isNull() - assert cockpit_img.width() >= 1600 - # 2. Switch Twin Stage modes (sanjiao -> organ -> tcm) + # Switch Twin Stage modes (sanjiao -> organ -> tcm) rec_page.cockpit_view.twin_stage.set_mode("organ") rec_page.cockpit_view.twin_stage.set_mode("tcm") rec_page.cockpit_view.twin_stage.set_mode("sanjiao") _settle(application, 4) - # 3. Switch to 6-tab Structured Chart and back to Digital Twin Cockpit - rec_page._open_structured_chart_tab(4) + # Open Structured Chart in Right Companion Wing without leaving Cockpit + rec_page._open_structured_chart_tab(3) + _settle(application, 4) + assert rec_page._workspace_mode == "cockpit" + assert shell.wing_manager.is_open + shell.wing_manager.close_wing() + _settle(application, 2) + + # Explicit legacy chart mode round-trip still works cleanly when invoked directly + rec_page.set_workspace_mode("chart") _settle(application, 4) assert rec_page._workspace_mode == "chart" assert rec_page._return_to_cockpit_bar.isVisible() - assert rec_page.detail_tabs.currentIndex() == 4 rec_page.set_workspace_mode("cockpit") _settle(application, 4) assert rec_page._workspace_mode == "cockpit" - # 4. Expand Serene.ai Obsidian Aurora-Glass Bottom Sheet + # Expand Obsidian Aurora-Glass Bottom Sheet assert not shell.ai_bottom_sheet.is_expanded shell.toggle_ai_bottom_sheet() _settle(application, 6) @@ -161,21 +313,15 @@ def test_spatial_shell_zero_sidebar_cockpit_and_cross_page_flow( _settle(application, 4) assert not shell.ai_bottom_sheet.is_expanded - # 5. Navigate to Schedule (AppointmentsPage) & verify 7-day WeekCalendarStripWidget + # Navigate to Schedule & other spatial routes assert shell.navigate("appointments") - _settle(application, 16) + _settle(application, 14) appt_page = shell.pages["appointments"] assert appt_page.spatial_week_card.isVisible() - assert not appt_page.header.isVisible() - tomorrow_iso = (date.today() + timedelta(days=1)).isoformat() - appt_page.week_strip.set_selected_date(date.today() + timedelta(days=1), emit_signal=True) - _settle(application, 10) - assert appt_page._start_date == tomorrow_iso - # 6. Navigate across Patients, Prescription Library, Prescriptions, Consultations for route_key in ("patients", "prescription_library", "prescriptions", "consultations"): assert shell.navigate(route_key) - _settle(application, 12) + _settle(application, 10) page = shell.pages[route_key] assert hasattr(page, "spatial_bridge") assert page.spatial_bridge.isVisible() diff --git a/app/tests/test_spatial_wings_v4.py b/app/tests/test_spatial_wings_v4.py new file mode 100644 index 000000000..e7a179a7c --- /dev/null +++ b/app/tests/test_spatial_wings_v4.py @@ -0,0 +1,500 @@ +"""End-to-end verification of Clinical OS 4.0 Dual-Wing Companion & Split-Stage Engine.""" + +from __future__ import annotations + +import os + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +import pytest +from PySide6.QtCore import QEvent, Qt, QTimer +from PySide6.QtTest import QTest +from PySide6.QtWidgets import QApplication, QDialog + +from doctor_workstation.core.permissions import PermissionSet +from doctor_workstation.services.demo_repository import DEMO_PERMISSIONS, DemoDoctorRepository +from doctor_workstation.ui.dialogs.appointment_complete import AppointmentCompleteDialog +from doctor_workstation.ui.dialogs.prescription import PrescriptionEditorDialog +from doctor_workstation.ui.shell_spatial import SpatialShellWindow +from doctor_workstation.ui.theme import apply_theme +from doctor_workstation.ui.visuals.ai_report_wing import ( + ClinicalAiReportWingPanel, + _extract_key_takeaways, + _split_evidence_rows, +) + + +def _settle(app: QApplication, rounds: int = 16) -> None: + for _ in range(rounds): + app.processEvents() + QTest.qWait(8) + + +@pytest.fixture(scope="module") +def application() -> QApplication: + app = QApplication.instance() or QApplication([]) + apply_theme(app) + return app + + +def test_ai_report_wing_extracts_tcm_takeaways_and_evidence_rows() -> None: + sample_advice = ( + "四诊:望诊见舌质偏红,舌苔黄腻(部分区域可见剥落),舌体略胖大,边有齿痕\n" + "闻诊未见异常记录\n" + "问诊见口干口苦,手脚偶发麻木,近期视物模糊、重影,腰酸\n" + "切诊脉象未采集\n" + "八纲:里证(病在脏腑)、热证(苔黄、口干口苦)、虚实夹杂\n" + "气血津液与脏腑定位:气阴两虚,湿热内蕴,病位主要在脾、肾、肝\n" + "证名:消渴病,气阴两虚兼湿热证" + ) + takeaways = _extract_key_takeaways(sample_advice) + assert len(takeaways) == 3 + assert takeaways[0][0] == "辨证证名" + assert "消渴病" in takeaways[0][1] + assert takeaways[1][0] == "八纲属性" + assert takeaways[2][0] == "病位病机" + assert "脾、肾、肝" in takeaways[2][1] + + rows = _split_evidence_rows(sample_advice) + badges = [r[0] for r in rows] + assert "望诊" in badges + assert "闻诊" in badges + assert "问诊" in badges + assert "切诊" in badges + assert "辨证结论" in badges + + # Also verify inline OpenAI bracketed wall-of-text splits into distinct structured sections + openai_wall = ( + "【已知事实】56岁男性,身高186 cm、体重70 kg,初诊空腹血糖11.00 mmol/L。" + "【合理推断】总体符合长期糖尿病伴血糖控制不稳定。" + "【信息缺口】缺少糖尿病明确分型、HbA1c及眼底检查。" + ) + o_rows = _split_evidence_rows(openai_wall) + o_badges = [r[0] for r in o_rows] + assert o_badges == ["已知事实", "临床推断", "待补信息"] + + +def test_spatial_wing_ai_report_left_right_dock_and_magnetic_sidecar( + application: QApplication, +) -> None: + repo = DemoDoctorRepository() + session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) + shell = SpatialShellWindow( + repo, + {"session": session, "user": session.user, "demo_mode": True}, + PermissionSet(DEMO_PERMISSIONS), + ) + shell.resize(1520, 920) + shell.show() + _settle(application, 24) + try: + # 1. Open AI Report Companion Wing via bottom sheet button (replaces ugly modal dialog!) + shell._open_active_patient_ai_report() + _settle(application, 8) + wm = shell.wing_manager + assert wm.is_open + assert wm.side == "right" + assert wm.mode == "docked" + assert shell.right_wing_dock.isVisible() + assert not shell.left_wing_dock.isVisible() + assert isinstance(wm.active_widget, ClinicalAiReportWingPanel) + + # Copy report uses clean inline feedback without giant center overlay + wm.active_widget._copy_current_report() + assert "已复制" in wm.active_widget.copy_btn.text() + + # 2. Switch wing to LEFT dock + wm.set_side("left") + _settle(application, 6) + assert wm.side == "left" + assert shell.left_wing_dock.isVisible() + assert not shell.right_wing_dock.isVisible() + + # Switch back to RIGHT dock + wm.set_side("right") + _settle(application, 6) + assert wm.side == "right" + assert shell.right_wing_dock.isVisible() + + # 3. Detach to external Magnetic Companion Sidecar Window & prove ZERO overlap! + wm.set_mode("sidecar") + _settle(application, 8) + assert wm.mode == "sidecar" + assert wm._sidecar is not None and wm._sidecar.isVisible() + assert not shell.right_wing_dock.isVisible() + assert shell.geometry().right() < wm._sidecar.geometry().left() + + # 4. Re-dock back into main window & verify clean restoration + wm.set_mode("docked") + _settle(application, 6) + assert wm.mode == "docked" + assert shell.right_wing_dock.isVisible() + assert not wm._sidecar.isVisible() + + wm.close_wing() + _settle(application, 4) + assert not wm.is_open + finally: + for page in shell.pages.values(): + if hasattr(page, "poll_timer"): + page.poll_timer.stop() + shell.chat_notifications.stop() + shell.close() + shell.deleteLater() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + application.processEvents() + + +def test_qdialogs_and_exec_callers_mount_non_modally_in_spatial_wing( + application: QApplication, +) -> None: + repo = DemoDoctorRepository() + session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) + shell = SpatialShellWindow( + repo, + {"session": session, "user": session.user, "demo_mode": True}, + PermissionSet(DEMO_PERMISSIONS), + ) + shell.resize(1520, 920) + shell.show() + _settle(application, 24) + try: + wm = shell.wing_manager + + # 1. Open DiagnosisDialog ('四诊病历') -> mounts full-bleed inside Right Wing! + shell._open_active_patient_diagnosis() + _settle(application, 12) + assert wm.is_open + assert wm.active_widget is shell._global_diagnosis_dialog + assert shell._global_diagnosis_dialog.property("hostedInSpatialWing") is True + assert shell.right_wing_dock.isVisible() + + # Close and reopen cached DiagnosisDialog -> must cleanly re-mount! + wm.close_wing() + _settle(application, 4) + assert not wm.is_open + shell._open_active_patient_diagnosis() + _settle(application, 8) + assert wm.is_open + assert wm.active_widget is shell._global_diagnosis_dialog + + # 2. Open PrescriptionEditorDialog via synchronous `.exec()` and reject asynchronously! + rx_dlg = PrescriptionEditorDialog( + repo, + {"diagnosis_id": 501, "patient_id": 301, "patient_name": "林晓岚"}, + mode="add", + current_user=session.user, + permissions=PermissionSet(DEMO_PERMISSIONS), + parent=shell, + ) + rx_errors: list[BaseException] = [] + + def _verify_and_close_rx() -> None: + try: + assert wm.is_open + assert wm.active_widget is rx_dlg + assert rx_dlg.property("hostedInSpatialWing") is True + assert not rx_dlg.isModal() + except BaseException as exc: # noqa: BLE001 + rx_errors.append(exc) + finally: + rx_dlg.reject() + + QTimer.singleShot(40, _verify_and_close_rx) + code = rx_dlg.exec() + if rx_errors: + raise rx_errors[0] + assert code == int(QDialog.DialogCode.Rejected) + assert not wm.is_open + + # 3. Test AppointmentCompleteDialog `.exec()` returning Accepted via Spatial Wing! + comp_dlg = AppointmentCompleteDialog(can_note=True, parent=shell) + QTimer.singleShot(30, comp_dlg.accept) + res = comp_dlg.exec() + assert res == int(QDialog.DialogCode.Accepted) + finally: + for page in shell.pages.values(): + if hasattr(page, "poll_timer"): + page.poll_timer.stop() + shell.chat_notifications.stop() + shell.close() + shell.deleteLater() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + application.processEvents() + + +def test_125dpi_rapid_switching_zero_overlap_and_fast_open( + application: QApplication, +) -> None: + """Reproduce 1920x1080 @ 125% DPI (1536x864) rapid wing switching & verify zero overlap.""" + import time + + from PySide6.QtWidgets import QScrollArea, QWidget + + repo = DemoDoctorRepository() + session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) + shell = SpatialShellWindow( + repo, + {"session": session, "user": session.user, "demo_mode": True}, + PermissionSet(DEMO_PERMISSIONS), + ) + shell.resize(1536, 864) + shell.show() + _settle(application, 28) + try: + rec = shell.pages["reception"] + wm = shell.wing_manager + + # Expand bottom sheet first, then open AI report wing -> bottom sheet must auto-collapse! + shell.set_ai_bottom_sheet_expanded(True) + assert shell.ai_bottom_sheet.is_expanded + + rec.open_ai_report_wing() + _settle(application, 6) + assert not shell.ai_bottom_sheet.is_expanded + + # Rapidly alternate between AI Report Wing and Edit Diagnosis 4 times + for _ in range(2): + t0 = time.perf_counter() + rec._edit_diagnosis() + dt_diag_ms = (time.perf_counter() - t0) * 1000.0 + _settle(application, 6) + + visible_body_children = [ + c + for c in wm.card.body_host.findChildren(QWidget, options=Qt.FindChildOption.FindDirectChildrenOnly) + if c.isVisible() and c is not wm.card.glide_veil + ] + assert len(visible_body_children) == 1 + assert visible_body_children[0] is shell._global_diagnosis_dialog + assert wm.card.header.title_label.text() == "编辑诊单" + + t1 = time.perf_counter() + rec.open_ai_report_wing() + dt_ai_ms = (time.perf_counter() - t1) * 1000.0 + _settle(application, 6) + + visible_body_children = [ + c + for c in wm.card.body_host.findChildren(QWidget, options=Qt.FindChildOption.FindDirectChildrenOnly) + if c.isVisible() and c is not wm.card.glide_veil + ] + assert len(visible_body_children) == 1 + assert isinstance(visible_body_children[0], ClinicalAiReportWingPanel) + assert dt_diag_ms < 180.0 + assert dt_ai_ms < 120.0 + + # Open Edit Diagnosis at 1536x864 and verify cockpit columns & past_history do NOT clip/overlap + rec._edit_diagnosis() + _settle(application, 10) + cockpit = rec.cockpit_view + twin_right = cockpit.twin_stage.mapTo(cockpit, cockpit.twin_stage.rect().topRight()).x() + plan_left = cockpit.plan_card.mapTo(cockpit, cockpit.plan_card.rect().topLeft()).x() + assert twin_right <= plan_left, f"TwinStage ({twin_right}) overlapped PlanCard ({plan_left})!" + + diag = shell._global_diagnosis_dialog + basic_scroll = diag.findChild(QScrollArea, "DiagnosisDrawerBody") + assert basic_scroll is not None + past_editor = diag._choice_fields["past_history"] + assert past_editor.width() <= basic_scroll.viewport().width() + + # Verify clicking '原始详单 ↗' opens DiagnosisDialog in Wing WITHOUT leaving Cockpit view! + wm.close_wing() + _settle(application, 4) + cockpit.open_chart_tab_requested.emit(0) + _settle(application, 8) + assert rec.view_mode_stack.currentWidget() is rec.cockpit_view + assert wm.is_open and wm.active_widget is shell._global_diagnosis_dialog + finally: + for page in shell.pages.values(): + if hasattr(page, "poll_timer"): + page.poll_timer.stop() + shell.chat_notifications.stop() + shell.close() + shell.deleteLater() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + application.processEvents() + + +def test_v4_3_calendar_density_patient_switch_sync_and_video_diagnosis_btn( + application: QApplication, +) -> None: + """Verify: (1) spacious 14d/7d calendar, (2) live Wing refresh on patient switch, (3) video 4-exam button.""" + + from PySide6.QtWidgets import QPushButton + + repo = DemoDoctorRepository() + session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) + shell = SpatialShellWindow( + repo, + {"session": session, "demo_mode": True}, + session.permissions, + ) + shell.resize(1536, 864) + shell.show() + _settle(application, 22) + + try: + rec = shell.pages["reception"] + wm = shell.wing_manager + journey_card = rec.cockpit_view.journey_card + + # 1. Full width: spacious 14-day rounded cards (every card >= 32px wide) + _ = shell.grab() + assert len(journey_card._day_rects) == 14 + assert all(r.width() >= 32.0 for r, _ in journey_card._day_rects) + + # 2. Open Edit Diagnosis for first patient (林晓岚, diagnosis_id=501) + rec._edit_diagnosis() + _settle(application, 14) + diag = shell._global_diagnosis_dialog + assert wm.is_open and wm.active_widget is diag + first_diag_id = diag._diagnosis_id + assert first_diag_id > 0 + + # When Right Wing narrows stage at 1536x864, calendar adapts to 7 spacious cards! + _ = shell.grab() + assert len(journey_card._day_rects) == 7 + assert all(r.width() >= 36.0 for r, _ in journey_card._day_rects) + + # Switch to the 2nd patient in queue while DiagnosisDialog stays open in Right Wing! + assert len(rec._queue_records) >= 2 + second_record = rec._queue_records[1] + second_name = str( + getattr(second_record, "patient_name", None) + or (second_record.get("patient_name") if isinstance(second_record, dict) else "") + or "" + ) + rec._select_record_from_cockpit(second_record) + _settle(application, 18) + + assert diag._diagnosis_id != first_diag_id + assert second_name and second_name in wm.card.header.context_badge.toolTip() + name_widget = diag.edit_fields.get("name") or diag.display_fields.get("name") + if name_widget is not None: + rendered_name = ( + name_widget.text() if hasattr(name_widget, "text") else name_widget.toPlainText() + ) + assert second_name in rendered_name + + # 3. Video/IM '四诊病历' QPushButton.clicked(bool=False) MUST NOT clobber diagnosis_id! + wm.close_wing() + _settle(application, 4) + target_diag_id = diag._diagnosis_id + callback = lambda *_args, current_id=target_diag_id: shell.open_diagnosis_by_id( # noqa: E731 + current_id, modeless=True + ) + fake_hud_btn = QPushButton("四诊病历") + fake_hud_btn.clicked.connect(lambda _checked=False: callback()) + fake_hud_btn.click() + _settle(application, 10) + assert wm.is_open and wm.active_widget is diag + assert diag._diagnosis_id == target_diag_id + + # Also verify open_diagnosis_by_id(False) safely falls back to active patient's diagnosis_id + wm.close_wing() + _settle(application, 4) + recovered = shell.open_diagnosis_by_id(False, modeless=True) + _settle(application, 8) + assert recovered is diag + assert diag._diagnosis_id == target_diag_id + finally: + for page in shell.pages.values(): + if hasattr(page, "poll_timer"): + page.poll_timer.stop() + shell.chat_notifications.stop() + shell.close() + shell.deleteLater() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + application.processEvents() + + +def test_v4_4_locus_deep_links_and_real_dated_data_only( + application: QApplication, +) -> None: + """Verify: (1) sparse patient renders ONLY real dated values (zero empty '—' or 11 blank bars), + (2) clicking each TwinStage card jumps straight to its matching tab & field in DiagnosisDialog.""" + + from doctor_workstation.ui.viewmodels.cockpit_vm import derive_cockpit_snapshot + + # 1. Sparse patient payload matching real-machine '王进花' screenshot + sparse_vm = derive_cockpit_snapshot( + appointment={ + "id": 88, + "diagnosis_id": 608, + "patient_name": "王进花", + "appointment_date": "2026-11-27", + "appointment_time": "17:30:00", + "diagnosis_type_text": "复诊", + }, + patient={"name": "王进花", "age": 67}, + diagnosis={ + "id": 608, + "patient_name": "王进花", + "diagnosis_date": 0, # Unset 0 timestamp must NEVER display '诊断日期 · 0' + "chief_complaint": "姓名:王进花\n年龄:67\n患者空腹血糖:空腹18\n在用药物:没有吃药\n患病时长:一年多", + }, + ) + assert sparse_vm.twin_sanjiao.scan_badge == "诊断日期 · 2026-11-27" + assert len(sparse_vm.progression.bars) == 1 + assert sparse_vm.progression.bars[0].value_text == "18" + assert sparse_vm.progression.bars[0].label == "11-27" + assert len(sparse_vm.diurnal.slots) == 0 + assert len(sparse_vm.diurnal.vitals) >= 2 + assert all(v.value != "—" and bool(v.date_label) for v in sparse_vm.diurnal.vitals) + assert any("没有吃药" in v.value for v in sparse_vm.diurnal.vitals) + assert any("一年多" in v.value for v in sparse_vm.diurnal.vitals) + + # 2. End-to-end Deep-Link Navigation across TwinStage cards & Glycemic cards + repo = DemoDoctorRepository() + session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) + shell = SpatialShellWindow( + repo, + {"session": session, "demo_mode": True}, + session.permissions, + ) + shell.resize(1536, 864) + shell.show() + _settle(application, 22) + + try: + rec = shell.pages["reception"] + cockpit = rec.cockpit_view + + # Click '下焦 · 腰肾二便与四肢' -> opens 'basic' tab & scrolls down to urine_condition + cockpit.locus_selected.emit("kidney_limbs") + _settle(application, 16) + diag = shell._global_diagnosis_dialog + assert shell.wing_manager.is_open and shell.wing_manager.active_widget is diag + assert diag._current_tab_key() == "basic" + assert diag._basic_scroll.verticalScrollBar().value() > 120 + + # Click '既往史与合并症' -> stays on 'basic' & scrolls down to past_history + cockpit.locus_selected.emit("past_history") + _settle(application, 10) + assert diag._current_tab_key() == "basic" + assert diag._basic_scroll.verticalScrollBar().value() > 180 + + # Click '医生备注与影像附件' -> switches directly to 'notes' tab + cockpit.locus_selected.emit("notes_media") + _settle(application, 8) + assert diag._current_tab_key() == "notes" + + # Click '本诊单电子处方记录' -> switches directly to 'prescription' tab + cockpit.locus_selected.emit("rx_summary") + _settle(application, 8) + assert diag._current_tab_key() == "prescription" + + # Click '空腹血糖监测' -> switches directly to 'daily' tab + cockpit.progression_card.open_daily_requested.emit() + _settle(application, 8) + assert diag._current_tab_key() == "daily" + finally: + for page in shell.pages.values(): + if hasattr(page, "poll_timer"): + page.poll_timer.stop() + shell.chat_notifications.stop() + shell.close() + shell.deleteLater() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + application.processEvents()