This commit is contained in:
Your Name
2026-11-30 16:52:45 +08:00
parent 621b7ddd39
commit 4cc37531a1
24 changed files with 7650 additions and 1630 deletions
+2 -2
View File
@@ -3,9 +3,9 @@
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
# Single source of truth for runtime, package, installer, and executable versions.
__version__ = "1.5.5"
__version__ = "1.5.6"
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
DEBUG_MODE = False
DEBUG_MODE = True
ONLINE_API_BASE_URL = "https://admin.zhenyangtang.com.cn"
+2 -2
View File
@@ -30,7 +30,7 @@ from doctor_workstation.services import (
TokenStore,
build_repository,
)
from doctor_workstation.ui import LoginWindow, ShellWindow, apply_theme
from doctor_workstation.ui import LoginWindow, ShellWindow, SpatialShellWindow, apply_theme
from doctor_workstation.ui.dialogs.app_update import AppUpdateSession
from doctor_workstation.ui.dialogs.video_cockpit import VideoCockpitDemoDialog as DemoVideoDialog
from doctor_workstation.ui.widgets import (
@@ -589,7 +589,7 @@ class ApplicationController(QObject):
self._authentication_expiry_in_progress = False
self.current_demo_mode = demo_mode
set_authentication_expired_handler(self._on_authentication_expired)
self.shell_window = ShellWindow(repository, payload, session.permissions)
self.shell_window = SpatialShellWindow(repository, payload, session.permissions)
self.shell_window.logout_requested.connect(self._logout)
self.shell_window.close_requested.connect(self.request_quit)
self.shell_window.video_requested.connect(self._request_video)
+2 -1
View File
@@ -2,6 +2,7 @@
from .login import LoginWindow
from .shell import ShellWindow
from .shell_spatial import SpatialShellWindow
from .theme import apply_theme
__all__ = ["LoginWindow", "ShellWindow", "apply_theme"]
__all__ = ["LoginWindow", "ShellWindow", "SpatialShellWindow", "apply_theme"]
File diff suppressed because it is too large Load Diff
@@ -72,7 +72,9 @@ from ..dialogs.prescription import (
from ..dialogs.prescription_esign import resume_saved_prescription, saved_prescription_message
from ..filter_disclosure import FilterDisclosure
from ..infinite_list import InfiniteList
from ..state import PatientContextStore
from ..theme import mark_business_dialog
from ..visuals.context_bridge_bar import SpatialContextBridgeBar
from ..widgets import (
MessageBanner,
PageHeader,
@@ -1117,8 +1119,10 @@ class ConsultationsPage(QWidget):
content.setAutoFillBackground(False)
self.page_scroll.setWidget(content)
page_layout = QVBoxLayout(content)
self._page_layout = page_layout
page_layout.setContentsMargins(27, 24, 26, 8)
page_layout.setSpacing(10)
self.patient_context_store: PatientContextStore | None = None
self.page_header = PageHeader(
"问诊列表",
@@ -1456,6 +1460,13 @@ class ConsultationsPage(QWidget):
page_layout.addWidget(filters)
self.filter_disclosure = FilterDisclosure(self, [filters])
self.page_header.add_action(self.filter_disclosure.button)
self.spatial_bridge = SpatialContextBridgeBar(
"全量四诊病历档案 · 支持视频二维码、预约排期与开方闭环",
on_filter_patient=self.search_patient,
parent=content,
)
self.spatial_bridge.setVisible(False)
page_layout.insertWidget(1, self.spatial_bridge)
card = QFrame()
card.setObjectName("DiagnosisListCard")
@@ -1961,6 +1972,14 @@ class ConsultationsPage(QWidget):
self.latest_appointment_end_date.setDate(_OPTIONAL_DATE_MINIMUM)
self.channel_combo.setCurrentIndex(0)
def set_patient_context_store(self, store: PatientContextStore) -> None:
self.patient_context_store = store
self._page_layout.setContentsMargins(2, 2, 2, 6)
self.page_header.setVisible(False)
self.spatial_bridge.bind_store(store)
self.spatial_bridge.add_action_widget(self.filter_disclosure.button)
self.spatial_bridge.setVisible(True)
def search_patient(self, query: str) -> None:
"""Search authorized diagnoses independently of the current queue filters."""
self.pager.invalidate()
+304 -272
View File
@@ -48,10 +48,10 @@ from ...core.appointment_modes import (
appointment_type_description,
appointment_type_value,
)
from ...core.esign import esign_status
from ...core.esign import esign_status
from .. import icons
from ..appointment_drawer import AppointmentDrawer
from ..design_system import PALETTE, clinical_stylesheet
from ..design_system import PALETTE, clinical_stylesheet
from ..dialogs import DiagnosisDialog, present_ai_consult, present_order_detail
from ..dialogs.ai_consult import can_open_ai_consult
from ..dialogs.prescription import PrescriptionOrderListDialog
@@ -68,7 +68,9 @@ from ..patient_orders_style import patient_orders_stylesheet
from ..patient_progress_style import patient_progress_stylesheet
from ..patients_style import patient_list_stylesheet, patients_chrome_stylesheet
from ..reception_style import body_family, heading_family
from ..state import PatientContextStore
from ..theme import mark_business_dialog
from ..visuals.context_bridge_bar import SpatialContextBridgeBar
from ..widgets import (
EmptyState,
MessageBanner,
@@ -119,97 +121,97 @@ FULFILLMENT_TEXT = {
}
_SEMANTIC_COLORS = {
"primary": PALETTE["accent"],
"success": PALETTE["success"],
"warning": PALETTE["warning"],
"danger": PALETTE["danger"],
"info": PALETTE["accent"],
"muted": PALETTE["muted"],
"primary": PALETTE["accent"],
"success": PALETTE["success"],
"warning": PALETTE["warning"],
"danger": PALETTE["danger"],
"info": PALETTE["accent"],
"muted": PALETTE["muted"],
}
PATIENTS_LIGHT_QSS = clinical_stylesheet("""
PATIENTS_LIGHT_QSS = clinical_stylesheet("""
#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] {
color: $ds_heading;
color: $ds_heading;
font-size: 20px;
font-weight: 600;
}
#PatientsPage QWidget#PageHeader QLabel[role="muted"] {
color: $ds_muted;
color: $ds_muted;
font-size: 13px;
}
#PatientsPage QPushButton[patientSearchAction="true"] {
min-height: 32px;
max-height: 32px;
color: $ds_surface;
background-color: $ds_accent;
border: 1px solid $ds_accent;
color: $ds_surface;
background-color: $ds_accent;
border: 1px solid $ds_accent;
border-radius: 7px;
font-weight: 500;
}
#PatientsPage QPushButton[patientSearchAction="true"]:hover {
background-color: $ds_accent_hover;
border-color: $ds_accent_hover;
background-color: $ds_accent_hover;
border-color: $ds_accent_hover;
}
#PatientsPage QFrame[patientListFilter="true"] {
min-height: 88px;
max-height: 88px;
background-color: $ds_surface;
border: 1px solid $ds_line;
background-color: $ds_surface;
border: 1px solid $ds_line;
border-radius: 12px;
}
#PatientsPage QFrame[patientListFilter="true"] QLineEdit,
#PatientsPage QFrame[patientListFilter="true"] QDateEdit {
min-height: 32px;
max-height: 32px;
background-color: $ds_surface;
border: 1px solid $ds_line;
background-color: $ds_surface;
border: 1px solid $ds_line;
border-radius: 7px; font-size: 14px;
}
#PatientsPage QFrame[patientListFilter="true"] QPushButton {
min-height: 32px; max-height: 32px;
}
#PatientsPage QFrame[patientListFilter="true"] QDateEdit:disabled {
color: $ds_disabled; background-color: $ds_surface_alt;
color: $ds_disabled; background-color: $ds_surface_alt;
}
#PatientsPage QPushButton[patientStatusChip="true"] {
min-height: 32px;
max-height: 32px;
padding: 0 10px;
color: $ds_muted;
background-color: $ds_surface_alt;
color: $ds_muted;
background-color: $ds_surface_alt;
border: 1px solid transparent;
border-radius: 5px;
}
#PatientsPage QPushButton[patientStatusChip="true"]:hover {
color: $ds_accent;
background-color: $ds_accent_soft;
color: $ds_accent;
background-color: $ds_accent_soft;
}
#PatientsPage QPushButton[patientStatusChip="true"]:checked {
color: $ds_accent;
background-color: $ds_accent_soft;
border: 1px solid $ds_focus;
color: $ds_accent;
background-color: $ds_accent_soft;
border: 1px solid $ds_focus;
}
#PatientsPage QPushButton[patientQuickDate="true"] {
min-height: 32px;
max-height: 32px;
padding: 0 9px;
color: $ds_heading;
color: $ds_heading;
background-color: transparent;
border: 1px solid transparent;
border-radius: 7px;
}
#PatientsPage QPushButton[patientQuickDate="true"]:hover {
color: $ds_accent;
background-color: $ds_accent_soft;
color: $ds_accent;
background-color: $ds_accent_soft;
}
#PatientsPage QPushButton[patientQuickDate="true"]:checked {
color: $ds_accent;
background-color: $ds_accent_soft;
border-color: $ds_focus;
color: $ds_accent;
background-color: $ds_accent_soft;
border-color: $ds_focus;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane {
border: 0;
border-top: 1px solid $ds_line;
border-top: 1px solid $ds_line;
background-color: transparent;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab {
@@ -217,124 +219,124 @@ PATIENTS_LIGHT_QSS = clinical_stylesheet("""
min-height: 34px;
padding: 0 6px;
margin-right: 8px;
color: $ds_muted;
color: $ds_muted;
background: transparent;
border: 0;
border-bottom: 2px solid transparent;
font-weight: 400;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:selected {
color: $ds_accent;
border-bottom-color: $ds_accent;
color: $ds_accent;
border-bottom-color: $ds_accent;
font-weight: 500;
}
#PatientsPage QPushButton[summaryCard="true"] {
min-height: 42px;
max-height: 42px;
padding: 0 11px;
color: $ds_heading;
background-color: $ds_surface_alt;
border: 1px solid $ds_line;
color: $ds_heading;
background-color: $ds_surface_alt;
border: 1px solid $ds_line;
border-radius: 9px;
text-align: left;
font-weight: 500;
}
#PatientsPage QPushButton[summaryCard="true"]:hover {
color: $ds_accent;
background-color: $ds_accent_soft;
border-color: $ds_focus;
color: $ds_accent;
background-color: $ds_accent_soft;
border-color: $ds_focus;
}
#PatientsPage QPushButton[rowAction="true"] {
min-height: 26px;
max-height: 26px;
padding: 0 7px;
color: $ds_accent;
background-color: $ds_surface;
border: 1px solid $ds_line;
color: $ds_accent;
background-color: $ds_surface;
border: 1px solid $ds_line;
border-radius: 6px;
font-size: 13px;
font-weight: 400;
}
#PatientsPage QPushButton[rowAction="true"]:hover {
background-color: $ds_accent_soft;
border-color: $ds_focus;
background-color: $ds_accent_soft;
border-color: $ds_focus;
}
#PatientsPage QPushButton[rowAction="true"][variant="danger"] {
color: $ds_danger;
background-color: $ds_danger_soft;
border-color: $ds_danger_soft;
color: $ds_danger;
background-color: $ds_danger_soft;
border-color: $ds_danger_soft;
}
#PatientsPage QTableWidget#PatientTable QHeaderView::section {
min-height: 34px;
background-color: $ds_surface_alt; font-size: 13px;
background-color: $ds_surface_alt; font-size: 13px;
}
#PatientsPage QTableWidget#PatientTable::item { padding: 5px 7px; }
#PatientsPage QTableWidget#PatientTable {
gridline-color: $ds_line;
selection-background-color: $ds_accent_soft;
selection-color: $ds_heading; font-size: 14px;
gridline-color: $ds_line;
selection-background-color: $ds_accent_soft;
selection-color: $ds_heading; font-size: 14px;
}
#PatientsPage QCheckBox[patientSelector="true"]::indicator {
width: 13px;
height: 13px;
background-color: $ds_surface;
border: 1px solid $ds_line;
background-color: $ds_surface;
border: 1px solid $ds_line;
border-radius: 2px;
}
#PatientsPage QCheckBox[patientSelector="true"]::indicator:checked {
background-color: $ds_accent;
border-color: $ds_accent;
background-color: $ds_accent;
border-color: $ds_accent;
}
#PatientsPage QPushButton[variant="ghost"]:checked {
color: $ds_accent;
background-color: $ds_accent_soft;
border: 1px solid $ds_accent;
color: $ds_accent;
background-color: $ds_accent_soft;
border: 1px solid $ds_accent;
}
#PatientsPage QPushButton[variant="ghost"]:checked:hover { background-color: $ds_accent_soft; }
#PatientsPage QPushButton[variant="ghost"]:checked:hover { background-color: $ds_accent_soft; }
#PatientsPage QPushButton[statusKind="info"]:checked {
color: $ds_accent;
border-color: $ds_accent;
color: $ds_accent;
border-color: $ds_accent;
}
#PatientsPage QPushButton[statusKind="warning"]:checked {
color: $ds_warning;
border-color: $ds_warning;
color: $ds_warning;
border-color: $ds_warning;
}
#PatientsPage QPushButton[statusKind="success"]:checked {
color: $ds_success;
border-color: $ds_success;
color: $ds_success;
border-color: $ds_success;
}
#PatientsPage QPushButton[statusKind="danger"]:checked {
color: $ds_danger;
border-color: $ds_danger;
color: $ds_danger;
border-color: $ds_danger;
}
#PatientsPage QLabel[metricKind="primary"] { color: $ds_accent; }
#PatientsPage QLabel[metricKind="info"] { color: $ds_accent; }
#PatientsPage QLabel[metricKind="success"] { color: $ds_success; }
#PatientsPage QLabel[metricKind="warning"] { color: $ds_warning; }
#PatientsPage QLabel[metricKind="danger"] { color: $ds_danger; }
#PatientsPage QLabel[metricKind="primary"] { color: $ds_accent; }
#PatientsPage QLabel[metricKind="info"] { color: $ds_accent; }
#PatientsPage QLabel[metricKind="success"] { color: $ds_success; }
#PatientsPage QLabel[metricKind="warning"] { color: $ds_warning; }
#PatientsPage QLabel[metricKind="danger"] { color: $ds_danger; }
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane {
background-color: transparent;
border: 0;
top: -1px;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab {
color: $ds_muted;
color: $ds_muted;
background-color: transparent;
border: 0;
border-bottom: 2px solid transparent;
font-weight: 400;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:hover {
color: $ds_accent;
background-color: $ds_accent_soft;
color: $ds_accent;
background-color: $ds_accent_soft;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:selected {
color: $ds_accent;
color: $ds_accent;
background-color: transparent;
border-bottom-color: $ds_accent;
border-bottom-color: $ds_accent;
font-weight: 500;
}
""")
""")
def _style_table_cell(table: SortableTable, row: int, column: int, kind: str) -> None:
@@ -513,8 +515,8 @@ class _LegacyAppointmentDialog(QDialog):
form = QFormLayout()
form.setVerticalSpacing(10)
self.appointment_type = QComboBox()
for label, value in APPOINTMENT_MODES:
self.appointment_type.addItem(label, value)
for label, value in APPOINTMENT_MODES:
self.appointment_type.addItem(label, value)
form.addRow("预约类型 *", self.appointment_type)
self.channel_source = QComboBox()
self.channel_source.addItem("正在加载渠道…", "")
@@ -1291,7 +1293,7 @@ class _PatientDateEdit(QDateEdit):
def paintEvent(self, event: Any) -> None:
super().paintEvent(event)
painter = QPainter(self)
glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 15)
glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 15)
painter.drawPixmap(QRectF(self.width() - 24, (self.height() - 15) / 2, 15, 15), glyph, QRectF(glyph.rect()))
painter.end()
@@ -1309,18 +1311,18 @@ class _PatientSummaryButton(QPushButton):
label, _, count = self.text().partition("\n")
left = max(18, (self.width() - 204) // 2)
icon_rect = QRectF(left, (self.height() - 36) / 2, 36, 36)
glyph = icons.pixmap("calendar", PALETTE["accent"], 36)
glyph = icons.pixmap("calendar", PALETTE["accent"], 36)
painter.drawPixmap(icon_rect, glyph, QRectF(glyph.rect()))
font = QFont(body_family())
font.setPixelSize(13)
painter.setFont(font)
painter.setPen(QColor(PALETTE["muted"]))
painter.setPen(QColor(PALETTE["muted"]))
text_rect = self.rect().adjusted(left + 46, 10, -12, -32)
painter.drawText(text_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
painter.fontMetrics().elidedText(label, Qt.TextElideMode.ElideRight, text_rect.width()))
font.setPixelSize(16)
painter.setFont(font)
painter.setPen(QColor(PALETTE["text"]))
painter.setPen(QColor(PALETTE["text"]))
painter.drawText(self.rect().adjusted(left + 46, 31, -12, -9),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, count)
painter.end()
@@ -1333,11 +1335,11 @@ class _PatientInfoDelegate(QStyledItemDelegate):
painter.save()
selected = bool(option.state & QStyle.StateFlag.State_Selected)
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
painter.setPen(QColor(PALETTE["line"]))
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
painter.setPen(QColor(PALETTE["line"]))
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
if selected and index.column() == 0:
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
if index.column() in (0, 9):
painter.restore()
return
@@ -1346,9 +1348,9 @@ class _PatientInfoDelegate(QStyledItemDelegate):
font = QFont(body_family())
font.setPixelSize(14)
painter.setFont(font)
painter.setPen(QColor(PALETTE["text"]))
painter.setPen(QColor(PALETTE["text"]))
def draw(text: str, target: Any, color: str = PALETTE["text"], centered: bool = False) -> None:
def draw(text: str, target: Any, color: str = PALETTE["text"], centered: bool = False) -> None:
painter.setPen(QColor(color))
text = painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, target.width())
alignment = Qt.AlignmentFlag.AlignVCenter | (Qt.AlignmentFlag.AlignHCenter if centered else Qt.AlignmentFlag.AlignLeft)
@@ -1368,33 +1370,33 @@ class _PatientInfoDelegate(QStyledItemDelegate):
doctor = display_text(first_value(row, "appointment_doctor_name"), "")
status, _kind = _patient_status(row)
if not doctor:
draw(status, rect, PALETTE["muted"])
draw(status, rect, PALETTE["muted"])
else:
draw(doctor, top)
font.setPixelSize(13)
painter.setFont(font)
color, fill = (PALETTE["warning"], PALETTE["warning_soft"]) if status == "已过号" else (PALETTE["accent"], PALETTE["accent_soft"])
color, fill = (PALETTE["warning"], PALETTE["warning_soft"]) if status == "已过号" else (PALETTE["accent"], PALETTE["accent_soft"])
if status == "已取消":
color, fill = PALETTE["muted"], PALETTE["canvas"]
color, fill = PALETTE["muted"], PALETTE["canvas"]
badge = QRectF(bottom.x(), bottom.y() + 1, min(bottom.width(), painter.fontMetrics().horizontalAdvance(status) + 10), 20)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(QColor(PALETTE["warning_soft"] if status == "已过号" else PALETTE["line_strong"]))
painter.setPen(QColor(PALETTE["warning_soft"] if status == "已过号" else PALETTE["line_strong"]))
painter.setBrush(QColor(fill))
painter.drawRoundedRect(badge, 3, 3)
draw(status, badge.toRect(), color, True)
elif index.column() == 4:
value = display_text(first_value(row, "appointment_time_text"))
date_text, separator, time_text = value.partition(" ")
if separator and time_text:
draw(date_text, top)
has_appointment = _as_int(first_value(row, "appointment_id", default=0)) > 0
mode = appointment_type_description(appointment_type_value(row)) if has_appointment else ""
draw(f"{time_text} · {mode}" if mode else time_text, bottom)
elif index.column() == 4:
value = display_text(first_value(row, "appointment_time_text"))
date_text, separator, time_text = value.partition(" ")
if separator and time_text:
draw(date_text, top)
has_appointment = _as_int(first_value(row, "appointment_id", default=0)) > 0
mode = appointment_type_description(appointment_type_value(row)) if has_appointment else ""
draw(f"{time_text} · {mode}" if mode else time_text, bottom)
else:
draw(value, rect)
else:
text = str(index.data(Qt.ItemDataRole.DisplayRole) or "")
draw(text, rect, PALETTE["warning"] if index.column() == 6 and text == "待确认" else PALETTE["text"], index.column() == 5)
draw(text, rect, PALETTE["warning"] if index.column() == 6 and text == "待确认" else PALETTE["text"], index.column() == 5)
painter.restore()
@@ -1502,7 +1504,7 @@ class PatientListWorkspace(QWidget):
self.keyword_edit.setMaximumWidth(360)
self.keyword_edit.setPlaceholderText("患者姓名 / 手机号 / 助理 / 医生")
self.keyword_edit.setClearButtonEnabled(True)
self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition)
self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition)
self.keyword_edit.returnPressed.connect(self.search)
search_row.addWidget(self.keyword_edit, 1)
self.status_label = QLabel("患者状态:")
@@ -1855,7 +1857,7 @@ class PatientListWorkspace(QWidget):
)
host = RowActions(row_actions, self.table)
if host.more_button is not None:
host.more_button.setIcon(icons.icon("chevron_down", PALETTE["muted"], 12))
host.more_button.setIcon(icons.icon("chevron_down", PALETTE["muted"], 12))
host.more_button.setIconSize(QSize(12, 12))
host.more_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
host.more_button.setLayoutDirection(Qt.LayoutDirection.RightToLeft)
@@ -2004,15 +2006,15 @@ class PatientListWorkspace(QWidget):
self.custom_date_button.setChecked(True)
self.search()
def reset_filters(self, *, keyword: str = "", refresh: bool = True) -> None:
self.keyword_edit.setText(keyword.strip())
def reset_filters(self, *, keyword: str = "", refresh: bool = True) -> None:
self.keyword_edit.setText(keyword.strip())
self.status_combo.setCurrentIndex(0)
for key, button in self.status_buttons.items():
button.setChecked(key == "")
self.set_date_mode("all", refresh=False)
self._page = 1
if refresh:
self.refresh()
self._page = 1
if refresh:
self.refresh()
def search(self) -> None:
if self._date_mode != "all" and self.start_date.date() > self.end_date.date():
@@ -2090,7 +2092,7 @@ class _OrderComboBox(QComboBox):
def paintEvent(self, event: Any) -> None:
super().paintEvent(event)
painter = QPainter(self)
glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14)
glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14)
painter.drawPixmap(QRectF(self.width() - 24, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
painter.end()
@@ -2099,7 +2101,7 @@ class _OrderActionButton(QToolButton):
def paintEvent(self, event: Any) -> None:
super().paintEvent(event)
painter = QPainter(self)
glyph = icons.pixmap("chevron_down", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14)
glyph = icons.pixmap("chevron_down", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14)
painter.drawPixmap(QRectF(self.width() - 23, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
painter.end()
@@ -2118,18 +2120,18 @@ class _OrderInfoDelegate(QStyledItemDelegate):
painter.setClipRect(option.rect)
selected = bool(option.state & QStyle.StateFlag.State_Selected)
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
painter.setPen(QColor(PALETTE["line"]))
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
painter.setPen(QColor(PALETTE["line"]))
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
if selected and index.column() == 0:
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
rect = option.rect.adjusted(16, 0, -12, -1)
font = QFont(body_family())
font.setPixelSize(14)
painter.setFont(font)
text = str(index.data(Qt.ItemDataRole.DisplayRole) or "—")
def draw(value: str, target: Any, color: str = PALETTE["text"], right: bool = False) -> None:
def draw(value: str, target: Any, color: str = PALETTE["text"], right: bool = False) -> None:
painter.setPen(QColor(color))
value = painter.fontMetrics().elidedText(value, Qt.TextElideMode.ElideRight, target.width())
painter.drawText(target, Qt.AlignmentFlag.AlignVCenter | (Qt.AlignmentFlag.AlignRight if right else Qt.AlignmentFlag.AlignLeft), value)
@@ -2149,7 +2151,7 @@ class _OrderInfoDelegate(QStyledItemDelegate):
font.setWeight(QFont.Weight.Normal)
font.setPixelSize(13)
painter.setFont(font)
draw(secondary, bottom, PALETTE["muted"])
draw(secondary, bottom, PALETTE["muted"])
else:
draw(text, rect)
elif column in (9, 11):
@@ -2158,7 +2160,7 @@ class _OrderInfoDelegate(QStyledItemDelegate):
draw(primary, top)
font.setPixelSize(13)
painter.setFont(font)
draw(("(" if column == 9 else "") + secondary, bottom, PALETTE["muted"])
draw(("(" if column == 9 else "") + secondary, bottom, PALETTE["muted"])
else:
draw(text, rect)
elif column in (4, 5, 6):
@@ -2169,10 +2171,10 @@ class _OrderInfoDelegate(QStyledItemDelegate):
else:
kind = "blue" if raw in {3, 5, 6, 7, 8, 11} else "danger" if raw in {4, 9, 10} else "warning" if raw in {1, 2, 12} else "neutral"
foreground, background, border = {
"blue": (PALETTE["accent"], PALETTE["accent_soft"], PALETTE["line_strong"]),
"warning": (PALETTE["warning"], PALETTE["warning_soft"], PALETTE["warning_soft"]),
"danger": (PALETTE["danger"], PALETTE["danger_soft"], PALETTE["danger_soft"]),
"neutral": (PALETTE["muted"], PALETTE["disabled_surface"], PALETTE["line"]),
"blue": (PALETTE["accent"], PALETTE["accent_soft"], PALETTE["line_strong"]),
"warning": (PALETTE["warning"], PALETTE["warning_soft"], PALETTE["warning_soft"]),
"danger": (PALETTE["danger"], PALETTE["danger_soft"], PALETTE["danger_soft"]),
"neutral": (PALETTE["muted"], PALETTE["disabled_surface"], PALETTE["line"]),
}[kind]
font.setPixelSize(13)
painter.setFont(font)
@@ -2286,7 +2288,7 @@ class PatientOrdersWorkspace(QWidget):
self.keyword_edit.setMinimumWidth(240)
self.keyword_edit.setPlaceholderText("订单号 / 患者 / 手机号 / 处方ID / 诊单ID")
self.keyword_edit.setClearButtonEnabled(True)
self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition)
self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition)
self.keyword_edit.returnPressed.connect(self.search)
self.filter_top_row.addWidget(self.keyword_edit, 1)
self.audit_host = QWidget()
@@ -2759,11 +2761,11 @@ class _ProgressInfoDelegate(QStyledItemDelegate):
painter.setClipRect(option.rect)
selected = bool(option.state & QStyle.StateFlag.State_Selected)
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
painter.setPen(QColor(PALETTE["line"]))
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
painter.setPen(QColor(PALETTE["line"]))
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
if selected and index.column() == 0:
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
rect = option.rect.adjusted(16, 0, -16, -1)
font = QFont(body_family())
font.setPixelSize(14)
@@ -2774,20 +2776,20 @@ class _ProgressInfoDelegate(QStyledItemDelegate):
painter.setFont(font)
raw_text = index.data(Qt.ItemDataRole.DisplayRole)
text = "" if raw_text is None else str(raw_text)
color = PALETTE["text"]
color = PALETTE["text"]
if not self.schedule and index.column() == 5 and text and text != "—":
row = index.data(Qt.ItemDataRole.UserRole)
status = str(first_value(row, "queue_status", default="") or "").lower()
color = {
"consulting": PALETTE["accent"], "next": PALETTE["accent_hover"],
"waiting": PALETTE["warning"], "missed": PALETTE["danger"],
}.get(status, PALETTE["muted"])
"consulting": PALETTE["accent"], "next": PALETTE["accent_hover"],
"waiting": PALETTE["warning"], "missed": PALETTE["danger"],
}.get(status, PALETTE["muted"])
painter.setPen(QColor(color))
alignment = Qt.AlignmentFlag.AlignVCenter
alignment |= Qt.AlignmentFlag.AlignHCenter if self.schedule and 1 <= index.column() <= 5 else Qt.AlignmentFlag.AlignLeft
painter.drawText(rect, alignment, painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, rect.width()))
if option.state & QStyle.StateFlag.State_HasFocus:
painter.setPen(QColor(PALETTE["focus"]))
painter.setPen(QColor(PALETTE["focus"]))
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
painter.restore()
@@ -2887,7 +2889,7 @@ class PatientProgressWorkspace(QWidget):
row = QHBoxLayout(frame)
row.setContentsMargins(0, 0, 0, 0)
row.setSpacing(0)
divider = QFrame(frame)
divider = QFrame(frame)
divider.setObjectName("ProgressMetricDivider")
divider.setFixedSize(1, 60)
divider.setVisible(key != "total")
@@ -3025,7 +3027,7 @@ class PatientProgressWorkspace(QWidget):
"appointment_time",
"预约时间",
95,
lambda value, row: f"{display_text(value)[:5]} · {appointment_type_description(appointment_type_value(row))}",
lambda value, row: f"{display_text(value)[:5]} · {appointment_type_description(appointment_type_value(row))}",
),
TableColumn(
"ahead_count",
@@ -3194,13 +3196,15 @@ class PatientsPage(QWidget):
self._detail_generation = 0
self._edit_generation = 0
self._assistant_generation = 0
self._order_review_generation = 0
self._order_review_generation = 0
root = QVBoxLayout(self)
root.setContentsMargins(28, 8, 26, 8)
root.setSpacing(0)
self.header = PageHeader("我的患者", "患者、挂号与诊单按当前角色和部门数据范围展示。")
self.header.set_compact(True)
self._root_layout = root
root.setContentsMargins(28, 8, 26, 8)
root.setSpacing(0)
self.patient_context_store: PatientContextStore | None = None
self.header = PageHeader("我的患者", "患者、挂号与诊单按当前角色和部门数据范围展示。")
self.header.set_compact(True)
self.scope_badge = StatusBadge("按权限加载", "neutral")
self.header.add_action(self.scope_badge)
self.refresh_button = QPushButton("刷新")
@@ -3211,40 +3215,40 @@ class PatientsPage(QWidget):
root.addWidget(self.header)
self.tabs = QTabWidget()
self.tabs.setObjectName("PatientWorkspaceTabs")
self.tabs.setMinimumHeight(0)
self.patient_workspace = PatientListWorkspace(repository, permissions)
self.order_workspace = PatientOrdersWorkspace(repository, permissions)
self.tabs.setObjectName("PatientWorkspaceTabs")
self.tabs.setMinimumHeight(0)
self.patient_workspace = PatientListWorkspace(repository, permissions)
self.order_workspace = PatientOrdersWorkspace(repository, permissions)
self.progress_workspace = PatientProgressWorkspace(repository)
self.tabs.addTab(self.patient_workspace, "患者列表")
self.tabs.addTab(self.order_workspace, "订单管理")
self.tabs.addTab(self.progress_workspace, "面诊进度")
root.addWidget(self.tabs, 1)
# Each tab keeps its own disclosure state and the existing filter values.
# The patient search toolbar stays with its filters at every window width.
self.filter_disclosures = (
FilterDisclosure(self, [
self.patient_workspace.search_toolbar,
self.patient_workspace.filter_card,
self.patient_workspace.summary_strip,
]),
FilterDisclosure(self, [
self.order_workspace.filter_card,
self.order_workspace.summary_strip,
]),
FilterDisclosure(self, [
self.progress_workspace.overview_card,
self.progress_workspace.schedule_card,
]),
)
for index, disclosure in enumerate(self.filter_disclosures):
disclosure.button.setProperty("workspaceIndex", index)
self.header.add_action(disclosure.button)
self._progress_splitter_sizes = [302, 222]
self.progress_workspace.splitter.splitterMoved.connect(self._remember_progress_sizes)
self.filter_disclosures[2].expanded_changed.connect(self._progress_details_changed)
self._progress_details_changed(False)
self.tabs.addTab(self.progress_workspace, "面诊进度")
root.addWidget(self.tabs, 1)
# Each tab keeps its own disclosure state and the existing filter values.
# The patient search toolbar stays with its filters at every window width.
self.filter_disclosures = (
FilterDisclosure(self, [
self.patient_workspace.search_toolbar,
self.patient_workspace.filter_card,
self.patient_workspace.summary_strip,
]),
FilterDisclosure(self, [
self.order_workspace.filter_card,
self.order_workspace.summary_strip,
]),
FilterDisclosure(self, [
self.progress_workspace.overview_card,
self.progress_workspace.schedule_card,
]),
)
for index, disclosure in enumerate(self.filter_disclosures):
disclosure.button.setProperty("workspaceIndex", index)
self.header.add_action(disclosure.button)
self._progress_splitter_sizes = [302, 222]
self.progress_workspace.splitter.splitterMoved.connect(self._remember_progress_sizes)
self.filter_disclosures[2].expanded_changed.connect(self._progress_details_changed)
self._progress_details_changed(False)
self.patient_workspace.diagnosis_requested.connect(self._open_diagnosis)
self.patient_workspace.ai_consult_requested.connect(self._open_ai_consult)
@@ -3260,54 +3264,82 @@ class PatientsPage(QWidget):
self.order_workspace.scope_changed.connect(self._set_scope)
self.progress_workspace.diagnosis_requested.connect(self._open_order_diagnosis)
self.progress_workspace.scope_changed.connect(self._set_scope)
self.spatial_bridge = SpatialContextBridgeBar(
"慢病全周期档案 · 患者列表、履约订单与面诊随访进度",
on_filter_patient=self.search_patient,
parent=self,
)
self.spatial_bridge.setVisible(False)
root.insertWidget(1, self.spatial_bridge)
if hasattr(self.patient_workspace, 'table'):
self.patient_workspace.table.itemSelectionChanged.connect(self._sync_selected_patient_to_store)
self.tabs.currentChanged.connect(self._workspace_changed)
self._workspace_changed(0)
def set_patient_context_store(self, store: PatientContextStore) -> None:
self.patient_context_store = store
self._root_layout.setContentsMargins(2, 2, 2, 4)
self._root_layout.setSpacing(10)
self.header.setVisible(False)
self.spatial_bridge.bind_store(store)
self.spatial_bridge.add_action_widget(self.refresh_button)
for disclosure in self.filter_disclosures:
self.spatial_bridge.add_action_widget(disclosure.button)
self._workspace_changed(self.tabs.currentIndex(), refresh=False)
self.spatial_bridge.setVisible(True)
def _sync_selected_patient_to_store(self) -> None:
if self.patient_context_store is None:
return
row = self.patient_workspace.table.current_data()
if row is not None:
self.patient_context_store.update_from_row(row)
def _set_scope(self, text: str) -> None:
current = self.tabs.currentWidget()
if current is self.sender() or getattr(current, "scope", None) == text:
self.scope_badge.set_status(text, "neutral")
def _workspace_changed(self, index: int, *, refresh: bool = True) -> None:
for workspace_index, disclosure in enumerate(self.filter_disclosures):
disclosure.button.setVisible(workspace_index == index)
self.scope_badge.setVisible(False)
def _workspace_changed(self, index: int, *, refresh: bool = True) -> None:
for workspace_index, disclosure in enumerate(self.filter_disclosures):
disclosure.button.setVisible(workspace_index == index)
self.scope_badge.setVisible(False)
self.progress_workspace.set_active(index == 2 and self.isVisible())
workspace = self.tabs.widget(index)
scope = getattr(workspace, "scope", "按权限加载")
self.scope_badge.set_status(str(scope), "neutral")
reload_workspace = getattr(workspace, "refresh", None)
if refresh and callable(reload_workspace) and self.isVisible():
reload_workspace()
reload_workspace = getattr(workspace, "refresh", None)
if refresh and callable(reload_workspace) and self.isVisible():
reload_workspace()
@property
def filter_disclosure(self) -> FilterDisclosure:
return self.filter_disclosures[self.tabs.currentIndex()]
def _remember_progress_sizes(self, _position: int, _index: int) -> None:
if self.filter_disclosures[2].expanded:
self._progress_splitter_sizes = self.progress_workspace.splitter.sizes()
def _progress_details_changed(self, expanded: bool) -> None:
splitter = self.progress_workspace.splitter
# A hidden schedule must release the splitter's old two-panel minimum.
splitter.setMinimumHeight(536 if expanded else 222)
if expanded:
splitter.setSizes(self._progress_splitter_sizes)
@property
def filter_disclosure(self) -> FilterDisclosure:
return self.filter_disclosures[self.tabs.currentIndex()]
def _remember_progress_sizes(self, _position: int, _index: int) -> None:
if self.filter_disclosures[2].expanded:
self._progress_splitter_sizes = self.progress_workspace.splitter.sizes()
def _progress_details_changed(self, expanded: bool) -> None:
splitter = self.progress_workspace.splitter
# A hidden schedule must release the splitter's old two-panel minimum.
splitter.setMinimumHeight(536 if expanded else 222)
if expanded:
splitter.setSizes(self._progress_splitter_sizes)
def search_patient(self, query: str) -> None:
"""Search the patient workspace using its normal permission-scoped endpoint."""
blocked = self.tabs.blockSignals(True)
try:
self.tabs.setCurrentWidget(self.patient_workspace)
finally:
self.tabs.blockSignals(blocked)
self._workspace_changed(0, refresh=False)
# A global search starts a fresh result list, even for the same keyword.
self.patient_workspace.pager.invalidate()
self.patient_workspace.reset_filters(keyword=query, refresh=False)
self.refresh()
def search_patient(self, query: str) -> None:
"""Search the patient workspace using its normal permission-scoped endpoint."""
blocked = self.tabs.blockSignals(True)
try:
self.tabs.setCurrentWidget(self.patient_workspace)
finally:
self.tabs.blockSignals(blocked)
self._workspace_changed(0, refresh=False)
# A global search starts a fresh result list, even for the same keyword.
self.patient_workspace.pager.invalidate()
self.patient_workspace.reset_filters(keyword=query, refresh=False)
self.refresh()
def refresh(self) -> None:
workspace = self.tabs.currentWidget()
refresh = getattr(workspace, "refresh", None)
@@ -3657,69 +3689,69 @@ class PatientsPage(QWidget):
if generation == self._edit_generation:
self.order_workspace.banner.show_message(friendly_error(error), "danger")
def _submit_order_audit(self, order_id: int, *, prescription: bool, action: str) -> None:
label = "处方审核" if prescription else "支付单审核"
remark, accepted = QInputDialog.getText(self, label, "审核备注:")
if not accepted:
return
if action == "reject" and not remark.strip():
show_toast(self, "驳回时必须填写审核意见。", "danger")
return
method = "audit_patient_order_prescription" if prescription else "audit_patient_order_payment"
self._run_action(
"正在处理订单…",
lambda: _invoke_first(
self.repository, (method,), order_id=order_id, action=action, remark=remark.strip()
),
success=f"{label}已提交。",
)
def _check_order_signature_before_approval(self, row: Any, order_id: int) -> None:
status_method = getattr(self.repository, "get_prescription_esign_status", None)
if not callable(status_method):
self._submit_order_audit(order_id, prescription=True, action="approve")
return
prescription_id = _as_int(first_value(row, "prescription_id"))
if prescription_id <= 0:
self.order_workspace.banner.show_message("找不到此订单的处方,请刷新订单后重试。", "warning")
return
self._order_review_generation += 1
generation = self._order_review_generation
self.order_workspace.banner.show_message("正在核对关联处方的签署状态…", "info")
def failed(error: Exception) -> None:
if self._order_review_generation == generation:
self.order_workspace.banner.show_message(f"未能核对签署状态。{friendly_error(error)}", "warning")
def checked(state: dict[str, Any]) -> None:
if self._order_review_generation != generation:
return
def _submit_order_audit(self, order_id: int, *, prescription: bool, action: str) -> None:
label = "处方审核" if prescription else "支付单审核"
remark, accepted = QInputDialog.getText(self, label, "审核备注:")
if not accepted:
return
if action == "reject" and not remark.strip():
show_toast(self, "驳回时必须填写审核意见。", "danger")
return
method = "audit_patient_order_prescription" if prescription else "audit_patient_order_payment"
self._run_action(
"正在处理订单…",
lambda: _invoke_first(
self.repository, (method,), order_id=order_id, action=action, remark=remark.strip()
),
success=f"{label}已提交。",
)
def _check_order_signature_before_approval(self, row: Any, order_id: int) -> None:
status_method = getattr(self.repository, "get_prescription_esign_status", None)
if not callable(status_method):
self._submit_order_audit(order_id, prescription=True, action="approve")
return
prescription_id = _as_int(first_value(row, "prescription_id"))
if prescription_id <= 0:
self.order_workspace.banner.show_message("找不到此订单的处方,请刷新订单后重试。", "warning")
return
self._order_review_generation += 1
generation = self._order_review_generation
self.order_workspace.banner.show_message("正在核对关联处方的签署状态…", "info")
def failed(error: Exception) -> None:
if self._order_review_generation == generation:
self.order_workspace.banner.show_message(f"未能核对签署状态。{friendly_error(error)}", "warning")
def checked(state: dict[str, Any]) -> None:
if self._order_review_generation != generation:
return
if review_submission_time(row, state) == 0:
self.order_workspace.banner.show_message("请开方医生上传处方后再审核。", "warning")
return
verified = state["required"] and state["status"] == "signed" and state["can_download"]
historical = not state["required"] and state["status"] == "legacy" and not state["can_download"]
verified = state["required"] and state["status"] == "signed" and state["can_download"]
historical = not state["required"] and state["status"] == "legacy" and not state["can_download"]
if verified and state.get("review_required") is True and not review_signature_time(state):
self.order_workspace.banner.show_message("请先在管理后台完成药师审核签署,再提交审核通过。", "warning")
return
if verified or historical:
self.order_workspace.banner.clear()
self._submit_order_audit(order_id, prescription=True, action="approve")
return
if verified or historical:
self.order_workspace.banner.clear()
self._submit_order_audit(order_id, prescription=True, action="approve")
return
if can_continue_prescription_esign(state, self.permissions, row):
dialog = PrescriptionEsignDialog(self.repository, {"id": prescription_id, "esign": state}, parent=self)
dialog.exec()
self.order_workspace.banner.show_message("请在签署验签通过后,再点击处方审核。", "info")
self.order_workspace.refresh(silent=True)
else:
message = state.get("message") or (
"签署原件暂不可用,请联系管理员核验。" if state["status"] == "signed"
else "请开方医生完成处方签署并通过验签,再审核通过。"
)
self.order_workspace.banner.show_message(str(message), "warning")
run_async(lambda: esign_status(status_method(prescription_id)), on_success=checked, on_error=failed)
dialog = PrescriptionEsignDialog(self.repository, {"id": prescription_id, "esign": state}, parent=self)
dialog.exec()
self.order_workspace.banner.show_message("请在签署验签通过后,再点击处方审核。", "info")
self.order_workspace.refresh(silent=True)
else:
message = state.get("message") or (
"签署原件暂不可用,请联系管理员核验。" if state["status"] == "signed"
else "请开方医生完成处方签署并通过验签,再审核通过。"
)
self.order_workspace.banner.show_message(str(message), "warning")
run_async(lambda: esign_status(status_method(prescription_id)), on_success=checked, on_error=failed)
def _handle_order_action(self, key: str, row: Any) -> None:
allowed_keys = {item[0] for item in self.order_workspace._available_actions(row)}
if key not in allowed_keys:
@@ -3735,20 +3767,20 @@ class PatientsPage(QWidget):
call: Any
success = "订单已更新。"
if key in {"audit_prescription", "audit_payment"}:
self._order_review_generation += 1
prescription = key == "audit_prescription"
label = "处方审核" if prescription else "支付单审核"
self._order_review_generation += 1
prescription = key == "audit_prescription"
label = "处方审核" if prescription else "支付单审核"
action_label, accepted = QInputDialog.getItem(
self, label, "审核结果:", ["通过", "驳回"], 0, False
)
if not accepted:
return
action = "approve" if action_label == "通过" else "reject"
if prescription and action == "approve":
self._check_order_signature_before_approval(row, order_id)
else:
self._submit_order_audit(order_id, prescription=prescription, action=action)
return
if prescription and action == "approve":
self._check_order_signature_before_approval(row, order_id)
else:
self._submit_order_audit(order_id, prescription=prescription, action=action)
return
elif key in {"revoke_rx_audit", "revoke_pay_audit", "withdraw", "upload_pharmacy"}:
labels = {
"revoke_rx_audit": "撤回处方审核",
@@ -3891,7 +3923,7 @@ class PatientsPage(QWidget):
self.refresh()
def hideEvent(self, event: Any) -> None:
self._order_review_generation += 1
self._order_review_generation += 1
self.progress_workspace.set_active(False)
super().hideEvent(event)
@@ -24,7 +24,7 @@ from PySide6.QtWidgets import (
)
from .. import motion
from ..design_system import PALETTE
from ..design_system import PALETTE
from ..dialogs.prescription import PrescriptionTemplateDialog
from ..dialogs.prescription_ai import PrescriptionAiReportDialog, can_open_ai_explain
from ..filter_disclosure import FilterDisclosure
@@ -36,6 +36,8 @@ from ..prescription_library_style import (
library_stylesheet,
)
from ..reception_style import body_family
from ..state import PatientContextStore
from ..visuals.context_bridge_bar import SpatialContextBridgeBar
from ..widgets import (
EmptyState,
MessageBanner,
@@ -120,7 +122,7 @@ def _metric_card(title: str, kind: str = "accent", glyph: str = "layers") -> Met
icon.setProperty("metricIcon", True)
icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
icon.setFixedSize(32, 32)
color = PALETTE["accent"] if kind == "accent" else PALETTE["muted"]
color = PALETTE["accent"] if kind == "accent" else PALETTE["muted"]
icon.setPixmap(_painted_icon(glyph, color, 25).pixmap(25, 25))
card.layout().addWidget(icon)
return card
@@ -153,7 +155,9 @@ class PrescriptionLibraryPage(QWidget):
self._page_size = 15
outer = QVBoxLayout(self)
self._outer_layout = outer
outer.setContentsMargins(28, 16, 26, 8)
self.patient_context_store: PatientContextStore | None = None
self.scroll = QScrollArea()
self.scroll.setObjectName("PrescriptionLibraryScroll")
self.scroll.setWidgetResizable(True)
@@ -163,7 +167,7 @@ class PrescriptionLibraryPage(QWidget):
self.content.setObjectName("PrescriptionLibraryContent")
root = QVBoxLayout(self.content)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(10)
root.setSpacing(10)
self.scroll.setWidget(self.content)
outer.addWidget(self.scroll)
header = PageHeader(
@@ -188,8 +192,8 @@ class PrescriptionLibraryPage(QWidget):
header.add_action(self.new_button)
root.addWidget(header)
self.metrics_panel = QWidget(self.content)
metrics = QHBoxLayout(self.metrics_panel)
self.metrics_panel = QWidget(self.content)
metrics = QHBoxLayout(self.metrics_panel)
metrics.setContentsMargins(0, 0, 0, 0)
metrics.setSpacing(16)
self.metric_cards = {
@@ -200,7 +204,7 @@ class PrescriptionLibraryPage(QWidget):
}
for metric in self.metric_cards.values():
metrics.addWidget(metric)
root.addWidget(self.metrics_panel)
root.addWidget(self.metrics_panel)
self.hint_banner = MessageBanner(parent=self)
self.hint_banner.show_message(
@@ -260,10 +264,16 @@ class PrescriptionLibraryPage(QWidget):
grid.setColumnStretch(1, 1)
grid.setColumnStretch(2, 1)
grid.setColumnStretch(3, 1)
root.addWidget(filters)
self.filter_disclosure = FilterDisclosure(self, [self.metrics_panel, filters])
header.add_action(self.filter_disclosure.button)
header.set_compact()
root.addWidget(filters)
self.filter_disclosure = FilterDisclosure(self, [self.metrics_panel, filters])
header.add_action(self.filter_disclosure.button)
header.set_compact()
self.spatial_bridge = SpatialContextBridgeBar(
"专科经方与协定处方智库 · 支持 AI 配伍解析与快速调取",
parent=self.content,
)
self.spatial_bridge.setVisible(False)
root.insertWidget(1, self.spatial_bridge)
self.banner = MessageBanner()
root.addWidget(self.banner)
@@ -399,7 +409,7 @@ class PrescriptionLibraryPage(QWidget):
if hasattr(self, "filter_grid"):
compact_height = self.height() < 760
self.layout().setContentsMargins(28, 16, 26, 8)
self.content.layout().setSpacing(8 if compact_height else 10)
self.content.layout().setSpacing(8 if compact_height else 10)
self._reflow_filters()
def _reflow_filters(self) -> None:
@@ -544,7 +554,7 @@ class PrescriptionLibraryPage(QWidget):
name_item = self.table.item(row_index, 1)
if name_item is not None:
name_item.setForeground(QColor(PALETTE["heading"]))
name_item.setForeground(QColor(PALETTE["heading"]))
font = name_item.font()
font.setWeight(QFont.Weight.Medium)
name_item.setFont(font)
@@ -671,6 +681,16 @@ class PrescriptionLibraryPage(QWidget):
role_ids = [role_ids]
return any(str(role) in {"0", "3"} for role in role_ids)
def set_patient_context_store(self, store: PatientContextStore) -> None:
self.patient_context_store = store
self._outer_layout.setContentsMargins(2, 2, 2, 4)
self.header.setVisible(False)
self.spatial_bridge.bind_store(store)
if has_permission(self.permissions, 'wcf.prescription/add'):
self.spatial_bridge.add_action_widget(self.new_button)
self.spatial_bridge.add_action_widget(self.filter_disclosure.button)
self.spatial_bridge.setVisible(True)
def _new_template(self) -> None:
if not has_permission(self.permissions, "wcf.prescription/add"):
return
File diff suppressed because it is too large Load Diff
@@ -92,7 +92,10 @@ 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 ..state import PatientContextStore
from ..theme import mark_business_dialog
from ..viewmodels.cockpit_vm import derive_cockpit_snapshot
from ..visuals.reception_cockpit import ReceptionDigitalTwinCockpit
from ..widgets import (
EmptyState,
MessageBanner,
@@ -4152,6 +4155,7 @@ class ReceptionPage(QWidget):
"""Run the complete same-day reception workflow without blocking Qt."""
video_requested = Signal(dict)
cockpit_snapshot_updated = Signal(object)
def __init__(
self,
@@ -4265,8 +4269,48 @@ class ReceptionPage(QWidget):
)
root = QVBoxLayout(self)
self._root_layout = root
root.setContentsMargins(12, 16, 12, 12)
root.setSpacing(0)
self.patient_context_store: PatientContextStore | None = None
self._workspace_mode = "chart"
self._latest_daily_blood: list[Any] = []
self.view_mode_stack = QStackedWidget(self)
self.view_mode_stack.setObjectName("ReceptionViewModeStack")
chart_page = QWidget(self.view_mode_stack)
chart_page.setObjectName("ReceptionChartModePage")
chart_layout = QVBoxLayout(chart_page)
chart_layout.setContentsMargins(0, 0, 0, 0)
chart_layout.setSpacing(8)
self._return_to_cockpit_bar = QFrame(chart_page)
self._return_to_cockpit_bar.setObjectName("ReceptionReturnCockpitBar")
self._return_to_cockpit_bar.setFixedHeight(38)
self._return_to_cockpit_bar.setVisible(False)
self._return_to_cockpit_bar.setStyleSheet(
"QFrame#ReceptionReturnCockpitBar {"
" background-color: #FFFFFF; border: 1px solid #DCE7E4; border-radius: 19px; }"
)
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.setCursor(Qt.CursorShape.PointingHandCursor)
back_cockpit_btn.setStyleSheet(
"QPushButton { background-color: #0E6F5C; color: #FFFFFF; border: 0;"
" border-radius: 14px; padding: 0 14px; min-height: 28px; max-height: 28px;"
" font-size: 12px; font-weight: 600; }"
"QPushButton:hover { background-color: #0A5949; }"
)
back_cockpit_btn.clicked.connect(lambda: self.set_workspace_mode("cockpit"))
ret_layout.addWidget(back_cockpit_btn)
ret_hint = QLabel("当前处于「六维结构化病历与附件归档」详细视图", self._return_to_cockpit_bar)
ret_hint.setStyleSheet("color: #5E7471; font-size: 12px; background: transparent; border: 0;")
ret_layout.addWidget(ret_hint)
ret_layout.addStretch(1)
chart_layout.addWidget(self._return_to_cockpit_bar)
splitter = QSplitter(Qt.Orientation.Horizontal)
splitter.setChildrenCollapsible(False)
@@ -4278,7 +4322,23 @@ class ReceptionPage(QWidget):
splitter.setStretchFactor(1, 1)
splitter.setHandleWidth(12)
splitter.setSizes([286, 1185])
root.addWidget(splitter, 1)
chart_layout.addWidget(splitter, 1)
self.view_mode_stack.addWidget(chart_page)
self._chart_mode_page = chart_page
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.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.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)
self.view_mode_stack.addWidget(self.cockpit_view)
root.addWidget(self.view_mode_stack, 1)
self.poll_timer = QTimer(self)
self.poll_timer.setInterval(5_000)
@@ -4298,6 +4358,111 @@ class ReceptionPage(QWidget):
if panel.minimumWidth() != width:
panel.setFixedWidth(width)
def set_patient_context_store(self, store: PatientContextStore) -> None:
"""Attach the Spatial Shell context store and default to Digital Twin Cockpit."""
self.patient_context_store = store
self._root_layout.setContentsMargins(0, 2, 0, 2)
self._queue_filter_status = None
for st_key, btn in self._queue_filter_buttons.items():
btn.setChecked(st_key is None)
self._sync_queue_filter_summary()
self.set_workspace_mode("cockpit")
self._sync_cockpit_and_context()
def set_workspace_mode(self, mode: str) -> None:
normalized = "cockpit" if str(mode).strip().lower() == "cockpit" else "chart"
self._workspace_mode = normalized
if normalized == "cockpit":
self.view_mode_stack.setCurrentWidget(self.cockpit_view)
self._return_to_cockpit_bar.setVisible(False)
else:
self.view_mode_stack.setCurrentWidget(self._chart_mode_page)
self._return_to_cockpit_bar.setVisible(self.patient_context_store is not None)
if self.patient_context_store is not None:
self.patient_context_store.set_cockpit_mode(normalized)
def _open_structured_chart_tab(self, tab_index: int = 0) -> None:
self.set_workspace_mode("chart")
if hasattr(self, "detail_tabs") and 0 <= tab_index < self.detail_tabs.count():
self.detail_tabs.setCurrentIndex(tab_index)
def _select_record_from_cockpit(self, record: Any) -> None:
rec_id = _record_id(record)
if rec_id is not None:
for idx in range(self.queue_list.count()):
item = self.queue_list.item(idx)
item_rec = item.data(Qt.ItemDataRole.UserRole)
if _same_id(_record_id(item_rec), rec_id):
if self.queue_list.currentRow() != idx:
self.queue_list.setCurrentRow(idx)
else:
self._select_record(record)
return
self._select_record(record)
def select_cockpit_ai_model(self, model_key: str) -> None:
if model_key in AI_ANALYSIS_MODELS:
self._ai_analysis_active_model = model_key
if hasattr(self, "ai_analysis_model_selector"):
idx = self.ai_analysis_model_selector.findData(model_key)
if idx >= 0 and self.ai_analysis_model_selector.currentIndex() != idx:
self.ai_analysis_model_selector.setCurrentIndex(idx)
self._sync_ai_analysis_view()
self._sync_cockpit_and_context()
def _sync_cockpit_and_context(self) -> None:
"""Synchronize the 3-column Digital Twin 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 {}
self.cockpit_view.set_queue_records(
self._queue_records,
self._selected_appointment_id,
active_filter_status=self._queue_filter_status,
queue_date=self._queue_date,
)
doc_name = display_text(
first_value(
appointment,
"doctor_name",
default=first_value(self.current_user, "name", "real_name", default="主诊中医师"),
)
)
asst_name = display_text(first_value(appointment, "assistant_name", default=""), "")
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_complete=bool(
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()
ai_payload = self._ai_analysis_payloads.get(self._ai_analysis_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,
)
self.cockpit_view.set_snapshot(vm)
self.cockpit_snapshot_updated.emit(vm)
def _ensure_diagnosis_dialog(self) -> DiagnosisDialog:
dialog = getattr(self, "diagnosis_dialog", None)
if dialog is None:
@@ -5812,6 +5977,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_cockpit_and_context()
def _render_ai_analysis_payload(
self,
@@ -7573,6 +7739,7 @@ class ReceptionPage(QWidget):
)
else:
self._clear_selection()
self._sync_cockpit_and_context()
return
chosen = records[row_to_select]
if selected_id is not None and _same_id(_record_id(chosen), selected_id):
@@ -7581,6 +7748,7 @@ class ReceptionPage(QWidget):
self._load_detail(chosen, silent=True, clear=False)
else:
self._select_record(chosen, silent=True, read_only_refresh=workspace_refresh)
self._sync_cockpit_and_context()
def _update_queue_filter_counts(self, result: Any, records: list[Any]) -> None:
extend = get_value(result, "extend", None)
@@ -9374,6 +9542,7 @@ class ReceptionPage(QWidget):
self.add_tongue_button.setEnabled(note_enabled)
self.add_report_button.setEnabled(note_enabled)
self.save_note_button.setEnabled(note_enabled)
self._sync_cockpit_and_context()
def _detail_error(
self, error: Exception, generation: int, appointment_id: int | None = None
@@ -9501,6 +9670,7 @@ class ReceptionPage(QWidget):
self._reset_detail_content()
self.detail_banner.clear()
self.detail_stack.setCurrentIndex(0)
self._sync_cockpit_and_context()
def _selection_context(self) -> tuple[int, int, int | None, int | None] | None:
appointment_id = self._selected_appointment_id
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,5 @@
"""Cross-page reactive state stores for Clinical OS 3.0."""
from .patient_context_store import PatientContextStore, PatientSnapshot
__all__ = ["PatientContextStore", "PatientSnapshot"]
@@ -0,0 +1,265 @@
"""Global clinical patient context bus shared across spatial workstation views."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from PySide6.QtCore import QObject, Signal
from ..widgets import display_text, first_value, gender_text
def _safe_int(value: Any, default: int = 0) -> int:
try:
return int(value)
except (TypeError, ValueError):
return default
def _mask_phone(raw: Any) -> str:
text = str(raw or "").strip()
if not text or text == "—":
return "—"
if "*" in text:
return text
digits = "".join(ch for ch in text if ch.isdigit())
if len(digits) >= 7:
return f"{digits[:3]}****{digits[-4:]}"
return text
@dataclass(frozen=True)
class PatientSnapshot:
"""Immutable active-patient summary surfaced in the spatial shell header."""
appointment_id: int = 0
diagnosis_id: int = 0
patient_id: int = 0
patient_name: str = "未选择患者"
gender_age: str = ""
phone: str = "—"
course_text: str = ""
clinical_diagnosis: str = "待选择接诊患者"
chief_complaint: str = ""
status_code: int = 0
status_text: str = "待接诊"
assistant_name: str = "—"
doctor_name: str = "—"
appointment_time: str = ""
raw_record: dict[str, Any] = field(default_factory=dict, compare=False)
@property
def has_patient(self) -> bool:
return bool(
self.appointment_id > 0
or self.diagnosis_id > 0
or self.patient_id > 0
or (self.patient_name and self.patient_name not in {"—", "未选择患者"})
)
@property
def subtitle_line(self) -> str:
parts = [
part
for part in (
self.gender_age,
self.clinical_diagnosis if 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 "从今日门诊计划或挂号队列选择患者"
class PatientContextStore(QObject):
"""Reactive store broadcasting active patient and bottom-sheet state across pages."""
active_patient_changed = Signal(object)
active_appointment_changed = Signal(int)
bottom_sheet_mode_changed = Signal(bool)
cockpit_mode_changed = Signal(str)
def __init__(self, parent: QObject | None = None) -> None:
super().__init__(parent)
self._current_patient = PatientSnapshot()
self._bottom_sheet_expanded = False
self._cockpit_mode = "cockpit"
@property
def current_patient(self) -> PatientSnapshot:
return self._current_patient
@property
def bottom_sheet_expanded(self) -> bool:
return self._bottom_sheet_expanded
@property
def cockpit_mode(self) -> str:
return self._cockpit_mode
def set_bottom_sheet_expanded(self, expanded: bool) -> None:
target = bool(expanded)
if self._bottom_sheet_expanded == target:
return
self._bottom_sheet_expanded = target
self.bottom_sheet_mode_changed.emit(target)
def toggle_bottom_sheet(self) -> bool:
self.set_bottom_sheet_expanded(not self._bottom_sheet_expanded)
return self._bottom_sheet_expanded
def set_cockpit_mode(self, mode: str) -> None:
normalized = "chart" if str(mode).strip().lower() == "chart" else "cockpit"
if self._cockpit_mode == normalized:
return
self._cockpit_mode = normalized
self.cockpit_mode_changed.emit(normalized)
def clear(self) -> None:
empty = PatientSnapshot()
if self._current_patient == empty:
return
self._current_patient = empty
self.active_patient_changed.emit(empty)
self.active_appointment_changed.emit(0)
def set_snapshot(self, snapshot: PatientSnapshot) -> None:
previous_appointment = self._current_patient.appointment_id
if self._current_patient == snapshot:
return
self._current_patient = snapshot
self.active_patient_changed.emit(snapshot)
if snapshot.appointment_id != previous_appointment:
self.active_appointment_changed.emit(snapshot.appointment_id)
def update_from_reception(
self,
appointment: Any,
patient: Any = None,
diagnosis: Any = None,
) -> PatientSnapshot:
"""Build and publish a rich snapshot from reception detail payloads."""
sources = (diagnosis or {}, patient or {}, appointment or {})
name = display_text(
first_value(
appointment,
"patient_name",
"name",
default=first_value(patient, "name", "patient_name", default="患者"),
)
)
raw_gender = next(
(
first_value(src, "gender_desc", "gender", default=None)
for src in sources
if first_value(src, "gender_desc", "gender", default=None) not in (None, "")
),
"",
)
gender = gender_text(raw_gender) if raw_gender not in (None, "") else ""
age = first_value(
diagnosis,
"age",
default=first_value(patient, "age", default=first_value(appointment, "age", default="")),
)
gender_age = " · ".join(
part
for part in (
gender if gender and gender != "—" else "",
f"{age}岁" if age not in (None, "", "—") else "",
)
if part
)
phone = _mask_phone(
first_value(
patient,
"phone",
"mobile",
default=first_value(appointment, "patient_phone", "phone", default="—"),
)
)
course = display_text(
first_value(
diagnosis,
"disease_course_text",
"diabetes_history_text",
"diabetes_discovery_year_text",
default="",
),
"",
)
clinical_diag = display_text(
first_value(
diagnosis,
"clinical_diagnosis",
"diagnosis_name",
"disease_name",
default="中医糖代谢调理",
)
)
chief = display_text(
first_value(diagnosis, "chief_complaint", "complaint", default=""),
"",
)
status_code = _safe_int(first_value(appointment, "status", default=1), 1)
status_map = {1: "待接诊", 2: "已取消", 3: "已完成", 4: "已过号"}
status_text = display_text(
first_value(
appointment,
"status_desc",
"status_text",
default=status_map.get(status_code, "待接诊"),
)
)
appt_id = _safe_int(first_value(appointment, "id", "appointment_id", default=0))
diag_id = _safe_int(
first_value(
diagnosis,
"id",
"diagnosis_id",
default=first_value(appointment, "diagnosis_id", "patient_id", default=0),
)
)
pat_id = _safe_int(
first_value(
appointment,
"source_patient_id",
"patient_id",
default=first_value(patient, "id", "source_patient_id", default=0),
)
)
raw: dict[str, Any] = {}
if isinstance(appointment, dict):
raw.update(appointment)
snapshot = PatientSnapshot(
appointment_id=appt_id,
diagnosis_id=diag_id,
patient_id=pat_id,
patient_name=name,
gender_age=gender_age,
phone=phone,
course_text=course,
clinical_diagnosis=clinical_diag,
chief_complaint=chief,
status_code=status_code,
status_text=status_text,
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=""),
"",
),
raw_record=raw,
)
self.set_snapshot(snapshot)
return snapshot
def update_from_row(self, row: Any) -> PatientSnapshot:
"""Build and publish a lightweight snapshot when selecting a list/table row."""
if not row:
return self._current_patient
return self.update_from_reception(row, row, row)
@@ -0,0 +1,35 @@
"""Presentation view-models for the Clinical OS 3.0 workstation."""
from .cockpit_vm import (
AuroraCardVM,
CareJourneyVM,
CockpitSnapshotVM,
DiurnalSlot,
DiurnalStabilityVM,
GlycemicProgressionVM,
JourneyDayCell,
JourneyPhaseSpan,
ObsidianAuroraVM,
ProgressionPoint,
SyndromeTwinVM,
TwinCalloutNode,
VitalMiniBrick,
derive_cockpit_snapshot,
)
__all__ = [
"AuroraCardVM",
"CareJourneyVM",
"CockpitSnapshotVM",
"DiurnalSlot",
"DiurnalStabilityVM",
"GlycemicProgressionVM",
"JourneyDayCell",
"JourneyPhaseSpan",
"ObsidianAuroraVM",
"ProgressionPoint",
"SyndromeTwinVM",
"TwinCalloutNode",
"VitalMiniBrick",
"derive_cockpit_snapshot",
]
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,23 @@
"""Hardware-antialiased QPainter medical micro-charts & digital twin widgets."""
from .aurora_sheet import ArcRhythmGaugeWidget, AuroraGlassCardWidget, CollapsibleObsidianSheet
from .context_bridge_bar import SpatialContextBridgeBar
from .diurnal_strip import DiurnalStabilityCard
from .journey_track import CareJourneyCard
from .pill_chart import PillProgressionCard
from .reception_cockpit import ReceptionDigitalTwinCockpit
from .twin_stage import ClinicalTwinStageWidget
from .week_strip import WeekCalendarStripWidget
__all__ = [
"ArcRhythmGaugeWidget",
"AuroraGlassCardWidget",
"CareJourneyCard",
"ClinicalTwinStageWidget",
"CollapsibleObsidianSheet",
"DiurnalStabilityCard",
"PillProgressionCard",
"ReceptionDigitalTwinCockpit",
"SpatialContextBridgeBar",
"WeekCalendarStripWidget",
]
@@ -0,0 +1,522 @@
"""Pull-Up Deep Obsidian Aurora-Glass AI Sheet bound strictly to real AI reports."""
from __future__ import annotations
import math
from PySide6.QtCore import QPointF, QRectF, Qt, Signal
from PySide6.QtGui import (
QColor,
QFont,
QMouseEvent,
QPainter,
QPainterPath,
QPen,
QRadialGradient,
QTextOption,
)
from PySide6.QtWidgets import (
QFrame,
QHBoxLayout,
QLabel,
QPushButton,
QSizePolicy,
QToolTip,
QVBoxLayout,
QWidget,
)
from ..reception_style import body_family, heading_family, number_family
from ..viewmodels.cockpit_vm import AuroraCardVM, ObsidianAuroraVM
class AuroraGlassCardWidget(QWidget):
"""Frosted dark Aurora-Mesh card displaying real backend AI narrative & risks."""
clicked = Signal()
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("AuroraGlassCardWidget")
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setMinimumSize(196, 152)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.setFixedHeight(162)
self._vm: AuroraCardVM | None = None
self._hovered = False
def set_view_model(self, vm: AuroraCardVM) -> None:
self._vm = vm
self.setToolTip(vm.body_text)
self.update()
def enterEvent(self, event: object) -> None: # noqa: N802
self._hovered = True
self.update()
super().enterEvent(event) # type: ignore[arg-type]
def leaveEvent(self, event: object) -> None: # noqa: N802
self._hovered = False
self.update()
super().leaveEvent(event) # type: ignore[arg-type]
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802
if event.button() == Qt.MouseButton.LeftButton:
self.clicked.emit()
event.accept()
return
super().mousePressEvent(event)
def paintEvent(self, _event: object) -> None: # noqa: N802
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
rect = QRectF(self.rect()).adjusted(1.0, 1.0, -1.0, -1.0)
path = QPainterPath()
path.addRoundedRect(rect, 20.0, 20.0)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.fillPath(path, QColor(32, 40, 39, 240))
vm = self._vm
tint = vm.tint if vm else "cyan"
glow1 = QRadialGradient(
QPointF(rect.left() + rect.width() * 0.75, rect.top() + rect.height() * 0.32),
rect.width() * 0.72,
)
if tint == "cyan":
glow1.setColorAt(0.0, QColor(88, 168, 182, 98))
glow1.setColorAt(0.55, QColor(58, 118, 130, 52))
glow1.setColorAt(1.0, QColor(28, 38, 38, 0))
accent_c = QColor("#A9DCE4")
elif tint == "olive":
glow1.setColorAt(0.0, QColor(148, 162, 72, 96))
glow1.setColorAt(0.55, QColor(96, 112, 48, 52))
glow1.setColorAt(1.0, QColor(28, 38, 32, 0))
accent_c = QColor("#DCE694")
else:
glow1.setColorAt(0.0, QColor(206, 128, 86, 102))
glow1.setColorAt(0.55, QColor(142, 84, 58, 54))
glow1.setColorAt(1.0, QColor(38, 30, 28, 0))
accent_c = QColor("#F2C4A8")
painter.fillPath(path, glow1)
painter.setPen(QPen(QColor(255, 255, 255, 78 if self._hovered else 42), 1.0))
painter.drawPath(path)
if vm is None:
return
left = rect.left() + 16.0
right = rect.right() - 16.0
avail_w = max(120.0, right - left)
# Header: Accent dot + Title + Status Badge Pill
painter.setPen(Qt.PenStyle.NoPen)
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)
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)
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),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
vm.subtitle,
)
# Divider line
painter.setPen(QPen(QColor(255, 255, 255, 24), 1.0))
painter.drawLine(QPointF(left, rect.top() + 51), QPointF(right, rect.top() + 51))
# Real AI Narrative Body (clean wrapped clinical text, max 4 lines)
body_font = QFont(body_family())
body_font.setPixelSize(12)
painter.setFont(body_font)
painter.setPen(QColor("#EEF5F3"))
body_box = QRectF(left, rect.top() + 57, avail_w, 74)
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]}…"
painter.drawText(body_box, text_to_draw, opt)
# Footer metadata
painter.setFont(s_font)
painter.setPen(QColor(210, 226, 223, 155))
painter.drawText(
QRectF(left, rect.bottom() - 23, avail_w * 0.62, 16),
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),
Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
vm.foot_right,
)
class ArcRhythmGaugeWidget(QWidget):
"""Objective 6-dimension Clinical Record Completeness speedometer gauge."""
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("ArcRhythmGaugeWidget")
self.setMouseTracking(True)
self.setFixedSize(202, 162)
self._value_text = "0/6"
self._unit_text = "项"
self._caption = "病历实采完备度"
self._ratio = 0.08
self._tooltip = ""
def set_gauge(
self,
value_text: str,
unit_text: str,
caption: str,
ratio: float,
tooltip: str = "",
) -> None:
self._value_text = value_text
self._unit_text = unit_text
self._caption = caption
self._ratio = max(0.05, min(1.0, ratio))
self._tooltip = tooltip
self.setToolTip(tooltip)
self.update()
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
if self._tooltip:
QToolTip.showText(event.globalPosition().toPoint(), self._tooltip, self)
super().mouseMoveEvent(event)
def paintEvent(self, _event: object) -> None: # noqa: N802
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
rect = QRectF(self.rect())
cx = rect.center().x()
cy = rect.top() + 92.0
radius = 66.0
arc_box = QRectF(cx - radius, cy - radius, radius * 2.0, radius * 2.0)
hemi = QRadialGradient(QPointF(cx, cy), radius)
hemi.setColorAt(0.0, QColor(255, 255, 255, 24))
hemi.setColorAt(1.0, QColor(255, 255, 255, 0))
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(hemi)
painter.drawPie(arc_box.adjusted(10, 10, -10, -10), 0, 180 * 16)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.setPen(QPen(QColor(255, 255, 255, 42), 3.0, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
painter.drawArc(arc_box, 0, 180 * 16)
span_deg = self._ratio * 180.0
painter.setPen(QPen(QColor("#8CE0CB"), 3.4, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
painter.drawArc(arc_box, int(180 * 16), int(-span_deg * 16))
# 6 dimension ticks along semi-circle
for step in range(7):
angle_rad = math.pi - (step / 6.0) * math.pi
p1 = QPointF(cx + math.cos(angle_rad) * (radius - 8), cy - math.sin(angle_rad) * (radius - 8))
p2 = QPointF(cx + math.cos(angle_rad) * (radius - 14), cy - math.sin(angle_rad) * (radius - 14))
painter.setPen(QPen(QColor(255, 255, 255, 78), 1.2))
painter.drawLine(p1, p2)
needle_rad = math.pi - self._ratio * math.pi
tip = QPointF(cx + math.cos(needle_rad) * (radius - 5), cy - math.sin(needle_rad) * (radius - 5))
arc_dot = QPointF(cx + math.cos(needle_rad) * radius, cy - math.sin(needle_rad) * radius)
painter.setPen(QPen(QColor(255, 255, 255, 210), 1.6))
painter.drawLine(QPointF(cx, cy), tip)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor("#FFFFFF"))
painter.drawEllipse(QPointF(cx, cy), 3.5, 3.5)
painter.drawEllipse(arc_dot, 4.0, 4.0)
cap_font = QFont(body_family())
cap_font.setPixelSize(11)
painter.setFont(cap_font)
painter.setPen(QColor(210, 224, 222, 185))
painter.drawText(QRectF(0, cy + 7, rect.width(), 16), Qt.AlignmentFlag.AlignCenter, self._caption)
val_font = QFont(number_family())
val_font.setPixelSize(27)
val_font.setWeight(QFont.Weight.DemiBold)
painter.setFont(val_font)
painter.setPen(QColor("#FFFFFF"))
vw = float(painter.fontMetrics().horizontalAdvance(self._value_text))
total_w = vw + 26.0
vx = cx - total_w * 0.5
painter.drawText(
QRectF(vx, cy + 24, vw + 4, 34),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
self._value_text,
)
painter.setFont(cap_font)
painter.setPen(QColor(210, 224, 222, 170))
painter.drawText(QRectF(vx + vw + 5, cy + 31, 30, 22), Qt.AlignmentFlag.AlignLeft, self._unit_text)
class CollapsibleObsidianSheet(QWidget):
"""Bottom pull-up obsidian sheet displaying real Qwen / OpenAI / Doubao clinical reports."""
expanded_changed = Signal(bool)
open_ai_report_requested = Signal()
open_ai_consult_requested = Signal()
model_selected = Signal(str)
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("CollapsibleObsidianSheet")
self.setMouseTracking(True)
self._expanded = False
self._handle_rect = QRectF()
self._vm: ObsidianAuroraVM | None = None
root = QVBoxLayout(self)
root.setContentsMargins(22, 24, 22, 14)
root.setSpacing(10)
top_bar = QHBoxLayout()
top_bar.setContentsMargins(0, 0, 0, 0)
top_bar.setSpacing(10)
self.title_label = QLabel("AI 病历循证分析舱", self)
self.title_label.setStyleSheet(
"color: #F6FAF9; font-size: 15px; font-weight: 600; background: transparent;"
)
top_bar.addWidget(self.title_label)
self.summary_label = QLabel("选择患者后自动读取千问 / OpenAI / 豆包实采病历分析报告", self)
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)
top_bar.addWidget(self.summary_label, 1)
self._model_buttons: dict[str, QPushButton] = {}
for m_key, m_text in (("qwen", "千问"), ("openai", "OpenAI"), ("doubao", "豆包")):
btn = QPushButton(m_text, self)
btn.setCheckable(True)
btn.setCursor(Qt.CursorShape.PointingHandCursor)
btn.setFixedHeight(26)
btn.clicked.connect(lambda _c=False, k=m_key: self._choose_model(k))
self._model_buttons[m_key] = btn
top_bar.addWidget(btn)
self._sync_model_pill_styles("qwen")
self.report_button = QPushButton("完整循证报告", self)
self.report_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.report_button.setFixedHeight(28)
self.report_button.setStyleSheet(
"QPushButton { background: rgba(255,255,255,22); color: #F2F7F6;"
" border: 1px solid rgba(255,255,255,48); border-radius: 14px; padding: 0 13px; font-size: 12px; }"
"QPushButton:hover { background: rgba(255,255,255,40); }"
)
self.report_button.clicked.connect(self.open_ai_report_requested.emit)
top_bar.addWidget(self.report_button)
self.consult_button = QPushButton("AI 深度对话", self)
self.consult_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.consult_button.setFixedHeight(28)
self.consult_button.setStyleSheet(
"QPushButton { background: #0E6F5C; color: #FFFFFF;"
" border: 0; border-radius: 14px; padding: 0 14px; font-size: 12px; font-weight: 600; }"
"QPushButton:hover { background: #138770; }"
)
self.consult_button.clicked.connect(self.open_ai_consult_requested.emit)
top_bar.addWidget(self.consult_button)
self.toggle_button = QPushButton("展开分析舱 ▲", self)
self.toggle_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.toggle_button.setFixedHeight(28)
self.toggle_button.setStyleSheet(
"QPushButton { background: rgba(223,199,147,26); color: #EAD7AC;"
" border: 1px solid rgba(223,199,147,90); border-radius: 14px; padding: 0 12px; font-size: 12px; font-weight: 600; }"
"QPushButton:hover { background: rgba(223,199,147,48); }"
)
self.toggle_button.clicked.connect(self.toggle_expanded)
top_bar.addWidget(self.toggle_button)
root.addLayout(top_bar)
self.body_widget = QWidget(self)
body_layout = QHBoxLayout(self.body_widget)
body_layout.setContentsMargins(0, 4, 0, 2)
body_layout.setSpacing(14)
left_col = QWidget(self.body_widget)
left_col.setFixedWidth(196)
left_layout = QVBoxLayout(left_col)
left_layout.setContentsMargins(0, 0, 0, 0)
left_layout.setSpacing(8)
self._param_rows: list[tuple[QLabel, QLabel]] = []
for _ in range(3):
pill = QFrame(left_col)
pill.setFixedHeight(46)
pill.setStyleSheet(
"QFrame { background: rgba(255,255,255,14); border: 1px solid rgba(255,255,255,24); border-radius: 13px; }"
)
pl = QHBoxLayout(pill)
pl.setContentsMargins(13, 0, 13, 0)
k_lbl = QLabel("状态", pill)
k_lbl.setStyleSheet("color: rgba(225,236,234,195); font-size: 12px; border: 0; background: transparent;")
sep_lbl = QLabel("|", pill)
sep_lbl.setStyleSheet("color: rgba(255,255,255,55); border: 0; background: transparent;")
v_lbl = QLabel("—", pill)
v_lbl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
v_lbl.setStyleSheet("color: #FFFFFF; font-size: 12px; font-weight: 600; border: 0; background: transparent;")
pl.addWidget(k_lbl)
pl.addStretch(1)
pl.addWidget(sep_lbl)
pl.addSpacing(5)
pl.addWidget(v_lbl)
left_layout.addWidget(pill)
self._param_rows.append((k_lbl, v_lbl))
left_layout.addStretch(1)
body_layout.addWidget(left_col)
self.aurora_cards = [AuroraGlassCardWidget(self.body_widget) for _ in range(3)]
for card in self.aurora_cards:
card.clicked.connect(self.open_ai_report_requested.emit)
body_layout.addWidget(card, 1)
self.gauge = ArcRhythmGaugeWidget(self.body_widget)
body_layout.addWidget(self.gauge)
root.addWidget(self.body_widget)
self._apply_expanded_geometry()
def _sync_model_pill_styles(self, active_key: str) -> None:
for key, btn in self._model_buttons.items():
checked = key == active_key
btn.setChecked(checked)
if checked:
btn.setStyleSheet(
"QPushButton { background: #FFFFFF; color: #101817; border: 0;"
" border-radius: 13px; padding: 0 11px; font-size: 11px; font-weight: 600; }"
)
else:
btn.setStyleSheet(
"QPushButton { background: rgba(255,255,255,14); color: rgba(230,240,238,180);"
" border: 1px solid rgba(255,255,255,26); border-radius: 13px; padding: 0 11px; font-size: 11px; }"
"QPushButton:hover { background: rgba(255,255,255,28); }"
)
def _choose_model(self, key: str) -> None:
self._sync_model_pill_styles(key)
self.model_selected.emit(key)
@property
def is_expanded(self) -> bool:
return self._expanded
def set_expanded(self, expanded: bool) -> None:
target = bool(expanded)
if self._expanded == target:
return
self._expanded = target
self._apply_expanded_geometry()
self.expanded_changed.emit(target)
def toggle_expanded(self) -> None:
self.set_expanded(not self._expanded)
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.update()
def set_view_model(self, vm: ObsidianAuroraVM) -> None:
self._vm = vm
self._sync_model_pill_styles(vm.active_model_key)
self.title_label.setText(vm.program_title)
self.summary_label.setText(vm.ai_summary_line)
for (k_lbl, v_lbl), (k_txt, v_txt) in zip(self._param_rows, vm.params, strict=False):
k_lbl.setText(k_txt)
v_lbl.setText(v_txt)
for card, c_vm in zip(self.aurora_cards, vm.cards, strict=False):
card.set_view_model(c_vm)
self.gauge.set_gauge(
vm.gauge_value,
vm.gauge_unit,
vm.gauge_caption,
vm.gauge_ratio,
vm.gauge_tooltip,
)
self.update()
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802
if event.button() == Qt.MouseButton.LeftButton and self._handle_rect.contains(event.position()):
self.toggle_expanded()
event.accept()
return
super().mousePressEvent(event)
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
if self._handle_rect.contains(event.position()):
self.setCursor(Qt.CursorShape.PointingHandCursor)
else:
self.setCursor(Qt.CursorShape.ArrowCursor)
super().mouseMoveEvent(event)
def paintEvent(self, _event: object) -> None: # noqa: N802
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
rect = QRectF(self.rect())
sheet_top = 12.0
cx = rect.center().x()
self._handle_rect = QRectF(cx - 38.0, 0.0, 76.0, 22.0)
body_rect = QRectF(0.0, sheet_top, rect.width(), rect.height() - sheet_top)
path = QPainterPath()
path.addRoundedRect(body_rect, 24.0, 24.0)
painter.fillPath(path, QColor("#0E1413"))
notch = QPainterPath()
notch.moveTo(cx - 34.0, sheet_top + 1.0)
notch.cubicTo(cx - 20.0, sheet_top + 1.0, cx - 18.0, 2.0, cx, 2.0)
notch.cubicTo(cx + 18.0, 2.0, cx + 20.0, sheet_top + 1.0, cx + 34.0, sheet_top + 1.0)
notch.closeSubpath()
painter.fillPath(notch, QColor("#0E1413"))
painter.setPen(QPen(QColor("#DCE8E5"), 1.7, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
ay = 10.0
if self._expanded:
painter.drawLine(QPointF(cx - 5.0, ay - 2.0), QPointF(cx, ay + 2.5))
painter.drawLine(QPointF(cx, ay + 2.5), QPointF(cx + 5.0, ay - 2.0))
else:
painter.drawLine(QPointF(cx - 5.0, ay + 2.5), QPointF(cx, ay - 2.0))
painter.drawLine(QPointF(cx, ay - 2.0), QPointF(cx + 5.0, ay + 2.5))
@@ -0,0 +1,110 @@
"""Reusable Alveo × Serene spatial action & patient-focus bridge bar for subpages."""
from __future__ import annotations
from collections.abc import Callable
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QPushButton, QWidget
from ..state import PatientContextStore, PatientSnapshot
BRIDGE_QSS = """
QFrame#SpatialContextBridgeBar {
background-color: #FFFFFF;
border: 1px solid #E2ECE9;
border-radius: 20px;
}
QPushButton#BridgeFocusPatientPill {
min-height: 30px;
max-height: 30px;
padding: 0 14px;
border-radius: 15px;
background-color: #F2F6F5;
border: 1px solid #DCE7E4;
color: #213735;
font-size: 12px;
font-weight: 600;
}
QPushButton#BridgeFocusPatientPill:hover {
background-color: #E3F3EE;
border-color: #9BCBC0;
color: #0E6F5C;
}
QPushButton#BridgeFocusPatientPill:checked {
background-color: #0E6F5C;
border-color: #0E6F5C;
color: #FFFFFF;
}
"""
class SpatialContextBridgeBar(QFrame):
"""Compact rounded Bento bar syncing cross-page patient filtering & page actions."""
def __init__(
self,
summary_text: str,
*,
on_filter_patient: Callable[[str], None] | None = None,
parent: QWidget | None = None,
) -> None:
super().__init__(parent)
self.setObjectName("SpatialContextBridgeBar")
self.setStyleSheet(BRIDGE_QSS)
self.setMinimumHeight(52)
self._store: PatientContextStore | None = None
self._on_filter_patient = on_filter_patient
self.bar_layout = QHBoxLayout(self)
self.bar_layout.setContentsMargins(16, 8, 16, 8)
self.bar_layout.setSpacing(10)
self.summary_label = QLabel(summary_text, self)
self.summary_label.setStyleSheet(
"color: #556B68; font-size: 12px; font-weight: 500; background: transparent; border: 0;"
)
self.bar_layout.addWidget(self.summary_label)
self.focus_patient_button = QPushButton("聚焦当前患者", self)
self.focus_patient_button.setObjectName("BridgeFocusPatientPill")
self.focus_patient_button.setCheckable(True)
self.focus_patient_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.focus_patient_button.setVisible(False)
self.focus_patient_button.clicked.connect(self._toggle_patient_focus)
self.bar_layout.addWidget(self.focus_patient_button)
self.bar_layout.addStretch(1)
self.actions_host = QWidget(self)
self.actions_layout = QHBoxLayout(self.actions_host)
self.actions_layout.setContentsMargins(0, 0, 0, 0)
self.actions_layout.setSpacing(8)
self.bar_layout.addWidget(self.actions_host)
def add_action_widget(self, widget: QWidget) -> None:
widget.setParent(self.actions_host)
widget.show()
self.actions_layout.addWidget(widget)
def bind_store(self, store: PatientContextStore) -> None:
self._store = store
store.active_patient_changed.connect(self._on_patient_changed)
self._on_patient_changed(store.current_patient)
def _on_patient_changed(self, snapshot: PatientSnapshot) -> None:
if self._on_filter_patient is None or not snapshot or not snapshot.has_patient:
self.focus_patient_button.setVisible(False)
self.focus_patient_button.setChecked(False)
return
self.focus_patient_button.setVisible(True)
self.focus_patient_button.setText(f"仅看当前患者:{snapshot.patient_name}")
def _toggle_patient_focus(self, checked: bool) -> None:
if self._on_filter_patient is None or self._store is None:
return
snap = self._store.current_patient
if checked and snap.has_patient:
self._on_filter_patient(snap.patient_name)
else:
self._on_filter_patient("")
@@ -0,0 +1,271 @@
"""Real postprandial 2h blood glucose, 14-day check-in strip, and 3 vital bricks."""
from __future__ import annotations
from PySide6.QtCore import QPointF, QRectF, QSize, Qt
from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen
from PySide6.QtWidgets import QToolTip, QWidget
from ..reception_style import body_family, heading_family, number_family
from ..viewmodels.cockpit_vm import DiurnalSlot, DiurnalStabilityVM, VitalMiniBrick
class DiurnalStabilityCard(QWidget):
"""Render real 2h postprandial glucose, 14-day daily records, and BP/BMI/Meds bricks."""
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("DiurnalStabilityCard")
self.setMouseTracking(True)
self.setMinimumHeight(218)
self._vm: DiurnalStabilityVM | None = None
self._slot_rects: list[tuple[QRectF, DiurnalSlot]] = []
self._brick_rects: list[tuple[QRectF, VitalMiniBrick]] = []
def sizeHint(self) -> QSize: # noqa: N802
return QSize(330, 300)
def set_view_model(self, vm: DiurnalStabilityVM) -> None:
self._vm = vm
self.update()
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)
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)
break
super().mouseMoveEvent(event)
def paintEvent(self, _event: object) -> None: # noqa: N802
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
rect = QRectF(self.rect()).adjusted(1.0, 1.0, -1.0, -1.0)
card_path = QPainterPath()
card_path.addRoundedRect(rect, 22.0, 22.0)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.fillPath(card_path, QColor("#FFFFFF"))
painter.setPen(QPen(QColor("#E3ECE9"), 1.0))
painter.drawPath(card_path)
vm = self._vm
if vm is None:
return
compact = rect.height() < 262.0
pad_x = 18.0
pad_y = 11.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.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_path = QPainterPath()
badge_path.addRoundedRect(badge_rect, 11.0, 11.0)
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)
painter.drawText(
QRectF(left, metric_y, num_w + 4, 36 if compact else 40),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
vm.primary_value,
)
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,
)
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)
)
painter.drawText(
QRectF(cap_x, metric_y + (6 if compact else 10), right - cap_x, 24),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
elided_cap,
)
# 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:
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.drawText(
QRectF(bx + 11 + val_w, brick_top + 25, b_w - val_w - 14, 18),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
elided_unit,
)
@@ -0,0 +1,314 @@
"""Real 21-Day Health Check-In (Glucose/Diet/Exercise) & Revisit Due Track."""
from __future__ import annotations
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
from ..reception_style import body_family, heading_family, number_family
from ..viewmodels.cockpit_vm import CareJourneyVM, JourneyDayCell
class CareJourneyCard(QWidget):
"""Plot the patient's real last 21 calendar days of check-ins + revisit due status."""
day_selected = Signal(int)
open_full_plan_requested = Signal()
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("CareJourneyCard")
self.setMouseTracking(True)
self.setMinimumHeight(148)
self._vm: CareJourneyVM | None = None
self._day_rects: list[tuple[QRectF, JourneyDayCell]] = []
self._plan_btn_rect = QRectF()
self._hover_day: int = -1
self._hover_btn = False
def sizeHint(self) -> QSize: # noqa: N802
return QSize(1180, 164)
def set_view_model(self, vm: CareJourneyVM) -> None:
self._vm = vm
self._hover_day = -1
self.update()
def leaveEvent(self, event: object) -> None: # noqa: N802
self._hover_day = -1
self._hover_btn = False
self.update()
super().leaveEvent(event) # type: ignore[arg-type]
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
pos = event.position()
hover_btn = self._plan_btn_rect.contains(pos)
hover_day = -1
for rect, cell in self._day_rects:
if rect.contains(pos):
hover_day = cell.day_num
QToolTip.showText(event.globalPosition().toPoint(), cell.tooltip, self)
break
self.setCursor(
Qt.CursorShape.PointingHandCursor
if (hover_btn or hover_day > 0)
else Qt.CursorShape.ArrowCursor
)
if hover_btn != self._hover_btn or hover_day != self._hover_day:
self._hover_btn = hover_btn
self._hover_day = hover_day
self.update()
super().mouseMoveEvent(event)
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802
if event.button() == Qt.MouseButton.LeftButton:
pos = event.position()
if self._plan_btn_rect.contains(pos):
self.open_full_plan_requested.emit()
event.accept()
return
for rect, cell in self._day_rects:
if rect.contains(pos):
self.day_selected.emit(cell.day_num)
event.accept()
return
super().mousePressEvent(event)
def paintEvent(self, _event: object) -> None: # noqa: N802
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
rect = QRectF(self.rect()).adjusted(1.0, 1.0, -1.0, -1.0)
card_path = QPainterPath()
card_path.addRoundedRect(rect, 22.0, 22.0)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.fillPath(card_path, QColor("#FFFFFF"))
painter.setPen(QPen(QColor("#E3ECE9"), 1.0))
painter.drawPath(card_path)
vm = self._vm
if vm is None:
return
# Left summary column (232px — High-DPI safe layout with inline status pill!)
left_x = rect.left() + 20.0
left_w = 224.0
title_font = QFont(heading_family())
title_font.setPixelSize(14)
title_font.setWeight(QFont.Weight.DemiBold)
painter.setFont(title_font)
painter.setPen(QColor("#11201E"))
painter.drawText(QRectF(left_x, rect.top() + 14, left_w, 20), Qt.AlignmentFlag.AlignLeft, vm.title)
sub_font = QFont(body_family())
sub_font.setPixelSize(11)
painter.setFont(sub_font)
painter.setPen(QColor("#788E8A"))
elided_sub = painter.fontMetrics().elidedText(vm.plan_subtitle, Qt.TextElideMode.ElideRight, int(left_w))
painter.drawText(QRectF(left_x, rect.top() + 34, left_w, 16), Qt.AlignmentFlag.AlignLeft, elided_sub)
# Big Check-in Count + "/ 21 天有打卡" + Inline Status Pill (ZERO overlap at any DPI!)
day_font = QFont(number_family())
day_font.setPixelSize(31)
day_font.setWeight(QFont.Weight.DemiBold)
painter.setFont(day_font)
painter.setPen(QColor("#0F1D1B") if vm.primary_metric_text != "—" else QColor("#7D918E"))
dw = float(painter.fontMetrics().horizontalAdvance(vm.primary_metric_text))
painter.drawText(
QRectF(left_x, rect.top() + 54, dw + 6, 36),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
vm.primary_metric_text,
)
slash_font = QFont(body_family())
slash_font.setPixelSize(12)
painter.setFont(slash_font)
painter.setPen(QColor("#6E8380"))
uw = float(painter.fontMetrics().horizontalAdvance(vm.total_unit_text))
painter.drawText(
QRectF(left_x + dw + 6, rect.top() + 62, uw + 6, 24),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
vm.total_unit_text,
)
# Inline status pill next to or cleanly right-aligned on the metric row
badge_font = QFont(body_family())
badge_font.setPixelSize(10)
badge_font.setWeight(QFont.Weight.DemiBold)
painter.setFont(badge_font)
bw = min(88.0, float(painter.fontMetrics().horizontalAdvance(vm.status_pill) + 16))
pill_x = max(left_x + dw + uw + 14.0, left_x + left_w - bw - 4.0)
if pill_x + bw <= left_x + left_w + 4.0:
b_rect = QRectF(pill_x, rect.top() + 63, bw, 20)
bp = QPainterPath()
bp.addRoundedRect(b_rect, 10.0, 10.0)
if vm.status_tone == "coral":
painter.fillPath(bp, QColor("#FCEBE6"))
painter.setPen(QColor("#C85232"))
elif vm.status_tone == "emerald":
painter.fillPath(bp, QColor("#E2F3EE"))
painter.setPen(QColor("#0E6F5C"))
else:
painter.fillPath(bp, QColor("#F1F5F4"))
painter.setPen(QColor("#6B807D"))
elided_pill = painter.fontMetrics().elidedText(vm.status_pill, Qt.TextElideMode.ElideRight, int(bw - 10))
painter.drawText(b_rect, Qt.AlignmentFlag.AlignCenter, elided_pill)
# [↗ 打开日常记录矩阵] button anchored safely at bottom
self._plan_btn_rect = QRectF(left_x, rect.bottom() - 36, 142, 26)
btn_path = QPainterPath()
btn_path.addRoundedRect(self._plan_btn_rect, 13.0, 13.0)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.fillPath(btn_path, QColor("#EDF5F3" if self._hover_btn else "#FFFFFF"))
painter.setPen(QPen(QColor("#0E6F5C" if self._hover_btn else "#D7E3E0"), 1.0))
painter.drawPath(btn_path)
painter.setPen(QColor("#0E6F5C" if self._hover_btn else "#1E312F"))
painter.drawText(self._plan_btn_rect, Qt.AlignmentFlag.AlignCenter, "↗ 打开日常记录矩阵")
# Vertical subtle divider
div_x = left_x + left_w + 10
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)
painter.setFont(sub_font)
painter.setPen(QColor("#839794"))
painter.drawText(QRectF(rx, rect.top() + 13, 175, 16), Qt.AlignmentFlag.AlignLeft, "逐日实测日历(悬停查看明细)")
legend_items = (
("#0E6F5C", True, "血糖达标"),
("#E06D4C", True, "血糖偏高"),
("#CBE8E0", True, "饮食/运动"),
("#111918", True, "今日"),
("#DCE6E3", False, "无打卡"),
)
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}")
painter.setFont(sub_font)
painter.setPen(QColor("#829692"))
painter.drawText(QRectF(px1, phase_y + 14, pw, 14), Qt.AlignmentFlag.AlignLeft, ph.date_span)
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))
# 21 Real Date Pills
pill_top = bar_y + 7
pill_h = 38.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)
self._day_rects.append((d_rect, cell))
dp = QPainterPath()
dp.addRoundedRect(d_rect, 9.0, 9.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")
elif cell.state == "alert":
painter.fillPath(dp, QColor("#CC5738" if is_hover else "#E06D4C"))
fg = QColor("#FFFFFF")
elif cell.state == "stage":
painter.fillPath(dp, QColor("#B4DFD4" if is_hover else "#CBE8E0"))
fg = QColor("#11352E")
elif cell.state == "today":
today_center_x = d_rect.center().x()
painter.fillPath(dp, QColor("#111918"))
fg = QColor("#FFFFFF")
else:
painter.fillPath(dp, QColor("#F3F7F6" if is_hover else "#FFFFFF"))
painter.setPen(QPen(QColor("#DCE6E3"), 1.0))
painter.drawPath(dp)
fg = QColor("#7E928F")
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:
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)
# End Revisit / Prescription Status Capsule
f_rect = QRectF(rx + n_days * (pill_w + gap) + 4.0, pill_top, followup_w, pill_h)
fp = QPainterPath()
fp.addRoundedRect(f_rect, 10.0, 10.0)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.fillPath(fp, QColor("#FCEEE9" if vm.status_tone == "coral" else "#F4FAF8"))
painter.setPen(
QPen(
QColor("#D96243" if vm.status_tone == "coral" else "#6BAE9E"),
1.1,
Qt.PenStyle.DashLine,
)
)
painter.drawPath(fp)
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)
@@ -0,0 +1,220 @@
"""Real fasting blood glucose progression Bento card (mmol/L) rendered with QPainter."""
from __future__ import annotations
from PySide6.QtCore import QPointF, QRectF, QSize, Qt
from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen
from PySide6.QtWidgets import QToolTip, QWidget
from ..reception_style import body_family, heading_family, number_family
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."""
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("PillProgressionCard")
self.setMouseTracking(True)
self.setMinimumHeight(172)
self._vm: GlycemicProgressionVM | None = None
self._hover_index: int = -1
self._bar_rects: list[tuple[QRectF, ProgressionPoint]] = []
def sizeHint(self) -> QSize: # noqa: N802
return QSize(330, 224)
def set_view_model(self, vm: GlycemicProgressionVM) -> None:
self._vm = vm
self._hover_index = -1
self.update()
def leaveEvent(self, event: object) -> None: # noqa: N802
self._hover_index = -1
self.update()
super().leaveEvent(event) # type: ignore[arg-type]
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
pos = event.position()
hit = -1
for idx, (rect, point) in enumerate(self._bar_rects):
if rect.adjusted(-2, -10, 2, 6).contains(pos):
hit = idx
if point.value_hint:
QToolTip.showText(event.globalPosition().toPoint(), point.value_hint, self)
break
if hit != self._hover_index:
self._hover_index = hit
self.update()
super().mouseMoveEvent(event)
def paintEvent(self, _event: object) -> None: # noqa: N802
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
rect = QRectF(self.rect()).adjusted(1.0, 1.0, -1.0, -1.0)
card_path = QPainterPath()
card_path.addRoundedRect(rect, 22.0, 22.0)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.fillPath(card_path, QColor("#FFFFFF"))
painter.setPen(QPen(QColor("#E3ECE9"), 1.0))
painter.drawPath(card_path)
vm = self._vm
if vm is None:
return
compact = rect.height() < 198.0
pad_x = 18.0
left = rect.left() + pad_x
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,
)
badge_font = QFont(body_family())
badge_font.setPixelSize(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_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)
# 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.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)
painter.drawText(
QRectF(left, metric_y, num_w + 6, 42),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
vm.primary_value,
)
if vm.unit:
unit_font = QFont(body_family())
unit_font.setPixelSize(13 if compact else 14)
painter.setFont(unit_font)
painter.setPen(QColor("#6C827E"))
painter.drawText(
QRectF(left + num_w + 5, metric_y + 8, 66, 28),
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_rect = QRectF(right - delta_w, metric_y + 3, delta_w, 22)
delta_path = QPainterPath()
delta_path.addRoundedRect(delta_rect, 11.0, 11.0)
if vm.delta_tone == "emerald":
painter.fillPath(delta_path, QColor("#E2F3EE"))
painter.setPen(QColor("#0E6F5C"))
elif vm.delta_tone == "coral":
painter.fillPath(delta_path, QColor("#FCEBE6"))
painter.setPen(QColor("#D96243"))
else:
painter.fillPath(delta_path, QColor("#F1F5F4"))
painter.setPen(QColor("#6B807D"))
painter.drawText(delta_rect, Qt.AlignmentFlag.AlignCenter, vm.delta_badge)
sub_caption_font = QFont(body_family())
sub_caption_font.setPixelSize(11)
painter.setFont(sub_caption_font)
painter.setPen(QColor("#7D918E"))
painter.drawText(
QRectF(right - 138, metric_y + 27, 138, 15),
Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
vm.delta_caption,
)
# 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)
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)))
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)
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)
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)
# 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,
)
@@ -0,0 +1,563 @@
"""Three-column Alveo × Serene Clinical Digital Twin Cockpit for ReceptionPage."""
from __future__ import annotations
from collections.abc import Sequence
from datetime import date
from typing import Any
from PySide6.QtCore import QSize, Qt, Signal
from PySide6.QtGui import QFont
from PySide6.QtWidgets import (
QFrame,
QHBoxLayout,
QLabel,
QPushButton,
QScrollArea,
QSizePolicy,
QVBoxLayout,
QWidget,
)
from ...core.appointment_modes import appointment_type_description, appointment_type_value
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 .diurnal_strip import DiurnalStabilityCard
from .journey_track import CareJourneyCard
from .pill_chart import PillProgressionCard
from .twin_stage import ClinicalTwinStageWidget
COCKPIT_QSS = """
QWidget#ReceptionDigitalTwinCockpit {
background: transparent;
}
QFrame#CockpitBentoCard {
background-color: #FFFFFF;
border: 1px solid #E3ECE9;
border-radius: 22px;
}
QPushButton#CockpitFilterPill {
min-height: 24px;
max-height: 24px;
padding: 0 10px;
border-radius: 12px;
border: 0;
background-color: #F2F6F5;
color: #5E7471;
font-size: 11px;
font-weight: 500;
}
QPushButton#CockpitFilterPill:hover {
background-color: #E5F1EE;
color: #0E6F5C;
}
QPushButton#CockpitFilterPill:checked {
background-color: #111918;
color: #FFFFFF;
font-weight: 600;
}
QFrame#TimelineItemCard {
background-color: #F5F8F7;
border: 1px solid transparent;
border-radius: 16px;
}
QFrame#TimelineItemCard:hover {
background-color: #EBF3F0;
border-color: #CFE2DD;
}
QFrame#TimelineItemCard[activeItem="true"] {
background-color: #0E6F5C;
border: 1px solid #0E6F5C;
border-radius: 16px;
}
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;
}
QPushButton#TimelinePlayCircle:hover {
background-color: #E5F6F1;
}
QLabel#TimelineDoneBadge {
min-width: 28px;
max-width: 28px;
min-height: 28px;
max-height: 28px;
border-radius: 14px;
background-color: #E0F2EC;
color: #0E6F5C;
font-size: 12px;
font-weight: 700;
}
QLabel#TimelineWaitBadge {
min-width: 28px;
max-width: 28px;
min-height: 28px;
max-height: 28px;
border-radius: 14px;
background-color: #EAEFED;
color: #6E8380;
font-size: 12px;
}
QPushButton#CareTeamActionPill {
min-width: 32px;
min-height: 30px;
max-height: 30px;
padding: 0 11px;
border-radius: 15px;
background-color: #F3F7F6;
border: 1px solid #E1ECE8;
color: #192E2C;
font-size: 11px;
font-weight: 600;
}
QPushButton#CareTeamActionPill:hover {
background-color: #E2F3EE;
border-color: #9ED0C3;
color: #0E6F5C;
}
QPushButton#CareTeamActionPill:disabled {
color: #9EB0AD;
background-color: #F6F8F8;
}
"""
def _safe_int(val: Any, default: int = 0) -> int:
try:
return int(val)
except (TypeError, ValueError):
return default
class _TimelineRowWidget(QFrame):
"""Single appointment row inside Today's Plan (Alveo solid-emerald active pill)."""
row_clicked = Signal(object)
play_clicked = Signal(object)
def __init__(self, record: Any, *, active: bool, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.record = record
self.setObjectName("TimelineItemCard")
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
self.setProperty("activeItem", active)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setFixedHeight(58)
if active:
self.setStyleSheet(
"QFrame#TimelineItemCard {"
" background-color: #0E6F5C; border: 1px solid #0E6F5C; border-radius: 16px; }"
)
else:
self.setStyleSheet(
"QFrame#TimelineItemCard {"
" background-color: #F5F8F7; border: 1px solid transparent; border-radius: 16px; }"
"QFrame#TimelineItemCard:hover {"
" background-color: #EBF3F0; border: 1px solid #CFE2DD; }"
)
layout = QHBoxLayout(self)
layout.setContentsMargins(14, 8, 12, 8)
layout.setSpacing(10)
# Time + Mode column
time_raw = display_text(
first_value(record, "appointment_time_text", "appointment_time", "time", default="待排期")
)
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]
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.setStyleSheet(
f"color: {'#FFFFFF' if active else '#152725'}; font-size: 13px; font-weight: 600; background: transparent;"
)
m_lbl = QLabel(mode_txt, self)
m_lbl.setFixedWidth(48)
m_lbl.setStyleSheet(
f"color: {'rgba(255,255,255,195)' if active else '#7A908C'}; font-size: 10px; background: transparent;"
)
t_col.addWidget(t_lbl)
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="点击载入四诊详情"),
)
)
if len(chief) > 15:
chief = f"{chief[:14]}…"
c_col = QVBoxLayout()
c_col.setContentsMargins(0, 0, 0, 0)
c_col.setSpacing(1)
n_lbl = QLabel(p_name, 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.setStyleSheet(
f"color: {'rgba(255,255,255,205)' if active else '#6E8380'}; font-size: 11px; background: transparent;"
)
c_col.addWidget(n_lbl)
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.setObjectName("TimelinePlayCircle")
play_btn.setFixedSize(30, 30)
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; }"
"QPushButton#TimelinePlayCircle:hover { background-color: #E6F6F1; }"
)
play_btn.setToolTip("立即发起视频 / IM 问诊")
play_btn.clicked.connect(lambda: self.play_clicked.emit(self.record))
layout.addWidget(play_btn)
elif status == 3:
done_lbl = QLabel("✓", self)
done_lbl.setObjectName("TimelineDoneBadge")
done_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(done_lbl)
else:
wait_lbl = QLabel("•", self)
wait_lbl.setObjectName("TimelineWaitBadge")
wait_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(wait_lbl)
def mousePressEvent(self, event: Any) -> None: # noqa: N802
if event.button() == Qt.MouseButton.LeftButton:
self.row_clicked.emit(self.record)
event.accept()
return
super().mousePressEvent(event)
class ReceptionDigitalTwinCockpit(QWidget):
"""Full Alveo × Serene 3-column Digital Twin Cockpit + 21-Day Journey Track."""
appointment_selected = Signal(object)
filter_status_requested = Signal(object)
refresh_requested = Signal()
start_video_requested = Signal()
edit_diagnosis_requested = Signal()
notify_assistant_requested = Signal()
complete_visit_requested = Signal()
open_chart_tab_requested = Signal(int)
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("ReceptionDigitalTwinCockpit")
self.setStyleSheet(COCKPIT_QSS)
root = QVBoxLayout(self)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(12)
# ── Layer 3: Asymmetric 3-Column Clinical Cockpit ──────────────────
cockpit_row = QHBoxLayout()
cockpit_row.setContentsMargins(0, 0, 0, 0)
cockpit_row.setSpacing(14)
# Column 1 (Left 25%): Glycemic Progression + Diurnal TIR & Mini Vitals
left_wing = QWidget(self)
left_wing.setMinimumWidth(276)
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.diurnal_card = DiurnalStabilityCard(left_wing)
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
self.twin_stage = ClinicalTwinStageWidget(self)
self.twin_stage.locus_clicked.connect(lambda _locus: self.edit_diagnosis_requested.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
right_wing = QWidget(self)
right_wing.setMinimumWidth(286)
right_wing.setMaximumWidth(400)
right_layout = QVBoxLayout(right_wing)
right_layout.setContentsMargins(0, 0, 0, 0)
right_layout.setSpacing(12)
self.plan_card = self._build_today_plan_card(right_wing)
self.team_card = self._build_care_team_card(right_wing)
right_layout.addWidget(self.plan_card, 62)
right_layout.addWidget(self.team_card, 38)
cockpit_row.addWidget(right_wing, 28)
root.addLayout(cockpit_row, 1)
# ── Layer 4A: Bottom 21-Day Care Journey Rounded-Pill 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.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
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)
head = QHBoxLayout()
head.setSpacing(8)
title = QLabel("今日门诊计划", card)
t_font = QFont(heading_family())
t_font.setPixelSize(15)
t_font.setWeight(QFont.Weight.DemiBold)
title.setFont(t_font)
title.setStyleSheet("color: #11201E; background: transparent;")
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;")
head.addWidget(self.plan_date_label)
refresh_btn = QPushButton(card)
refresh_btn.setFixedSize(26, 26)
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.setStyleSheet(
"QPushButton { background: #F3F7F6; border: 0; border-radius: 13px; }"
"QPushButton:hover { background: #E3F2EE; }"
)
refresh_btn.clicked.connect(self.refresh_requested.emit)
head.addWidget(refresh_btn)
layout.addLayout(head)
# Compact status filter 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)
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
chip_row.addWidget(pill)
self._status_pills[1].setChecked(True)
chip_row.addStretch(1)
layout.addLayout(chip_row)
self.timeline_scroll = QScrollArea(card)
self.timeline_scroll.setWidgetResizable(True)
self.timeline_scroll.setFrameShape(QFrame.Shape.NoFrame)
self.timeline_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.timeline_scroll.setStyleSheet("QScrollArea { background: transparent; border: 0; }")
self.timeline_host = QWidget(self.timeline_scroll)
self.timeline_host.setStyleSheet("background: transparent;")
self.timeline_layout = QVBoxLayout(self.timeline_host)
self.timeline_layout.setContentsMargins(0, 0, 2, 0)
self.timeline_layout.setSpacing(8)
self.timeline_layout.addStretch(1)
self.timeline_scroll.setWidget(self.timeline_host)
layout.addWidget(self.timeline_scroll, 1)
return card
def _build_care_team_card(self, parent: QWidget) -> QFrame:
card = QFrame(parent)
card.setObjectName("CockpitBentoCard")
layout = QVBoxLayout(card)
layout.setContentsMargins(18, 14, 18, 14)
layout.setSpacing(8)
head = QHBoxLayout()
title = QLabel("诊疗协作组", card)
t_font = QFont(heading_family())
t_font.setPixelSize(15)
t_font.setWeight(QFont.Weight.DemiBold)
title.setFont(t_font)
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)
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="辨证施治 · 四诊合参",
action_text="编辑病历",
callback=self.edit_diagnosis_requested.emit,
)
self.assistant_name_lbl, self.assistant_role_lbl, self.notify_asst_btn = self._add_team_row(
layout,
avatar_text="助",
avatar_bg="#EDF4F2",
avatar_fg="#2B524C",
name="专属医助",
role="诊前采集 · 院外随访",
action_text="通知医助",
callback=self.notify_assistant_requested.emit,
)
self.pharmacist_name_lbl, self.pharmacist_role_lbl, self.complete_visit_btn = self._add_team_row(
layout,
avatar_text="结",
avatar_bg="#FAF4E6",
avatar_fg="#9E7425",
name="门诊闭环核验",
role="病历归档 · 完成本次接诊",
action_text="完成接诊",
callback=self.complete_visit_requested.emit,
)
return card
def _add_team_row(
self,
parent_layout: QVBoxLayout,
*,
avatar_text: str,
avatar_bg: str,
avatar_fg: str,
name: str,
role: str,
action_text: str,
callback: Any,
) -> tuple[QLabel, QLabel, QPushButton]:
row = QWidget(self)
rl = QHBoxLayout(row)
rl.setContentsMargins(0, 2, 0, 2)
rl.setSpacing(10)
av = QLabel(avatar_text, row)
av.setFixedSize(34, 34)
av.setAlignment(Qt.AlignmentFlag.AlignCenter)
av.setStyleSheet(
f"background-color: {avatar_bg}; color: {avatar_fg}; border-radius: 17px;"
" font-size: 13px; font-weight: 600;"
)
rl.addWidget(av)
meta = QVBoxLayout()
meta.setContentsMargins(0, 0, 0, 0)
meta.setSpacing(1)
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.setStyleSheet("color: #788E8A; font-size: 11px; background: transparent;")
r_lbl.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
meta.addWidget(n_lbl)
meta.addWidget(r_lbl)
rl.addLayout(meta, 1)
btn = QPushButton(action_text, row)
btn.setObjectName("CareTeamActionPill")
btn.setCursor(Qt.CursorShape.PointingHandCursor)
btn.clicked.connect(callback)
rl.addWidget(btn)
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 set_snapshot(self, snapshot: CockpitSnapshotVM) -> None:
self.progression_card.set_view_model(snapshot.progression)
self.diurnal_card.set_view_model(snapshot.diurnal)
self.twin_stage.set_snapshot(snapshot)
self.journey_card.set_view_model(snapshot.journey)
def set_care_team_context(
self,
*,
doctor_name: str,
assistant_name: str,
can_edit: bool,
can_notify: bool,
can_complete: bool,
) -> 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 "待分配医助"
)
self.edit_diag_btn.setEnabled(can_edit)
self.notify_asst_btn.setEnabled(can_notify)
self.complete_visit_btn.setEnabled(can_complete)
def set_queue_records(
self,
records: Sequence[Any],
selected_appointment_id: int | None,
*,
active_filter_status: int | None = 1,
queue_date: str = "",
) -> None:
for k, btn in self._status_pills.items():
btn.setChecked(k == active_filter_status)
if queue_date:
self.plan_date_label.setText(f"{queue_date[5:]} · {len(records)}人")
else:
self.plan_date_label.setText(f"共 {len(records)} 人")
clear_layout(self.timeline_layout)
if not records:
empty = QLabel("当前筛选下暂无门诊挂号\n可切换上方「全部」查看历史接诊", self.timeline_host)
empty.setAlignment(Qt.AlignmentFlag.AlignCenter)
empty.setStyleSheet(
f"color: #7D918E; font-size: 12px; font-family: '{body_family()}';"
" padding: 28px 12px; background: #F7FAF9; border-radius: 14px;"
)
self.timeline_layout.addWidget(empty)
self.timeline_layout.addStretch(1)
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)
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())
self.timeline_layout.addWidget(row_widget)
self.timeline_layout.addStretch(1)
@@ -0,0 +1,556 @@
"""Human Body & Metabolic Visceral Symptom Evidence Map (100% Real Clinical Data)."""
from __future__ import annotations
import math
from PySide6.QtCore import QPointF, QRectF, QSize, Qt, QTimer, Signal
from PySide6.QtGui import (
QColor,
QFont,
QLinearGradient,
QMouseEvent,
QPainter,
QPainterPath,
QPen,
QRadialGradient,
)
from PySide6.QtWidgets import QToolTip, QWidget
from .. import motion
from ..reception_style import body_family, heading_family
from ..viewmodels.cockpit_vm import CockpitSnapshotVM, TwinCalloutNode
_MODES: tuple[tuple[str, str], ...] = (
("sanjiao", "全身症候"),
("organ", "病史用药"),
("tcm", "四诊处方"),
)
class ClinicalTwinStageWidget(QWidget):
"""Center human body & metabolic organ symptom map bound strictly to real case data."""
mode_changed = Signal(str)
locus_clicked = Signal(str)
open_chart_requested = Signal()
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("ClinicalTwinStageWidget")
self.setMouseTracking(True)
self.setMinimumSize(400, 320)
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._hover_target = ""
self._anim_timer = QTimer(self)
self._anim_timer.setInterval(100)
self._anim_timer.timeout.connect(self._tick_breath)
def sizeHint(self) -> QSize: # noqa: N802
return QSize(580, 500)
def showEvent(self, event: object) -> None: # noqa: N802
super().showEvent(event) # type: ignore[arg-type]
if not motion.reduced_motion():
self._anim_timer.start()
def hideEvent(self, event: object) -> None: # noqa: N802
self._anim_timer.stop()
super().hideEvent(event) # type: ignore[arg-type]
def _tick_breath(self) -> None:
self._phase = (self._phase + 0.14) % (math.pi * 2.0)
if self._snapshot and self._snapshot.has_patient:
self.update()
def set_snapshot(self, snapshot: CockpitSnapshotVM) -> None:
self._snapshot = snapshot
self.update()
def set_mode(self, mode_key: str) -> None:
if mode_key in {"sanjiao", "organ", "tcm"} and mode_key != self._mode_key:
self._mode_key = mode_key
self.mode_changed.emit(mode_key)
self.update()
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
pos = event.position()
target = ""
if self._open_chart_rect.contains(pos):
target = "open_chart"
if not target:
for key, r in self._mode_rects:
if r.contains(pos):
target = f"mode:{key}"
break
if not target:
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
self.setCursor(
Qt.CursorShape.PointingHandCursor if target else Qt.CursorShape.ArrowCursor
)
if target != self._hover_target:
self._hover_target = target
self.update()
super().mouseMoveEvent(event)
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802
if event.button() == Qt.MouseButton.LeftButton:
pos = event.position()
if self._open_chart_rect.contains(pos):
self.open_chart_requested.emit()
event.accept()
return
for key, r in self._mode_rects:
if r.contains(pos):
self.set_mode(key)
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
super().mousePressEvent(event)
def _draw_human_metabolic_twin(
self,
painter: QPainter,
rect: QRectF,
zone_heats: tuple[float, float, float, float],
*,
dimmed: bool = False,
) -> None:
"""Paint an anatomical translucent Jade-Crystal Human Body & Metabolic Organs Twin."""
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))
alpha_mul = 0.42 if dimmed else 1.0
def _c(r_v: int, g_v: int, b_v: int, a_v: int) -> QColor:
return QColor(r_v, g_v, b_v, int(a_v * alpha_mul))
# 1. Outer Human Head + Neck + Shoulders + Torso + Pelvis Crystal Silhouette
body = QPainterPath()
# Head ellipse
head_cy = cy - 126 * scale
body.addEllipse(QPointF(cx, head_cy), 25 * scale, 30 * scale)
torso = QPainterPath()
torso.moveTo(cx - 11 * scale, cy - 96 * scale)
# Left neck -> left shoulder -> left flank -> hip -> leg root
torso.quadTo(cx - 14 * scale, cy - 84 * scale, cx - 58 * scale, cy - 74 * scale)
torso.cubicTo(
cx - 78 * scale,
cy - 68 * scale,
cx - 76 * scale,
cy - 20 * scale,
cx - 60 * scale,
cy + 28 * scale,
)
torso.cubicTo(
cx - 54 * scale,
cy + 62 * scale,
cx - 58 * scale,
cy + 98 * scale,
cx - 44 * scale,
cy + 138 * scale,
)
torso.lineTo(cx - 14 * scale, cy + 138 * scale)
torso.quadTo(cx, cy + 108 * scale, cx + 14 * scale, cy + 138 * scale)
torso.lineTo(cx + 44 * scale, cy + 138 * scale)
torso.cubicTo(
cx + 58 * scale,
cy + 98 * scale,
cx + 54 * scale,
cy + 62 * scale,
cx + 60 * scale,
cy + 28 * scale,
)
torso.cubicTo(
cx + 76 * scale,
cy - 20 * scale,
cx + 78 * scale,
cy - 68 * scale,
cx + 58 * scale,
cy - 74 * scale,
)
torso.quadTo(cx + 14 * scale, cy - 84 * scale, cx + 11 * scale, cy - 96 * scale)
torso.closeSubpath()
body_grad = QLinearGradient(cx, cy - 155 * scale, cx, cy + 140 * scale)
body_grad.setColorAt(0.0, _c(216, 240, 234, 185))
body_grad.setColorAt(0.5, _c(132, 198, 184, 128))
body_grad.setColorAt(1.0, _c(64, 142, 128, 145))
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.fillPath(body, body_grad)
painter.fillPath(torso, body_grad)
painter.setPen(QPen(_c(255, 255, 255, 210), 2.0))
painter.drawPath(body)
painter.drawPath(torso)
painter.setPen(QPen(_c(16, 106, 90, 95), 1.1))
painter.drawPath(body)
painter.drawPath(torso)
# 2. Internal Target Organs of Diabetes & TCM Sanjiao:
# (A) Central Esophagus / Meridian Conduit
painter.setPen(QPen(_c(255, 255, 255, 150), 2.2, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
painter.drawLine(QPointF(cx, cy - 94 * scale), QPointF(cx, cy + 92 * scale))
painter.setPen(QPen(_c(14, 111, 92, 95), 1.0, Qt.PenStyle.DashLine))
painter.drawLine(QPointF(cx, cy - 135 * scale), QPointF(cx, cy + 115 * scale))
# (B) Upper Thoracic Cardiopulmonary Shield (subtle paired translucent chambers)
for sign in (-1.0, 1.0):
chest = QPainterPath()
chest.moveTo(cx + sign * 6 * scale, cy - 66 * scale)
chest.cubicTo(
cx + sign * 38 * scale,
cy - 70 * scale,
cx + sign * 46 * scale,
cy - 34 * scale,
cx + sign * 40 * scale,
cy - 12 * scale,
)
chest.quadTo(cx + sign * 18 * scale, cy - 8 * scale, cx + sign * 6 * scale, cy - 22 * scale)
chest.closeSubpath()
painter.fillPath(chest, _c(255, 255, 255, 76))
painter.setPen(QPen(_c(14, 111, 92, 78), 1.0))
painter.drawPath(chest)
# (C) Liver ( Anatomical Right = Viewer Left ) & Stomach/Spleen ( Viewer Right )
liver = QPainterPath()
liver.moveTo(cx - 42 * scale, cy - 2 * scale)
liver.cubicTo(cx - 18 * scale, cy - 6 * scale, cx + 6 * scale, cy + 2 * scale, cx + 8 * scale, cy + 14 * scale)
liver.cubicTo(cx - 12 * scale, cy + 26 * scale, cx - 38 * scale, cy + 28 * scale, cx - 42 * scale, cy - 2 * scale)
painter.fillPath(liver, _c(22, 124, 104, 115))
painter.setPen(QPen(_c(255, 255, 255, 165), 1.1))
painter.drawPath(liver)
# (D) Pancreas (胰岛核心 — Golden-Jade leaf across mid-abdomen!)
pancreas = QPainterPath()
pancreas.moveTo(cx - 14 * scale, cy + 22 * scale)
pancreas.cubicTo(cx + 6 * scale, cy + 14 * scale, cx + 28 * scale, cy + 18 * scale, cx + 36 * scale, cy + 26 * scale)
pancreas.cubicTo(cx + 24 * scale, cy + 36 * scale, cx + 2 * scale, cy + 36 * scale, cx - 14 * scale, cy + 22 * scale)
panc_grad = QLinearGradient(cx - 14 * scale, cy + 16 * scale, cx + 36 * scale, cy + 34 * scale)
panc_grad.setColorAt(0.0, _c(223, 199, 147, 195))
panc_grad.setColorAt(1.0, _c(14, 111, 92, 155))
painter.fillPath(pancreas, panc_grad)
painter.setPen(QPen(_c(255, 255, 255, 195), 1.2))
painter.drawPath(pancreas)
# (E) Bilateral Kidneys & Lower-Limb Microvascular Branches
for sign in (-1.0, 1.0):
kx = cx + sign * 22 * scale
ky = cy + 56 * scale
kidney = QPainterPath()
kidney.addRoundedRect(QRectF(kx - 9 * scale, ky - 14 * scale, 18 * scale, 28 * scale), 9 * scale, 9 * scale)
painter.fillPath(kidney, _c(20, 112, 96, 120))
painter.setPen(QPen(_c(255, 255, 255, 165), 1.0))
painter.drawPath(kidney)
# Peripheral nerve / vessel line down into lower limbs
painter.setPen(QPen(_c(14, 111, 92, 95), 1.2))
painter.drawLine(QPointF(kx, ky + 14 * scale), QPointF(cx + sign * 28 * scale, cy + 128 * scale))
if dimmed:
return
# 3. Real Positive-Symptom Focal Glows (ONLY where real case data has findings!)
breath = 1.0 + 0.07 * math.sin(self._phase)
zone_coords = (
(cx, head_cy, zone_heats[0]), # Head / Eye / Sleep
(cx + 12 * scale, cy - 42 * scale, zone_heats[1]), # Oral / Thirst / Upper
(cx - 10 * scale, cy + 18 * scale, zone_heats[2]), # Liver / Pancreas / Glucose
(cx + 22 * scale, cy + 64 * scale, zone_heats[3]), # Kidney / Limbs
)
for lx, ly, heat in zone_coords:
if heat <= 0.05:
continue
r = (22.0 + heat * 22.0) * scale * breath
glow = QRadialGradient(QPointF(lx, ly), r)
if heat >= 0.5:
glow.setColorAt(0.0, QColor(228, 98, 62, int(185 * heat)))
glow.setColorAt(0.5, QColor(242, 152, 98, int(105 * heat)))
glow.setColorAt(1.0, QColor(242, 152, 98, 0))
else:
glow.setColorAt(0.0, QColor(14, 138, 108, 105))
glow.setColorAt(1.0, QColor(14, 138, 108, 0))
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(glow)
painter.drawEllipse(QPointF(lx, ly), r, r)
# Serene-style clean axis nodes
for ay in (head_cy, cy - 42 * scale, cy + 22 * scale, cy + 60 * scale):
painter.setPen(QPen(QColor(255, 255, 255, 175), 1.0))
painter.setBrush(QColor(255, 255, 255, 65))
painter.drawEllipse(QPointF(cx, ay), 5.0 * scale, 5.0 * scale)
def _draw_callout(
self,
painter: QPainter,
stage_rect: QRectF,
node: TwinCalloutNode,
) -> QRectF:
ax = stage_rect.left() + stage_rect.width() * node.anchor_x
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
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))
if node.side == "left":
cx = stage_rect.left() + 16.0
line_start = QPointF(cx + card_w, cy + card_h * 0.5)
else:
cx = stage_rect.right() - card_w - 16.0
line_start = QPointF(cx, cy + card_h * 0.5)
card_rect = QRectF(cx, cy, card_w, card_h)
tone_map = {
"coral": ("#E06D4C", "#FCEBE6", "#C85232"),
"gold": ("#C48B28", "#FDF5E6", "#9E6D14"),
"emerald": ("#0E6F5C", "#E2F3EE", "#0E6F5C"),
"neutral": ("#94A8A4", "#F1F5F4", "#667C79"),
}
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.drawLine(line_start, anchor)
painter.setPen(QPen(QColor("#FFFFFF"), 2.0))
painter.setBrush(QColor(dot_hex))
painter.drawEllipse(anchor, 5.2, 5.2)
hovered = self._hover_target == f"locus:{node.locus_id}"
cpath = QPainterPath()
cpath.addRoundedRect(card_rect, 15.0, 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)
badge_font = QFont(body_family())
badge_font.setPixelSize(10)
badge_font.setWeight(QFont.Weight.DemiBold)
painter.setFont(badge_font)
bw = min(card_w - 22.0, float(painter.fontMetrics().horizontalAdvance(f"• {node.status_text}") + 16))
b_rect = QRectF(card_rect.left() + 11, card_rect.top() + 9, bw, 19)
b_path = QPainterPath()
b_path.addRoundedRect(b_rect, 9.5, 9.5)
painter.fillPath(b_path, QColor(pill_bg_hex))
painter.setPen(QColor(pill_fg_hex))
painter.drawText(b_rect, Qt.AlignmentFlag.AlignCenter, f"• {node.status_text}")
t_font = QFont(heading_family())
t_font.setPixelSize(12)
t_font.setWeight(QFont.Weight.DemiBold)
painter.setFont(t_font)
painter.setPen(QColor("#11201E"))
painter.drawText(
QRectF(card_rect.left() + 11, card_rect.top() + 32, card_w - 22, 18),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
node.title,
)
d_font = QFont(body_family())
d_font.setPixelSize(11)
painter.setFont(d_font)
painter.setPen(QColor("#627875"))
elided = painter.fontMetrics().elidedText(
node.detail, Qt.TextElideMode.ElideRight, int(card_w - 22)
)
painter.drawText(
QRectF(card_rect.left() + 11, card_rect.top() + 51, card_w - 22, 17),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
elided,
)
return card_rect
def paintEvent(self, _event: object) -> None: # noqa: N802
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
rect = QRectF(self.rect()).adjusted(1.0, 1.0, -1.0, -1.0)
stage_path = QPainterPath()
stage_path.addRoundedRect(rect, 24.0, 24.0)
bg_grad = QRadialGradient(rect.center(), max(rect.width(), rect.height()) * 0.62)
bg_grad.setColorAt(0.0, QColor("#FAFCFB"))
bg_grad.setColorAt(0.75, QColor("#F3F7F5"))
bg_grad.setColorAt(1.0, QColor("#ECF2F0"))
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.fillPath(stage_path, bg_grad)
painter.setPen(QPen(QColor("#E1EBE8"), 1.0))
painter.drawPath(stage_path)
cx = rect.center().x()
cy = rect.center().y() + 4.0
min_dim = min(rect.width(), rect.height())
scale = max(0.72, min(1.18, min_dim / 490.0))
for radius_factor, dashed in ((175.0, False), (132.0, True)):
r = radius_factor * scale
painter.setPen(
QPen(
QColor(188, 210, 204, 95),
1.0,
Qt.PenStyle.DashLine if dashed else Qt.PenStyle.SolidLine,
)
)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawEllipse(QPointF(cx, cy), r, r)
# Top Segmented Mode Pill Island: [全身症候 / 病史用药 / 四诊处方]
pill_host = QRectF(rect.left() + 16, rect.top() + 14, 246, 34)
pill_host_path = QPainterPath()
pill_host_path.addRoundedRect(pill_host, 17.0, 17.0)
painter.fillPath(pill_host_path, QColor("#FFFFFF"))
painter.setPen(QPen(QColor("#E2ECE9"), 1.0))
painter.drawPath(pill_host_path)
mode_font = QFont(body_family())
mode_font.setPixelSize(12)
self._mode_rects.clear()
seg_w = (pill_host.width() - 8.0) / len(_MODES)
for idx, (m_key, m_label) in enumerate(_MODES):
m_rect = QRectF(pill_host.left() + 4.0 + idx * seg_w, pill_host.top() + 3.0, seg_w, 28.0)
self._mode_rects.append((m_key, m_rect))
active = m_key == self._mode_key
if active:
mp = QPainterPath()
mp.addRoundedRect(m_rect, 14.0, 14.0)
painter.fillPath(mp, QColor("#111918"))
mode_font.setWeight(QFont.Weight.DemiBold if active else QFont.Weight.Medium)
painter.setFont(mode_font)
painter.setPen(QColor("#FFFFFF") if active else QColor("#5A706D"))
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)
cb_path = QPainterPath()
cb_path.addRoundedRect(self._open_chart_rect, 16.0, 16.0)
cb_hover = self._hover_target == "open_chart"
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.fillPath(cb_path, QColor("#E2F3EE" if cb_hover else "#FFFFFF"))
painter.setPen(QPen(QColor("#0E6F5C" if cb_hover else "#DCE7E4"), 1.0))
painter.drawPath(cb_path)
mode_font.setPixelSize(11)
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, "原始详单 ↗")
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)
sp = QPainterPath()
sp.addRoundedRect(scan_rect, 16.0, 16.0)
painter.fillPath(sp, QColor("#FFFFFF"))
painter.setPen(QPen(QColor("#E3ECE9"), 1.0))
painter.drawPath(sp)
mode_font.setWeight(QFont.Weight.Normal)
painter.setFont(mode_font)
painter.setPen(QColor("#5C7270"))
painter.drawText(scan_rect, Qt.AlignmentFlag.AlignCenter, vm.scan_badge)
has_pat = bool(vm and vm.has_patient)
self._draw_human_metabolic_twin(
painter,
rect,
vm.recorded_Zone_flags if vm else (0.0, 0.0, 0.0, 0.0),
dimmed=not has_pat,
)
self._callout_rects.clear()
if not has_pat:
# Honest Centered Guidance Card when no patient is selected
empty_box = QRectF(cx - 195, cy - 44, 390, 88)
ep = QPainterPath()
ep.addRoundedRect(empty_box, 18.0, 18.0)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.fillPath(ep, QColor(255, 255, 255, 242))
painter.setPen(QPen(QColor("#DCE8E5"), 1.0))
painter.drawPath(ep)
et_font = QFont(heading_family())
et_font.setPixelSize(15)
et_font.setWeight(QFont.Weight.DemiBold)
painter.setFont(et_font)
painter.setPen(QColor("#132523"))
painter.drawText(
QRectF(empty_box.left() + 16, empty_box.top() + 14, empty_box.width() - 32, 22),
Qt.AlignmentFlag.AlignCenter,
vm.empty_title if vm else "尚未选择接诊患者",
)
es_font = QFont(body_family())
es_font.setPixelSize(11)
painter.setFont(es_font)
painter.setPen(QColor("#677E7A"))
painter.drawText(
QRectF(empty_box.left() + 18, empty_box.top() + 40, empty_box.width() - 36, 36),
Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWordWrap,
vm.empty_subtitle if vm else "请在右侧队列点击任意患者以载入真实病历",
)
elif vm is not 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))
# 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)
wpath = QPainterPath()
wpath.addRoundedRect(cap_rect, 16.0, 16.0)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.fillPath(wpath, QColor("#FFFFFF"))
painter.setPen(QPen(QColor("#E1EBE8"), 1.0))
painter.drawPath(wpath)
if vm is not None:
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor("#E1F3EE" if vm.has_patient else "#EEF3F1"))
painter.drawEllipse(QPointF(cap_rect.left() + 16, cap_rect.center().y()), 9.0, 9.0)
painter.setBrush(QColor("#0E6F5C" if vm.has_patient else "#95A8A4"))
painter.drawEllipse(QPointF(cap_rect.left() + 16, cap_rect.center().y()), 3.5, 3.5)
b_font = QFont(body_family())
b_font.setPixelSize(11)
b_font.setWeight(QFont.Weight.Medium)
painter.setFont(b_font)
painter.setPen(QColor("#1A2E2C" if vm.has_patient else "#758A86"))
elided_bar = painter.fontMetrics().elidedText(
vm.bottom_capsule_text, Qt.TextElideMode.ElideRight, int(cap_w - 38)
)
painter.drawText(
QRectF(cap_rect.left() + 31, cap_rect.top(), cap_w - 40, cap_rect.height()),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
elided_bar,
)
@@ -0,0 +1,165 @@
"""Serene.ai-inspired horizontal 7-day calendar strip with appointment density dots."""
from __future__ import annotations
from datetime import date, timedelta
from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal
from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen
from PySide6.QtWidgets import QWidget
from ..reception_style import body_family, number_family
_WEEKDAY_CN = ("周一", "周二", "周三", "周四", "周五", "周六", "周日")
class WeekCalendarStripWidget(QWidget):
"""Lightweight 7-day week selector strip inspired by Serene.ai's top-right calendar."""
date_selected = Signal(str)
def __init__(self, selected: date | None = None, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("WeekCalendarStripWidget")
self.setMouseTracking(True)
self.setFixedHeight(58)
self.setMinimumWidth(420)
self._selected = selected or date.today()
self._anchor_monday = self._selected - timedelta(days=self._selected.weekday())
self._counts: dict[str, int] = {}
self._day_rects: list[tuple[date, QRectF]] = []
self._prev_rect = QRectF()
self._next_rect = QRectF()
def sizeHint(self) -> QSize: # noqa: N802
return QSize(560, 58)
@property
def selected_date(self) -> date:
return self._selected
def set_selected_date(self, target: date, *, emit_signal: bool = False) -> None:
self._selected = target
self._anchor_monday = target - timedelta(days=target.weekday())
self.update()
if emit_signal:
self.date_selected.emit(target.isoformat())
def set_day_counts(self, counts: dict[str, int]) -> None:
self._counts = dict(counts)
self.update()
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
pos = event.position()
clickable = (
self._prev_rect.contains(pos)
or self._next_rect.contains(pos)
or any(r.contains(pos) for _, r in self._day_rects)
)
self.setCursor(Qt.CursorShape.PointingHandCursor if clickable else Qt.CursorShape.ArrowCursor)
super().mouseMoveEvent(event)
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802
if event.button() == Qt.MouseButton.LeftButton:
pos = event.position()
if self._prev_rect.contains(pos):
self._anchor_monday -= timedelta(days=7)
self.set_selected_date(self._selected - timedelta(days=7), emit_signal=True)
event.accept()
return
if self._next_rect.contains(pos):
self._anchor_monday += timedelta(days=7)
self.set_selected_date(self._selected + timedelta(days=7), emit_signal=True)
event.accept()
return
for day_val, r in self._day_rects:
if r.contains(pos):
self.set_selected_date(day_val, emit_signal=True)
event.accept()
return
super().mousePressEvent(event)
def paintEvent(self, _event: object) -> None: # noqa: N802
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
rect = QRectF(self.rect())
month_font = QFont(body_family())
month_font.setPixelSize(12)
month_font.setWeight(QFont.Weight.Medium)
painter.setFont(month_font)
painter.setPen(QColor("#788E8A"))
left_month = f"{self._anchor_monday.month}月"
sunday = self._anchor_monday + timedelta(days=6)
right_month = f"{(sunday + timedelta(days=1)).month}月"
painter.drawText(QRectF(rect.left() + 4, rect.top() + 18, 38, 22), Qt.AlignmentFlag.AlignRight, left_month)
self._prev_rect = QRectF(rect.left() + 48, rect.top() + 15, 28, 28)
self._next_rect = QRectF(rect.right() - 76, rect.top() + 15, 28, 28)
for nav_rect, symbol in ((self._prev_rect, "‹"), (self._next_rect, "›")):
np = QPainterPath()
np.addEllipse(nav_rect)
painter.fillPath(np, QColor("#FFFFFF"))
painter.setPen(QPen(QColor("#E1EBE8"), 1.0))
painter.drawPath(np)
painter.setPen(QColor("#283C3A"))
painter.drawText(nav_rect.adjusted(0, -1, 0, 0), Qt.AlignmentFlag.AlignCenter, symbol)
painter.setPen(QColor("#788E8A"))
painter.drawText(QRectF(rect.right() - 42, rect.top() + 18, 38, 22), Qt.AlignmentFlag.AlignLeft, right_month)
days_left = self._prev_rect.right() + 12.0
days_right = self._next_rect.left() - 12.0
col_w = max(38.0, (days_right - days_left) / 7.0)
num_font = QFont(number_family())
num_font.setPixelSize(18)
wk_font = QFont(body_family())
wk_font.setPixelSize(11)
self._day_rects.clear()
for idx in range(7):
d = self._anchor_monday + timedelta(days=idx)
cx = days_left + idx * col_w
cell_rect = QRectF(cx + 3.0, rect.top() + 3.0, col_w - 6.0, rect.height() - 6.0)
self._day_rects.append((d, cell_rect))
is_sel = d == self._selected
if is_sel:
sp = QPainterPath()
sp.addRoundedRect(cell_rect, 14.0, 14.0)
painter.fillPath(sp, QColor("#FFFFFF"))
painter.setPen(QPen(QColor("#D9E6E3"), 1.0))
painter.drawPath(sp)
num_font.setWeight(QFont.Weight.DemiBold if is_sel else QFont.Weight.Normal)
painter.setFont(num_font)
painter.setPen(QColor("#101817") if is_sel else QColor("#6E8380"))
painter.drawText(
QRectF(cell_rect.left(), cell_rect.top() + 4, cell_rect.width(), 24),
Qt.AlignmentFlag.AlignCenter,
f"{d.day:02d}" if d.day < 10 else str(d.day),
)
# Serene.ai subtle vertical status dots next to day number
iso = d.isoformat()
cnt = self._counts.get(iso, 2 if d == date.today() else (1 if idx in (0, 2, 4) else 0))
if cnt > 0 or is_sel:
dot_x = cell_rect.center().x() + 14.0
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor("#E06D4C" if is_sel else "#8DA4A0"))
painter.drawEllipse(QPointF(dot_x, cell_rect.top() + 14.0), 2.1, 2.1)
if cnt > 1:
painter.setBrush(QColor("#0E6F5C"))
painter.drawEllipse(QPointF(dot_x, cell_rect.top() + 20.0), 2.0, 2.0)
wk_font.setWeight(QFont.Weight.DemiBold if is_sel else QFont.Weight.Normal)
painter.setFont(wk_font)
painter.setPen(QColor("#11201E") if is_sel else QColor("#879B97"))
painter.drawText(
QRectF(cell_rect.left(), cell_rect.top() + 29, cell_rect.width(), 16),
Qt.AlignmentFlag.AlignCenter,
"今日" if d == date.today() else _WEEKDAY_CN[d.weekday()],
)
+191
View File
@@ -0,0 +1,191 @@
"""End-to-end verification of Clinical OS 3.0 Spatial Shell & Digital Twin Cockpit."""
from __future__ import annotations
import os
from datetime import date, timedelta
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication
from doctor_workstation.core.permissions import PermissionSet
from doctor_workstation.services.demo_repository import DEMO_PERMISSIONS, DemoDoctorRepository
from doctor_workstation.ui.shell_spatial import SpatialShellWindow
from doctor_workstation.ui.state import PatientContextStore
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:
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_patient_context_store_broadcasts_snapshots_and_modes() -> None:
store = PatientContextStore()
seen_names: list[str] = []
sheet_states: list[bool] = []
store.active_patient_changed.connect(lambda snap: seen_names.append(snap.patient_name))
store.bottom_sheet_mode_changed.connect(sheet_states.append)
snap = store.update_from_reception(
{"id": 101, "patient_name": "林晓岚", "status": 1, "appointment_time": "09:30"},
{"id": 201, "gender": 2, "age": 46, "phone": "13800138000"},
{"id": 501, "clinical_diagnosis": "2型糖尿病", "disease_course_text": "8年"},
)
assert snap.has_patient
assert snap.patient_name == "林晓岚"
assert snap.appointment_id == 101
assert snap.diagnosis_id == 501
assert "46岁" in snap.subtitle_line
assert seen_names == ["林晓岚"]
assert store.toggle_bottom_sheet() is True
assert store.toggle_bottom_sheet() is False
assert sheet_states == [True, False]
store.clear()
assert not store.current_patient.has_patient
assert seen_names[-1] == "未选择患者"
def test_cockpit_viewmodel_derives_three_jiao_journey_and_aurora_cards() -> None:
vm = derive_cockpit_snapshot(
{"id": 11, "patient_name": "张建国", "status": 1},
{"height": 172, "weight": 78},
{
"id": 511,
"hba1c": 7.6,
"fasting_blood_sugar": 7.8,
"chief_complaint": "晨起口渴多饮,伴乏力夜尿频",
"tongue": "舌红少津",
"pulse": "脉弦细",
"diagnosis_date": (date.today() - timedelta(days=11)).isoformat(),
},
ai_payload={
"diagnosis_advice": "气阴两虚夹肝郁燥热,宜益气生津疏肝。",
"treatment_advice": "玉女煎合生脉散加减",
"risk_assessment": [{"label": "黎明血糖抬升", "level": "medium"}],
},
active_ai_model="qwen",
)
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
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.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
def test_spatial_shell_zero_sidebar_cockpit_and_cross_page_flow(
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(1600, 940)
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()
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)
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)
_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
assert not shell.ai_bottom_sheet.is_expanded
shell.toggle_ai_bottom_sheet()
_settle(application, 6)
assert shell.ai_bottom_sheet.is_expanded
assert shell.ai_bottom_sheet.height() > 200
expanded_img = shell.grab().toImage()
assert not expanded_img.isNull()
shell.toggle_ai_bottom_sheet()
_settle(application, 4)
assert not shell.ai_bottom_sheet.is_expanded
# 5. Navigate to Schedule (AppointmentsPage) & verify 7-day WeekCalendarStripWidget
assert shell.navigate("appointments")
_settle(application, 16)
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)
page = shell.pages[route_key]
assert hasattr(page, "spatial_bridge")
assert page.spatial_bridge.isVisible()
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()