diff --git a/app/src/doctor_workstation/__init__.py b/app/src/doctor_workstation/__init__.py index d616d4472..3ee773a9c 100755 --- a/app/src/doctor_workstation/__init__.py +++ b/app/src/doctor_workstation/__init__.py @@ -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" diff --git a/app/src/doctor_workstation/app.py b/app/src/doctor_workstation/app.py index cca422dd0..86c065a3e 100755 --- a/app/src/doctor_workstation/app.py +++ b/app/src/doctor_workstation/app.py @@ -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) diff --git a/app/src/doctor_workstation/ui/__init__.py b/app/src/doctor_workstation/ui/__init__.py index 1db885b24..b648f4d45 100755 --- a/app/src/doctor_workstation/ui/__init__.py +++ b/app/src/doctor_workstation/ui/__init__.py @@ -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"] diff --git a/app/src/doctor_workstation/ui/pages/appointments.py b/app/src/doctor_workstation/ui/pages/appointments.py index 0cee7b74a..2a0523ad8 100755 --- a/app/src/doctor_workstation/ui/pages/appointments.py +++ b/app/src/doctor_workstation/ui/pages/appointments.py @@ -67,7 +67,9 @@ from ..filter_disclosure import FilterDisclosure from ..icons import icon from ..infinite_list import InfiniteList from ..reception_style import heading_family +from ..state import PatientContextStore from ..theme import mark_business_dialog +from ..visuals.week_strip import WeekCalendarStripWidget from ..widgets import ( MessageBanner, PageHeader, @@ -106,11 +108,11 @@ NOTE_LIMIT = 500 TABLE_CELL_VERTICAL_PADDING = 10 _SEMANTIC_COLORS = { - "success": "#273244", - "warning": "#273244", + "success": "#273244", + "warning": "#273244", "danger": "#BE4B58", - "info": "#1555B6", - "muted": "#5D6B80", + "info": "#1555B6", + "muted": "#5D6B80", } @@ -250,9 +252,9 @@ def prescription_action_label(row: Any) -> str: ) if not has_prescription: return "开方" - if voided == 1: - return "重新开方" - return "查看" if audit == 1 else "编辑处方" + if voided == 1: + return "重新开方" + return "查看" if audit == 1 else "编辑处方" def _patient_cell(_value: Any, row: Any, *, can_plain: bool) -> str: @@ -329,8 +331,8 @@ def _appointment_info_cell(_value: Any, row: Any) -> str: channel = display_text( first_value(row, "channel_name", "channel_source_name", "source_name"), "—" ) - mode = appointment_type_description(appointment_type_value(row)) - return f"{status} {doctor}\n{date_text} {time_text} · {mode}\n最近渠道:{channel}" + mode = appointment_type_description(appointment_type_value(row)) + return f"{status} {doctor}\n{date_text} {time_text} · {mode}\n最近渠道:{channel}" def _revisit_cell(_value: Any, row: Any) -> str: @@ -468,10 +470,10 @@ class AppointmentsPage(QWidget): current_user: Any = None, parent: QWidget | None = None, ) -> None: - super().__init__(parent) - self.setObjectName("AppointmentsPage") - self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) - self.setStyleSheet(appointments_stylesheet()) + super().__init__(parent) + self.setObjectName("AppointmentsPage") + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self.setStyleSheet(appointments_stylesheet()) self.repository = repository self.permissions = permissions self.current_user = current_user @@ -501,25 +503,52 @@ class AppointmentsPage(QWidget): self._is_admin = _is_admin_user(current_user) root = QVBoxLayout(self) - root.setContentsMargins(30, 18, 27, 8) - root.setSpacing(12) - self.header = PageHeader("挂号列表", "管理当日与近期挂号,确认到号、指派医助并进入接诊。") - self.header.setMinimumHeight(101) - self.header.layout().setSpacing(18) - self.header.layout().setAlignment(Qt.AlignmentFlag.AlignTop) - breadcrumb = self.header.layout().itemAt(0).layout() - for index in range(breadcrumb.count()): - label = breadcrumb.itemAt(index).widget() - if label is not None: - label.setFixedHeight(18) - self.header.actions.setAlignment(Qt.AlignmentFlag.AlignTop) - self.header.layout().itemAt(1).layout().itemAt(0).layout().setSpacing(10) - self.header.set_compact(True) - root.addWidget(self.header) - self.filter_panel = self._build_filter_panel() - root.addWidget(self.filter_panel) - self.filter_disclosure = FilterDisclosure(self, [self.filter_panel]) - self.header.add_action(self.filter_disclosure.button) + self._root_layout = root + root.setContentsMargins(30, 18, 27, 8) + root.setSpacing(12) + self.patient_context_store: PatientContextStore | None = None + self.header = PageHeader("挂号列表", "管理当日与近期挂号,确认到号、指派医助并进入接诊。") + self.header.setMinimumHeight(101) + self.header.layout().setSpacing(18) + self.header.layout().setAlignment(Qt.AlignmentFlag.AlignTop) + breadcrumb = self.header.layout().itemAt(0).layout() + for index in range(breadcrumb.count()): + label = breadcrumb.itemAt(index).widget() + if label is not None: + label.setFixedHeight(18) + self.header.actions.setAlignment(Qt.AlignmentFlag.AlignTop) + self.header.layout().itemAt(1).layout().itemAt(0).layout().setSpacing(10) + self.header.set_compact(True) + root.addWidget(self.header) + self.spatial_week_card = QFrame(self) + self.spatial_week_card.setObjectName("SpatialScheduleWeekCard") + self.spatial_week_card.setVisible(False) + self.spatial_week_card.setStyleSheet( + "QFrame#SpatialScheduleWeekCard {" + " background-color: #FFFFFF; border: 1px solid #E1ECE8; border-radius: 22px; }" + ) + sw_layout = QHBoxLayout(self.spatial_week_card) + sw_layout.setContentsMargins(16, 6, 18, 6) + sw_layout.setSpacing(12) + self.week_strip = WeekCalendarStripWidget(date.today(), self.spatial_week_card) + self.week_strip.date_selected.connect(self._on_week_strip_date_selected) + sw_layout.addWidget(self.week_strip, 1) + self.week_all_dates_btn = QPushButton("不限日期", self.spatial_week_card) + self.week_all_dates_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.week_all_dates_btn.setFixedHeight(32) + self.week_all_dates_btn.setStyleSheet( + "QPushButton { background: #F2F6F5; color: #243836; border: 1px solid #DCE7E4;" + " border-radius: 16px; padding: 0 14px; font-size: 12px; font-weight: 600; }" + "QPushButton:hover { background: #E3F3EE; color: #0E6F5C; }" + ) + self.week_all_dates_btn.clicked.connect(lambda: self._set_date_preset("")) + sw_layout.addWidget(self.week_all_dates_btn) + self._spatial_week_actions = sw_layout + root.addWidget(self.spatial_week_card) + self.filter_panel = self._build_filter_panel() + root.addWidget(self.filter_panel) + self.filter_disclosure = FilterDisclosure(self, [self.filter_panel]) + self.header.add_action(self.filter_disclosure.button) self.banner = MessageBanner() root.addWidget(self.banner) self.content_host = self._build_content() @@ -527,9 +556,27 @@ class AppointmentsPage(QWidget): self.poll_timer = QTimer(self) self.poll_timer.setInterval(LIST_POLL_MS) - self.poll_timer.timeout.connect(self._poll_refresh) + self.poll_timer.timeout.connect(self._poll_refresh) self._apply_responsive_layout() + def set_patient_context_store(self, store: PatientContextStore) -> None: + self.patient_context_store = store + self._root_layout.setContentsMargins(2, 2, 2, 4) + self.header.setVisible(False) + self.filter_disclosure.button.setParent(self.spatial_week_card) + self.filter_disclosure.button.show() + self._spatial_week_actions.addWidget(self.filter_disclosure.button) + self.spatial_week_card.setVisible(True) + + def _on_week_strip_date_selected(self, iso_date: str) -> None: + self._date_preset = "custom" + for button in self.date_buttons.values(): + button.setChecked(False) + self._start_date = iso_date + self._end_date = iso_date + self._page = 1 + self.refresh() + def _diagnosis_dialog(self) -> DiagnosisDialog: dialog = getattr(self, "_diagnosis_dialog_impl", None) if dialog is None: @@ -542,11 +589,11 @@ class AppointmentsPage(QWidget): frame = QFrame() frame.setObjectName("AppointmentFilterPanel") layout = QVBoxLayout(frame) - layout.setContentsMargins(16, 16, 16, 14) - layout.setSpacing(18) + layout.setContentsMargins(16, 16, 16, 14) + layout.setSpacing(18) date_row = QHBoxLayout() - date_row.setSpacing(16) + date_row.setSpacing(16) self.date_buttons: dict[str, QPushButton] = {} self._date_stat_labels: dict[str, str] = {} for source_label, preset in DATE_PRESETS: @@ -573,11 +620,11 @@ class AppointmentsPage(QWidget): date_menu.addSeparator() date_menu.addAction("自定义日期").triggered.connect(self._open_custom_date) self.date_overflow_button.setMenu(date_menu) - date_row.addWidget(self.date_overflow_button) - - date_divider = QLabel("│") - date_divider.setObjectName("FilterDivider") - date_row.addWidget(date_divider) + date_row.addWidget(self.date_overflow_button) + + date_divider = QLabel("│") + date_divider.setObjectName("FilterDivider") + date_row.addWidget(date_divider) self.pending_stat_button = QPushButton("待预约 0") self.pending_stat_button.setProperty("appointmentStat", True) @@ -595,31 +642,31 @@ class AppointmentsPage(QWidget): self.unassigned_stat_button.setProperty("appointmentStatKind", "warning") self.unassigned_stat_button.setMinimumWidth(0) self.unassigned_stat_button.clicked.connect(self._toggle_unassigned_filter) - date_row.addWidget(self.unassigned_stat_button) - date_row.addSpacing(52) + date_row.addWidget(self.unassigned_stat_button) + date_row.addSpacing(52) - search_row = QHBoxLayout() - search_row.setSpacing(8) - search_row.addStretch(1) - self.patient_input = QLineEdit(frame) + search_row = QHBoxLayout() + search_row.setSpacing(8) + search_row.addStretch(1) + self.patient_input = QLineEdit(frame) self.patient_input.setObjectName("AppointmentPatientSearch") self.patient_input.setPlaceholderText("患者姓名 / 手机号") - self.patient_input.setClearButtonEnabled(True) - self.patient_input.addAction(icon("search", "#5D6B80", 16), QLineEdit.ActionPosition.LeadingPosition) + self.patient_input.setClearButtonEnabled(True) + self.patient_input.addAction(icon("search", "#5D6B80", 16), QLineEdit.ActionPosition.LeadingPosition) self.patient_input.returnPressed.connect(self._search) - self.patient_input.setFixedWidth(270) - search_row.addWidget(self.patient_input) + self.patient_input.setFixedWidth(270) + search_row.addWidget(self.patient_input) search = QPushButton("查询") search.setObjectName("AppointmentSearchButton") search.setProperty("variant", "primary") search.clicked.connect(self._search) - search_row.addWidget(search) - layout.addLayout(search_row) - layout.addLayout(date_row) + search_row.addWidget(search) + layout.addLayout(search_row) + layout.addLayout(date_row) filter_row = QHBoxLayout() - filter_row.setSpacing(8) + filter_row.setSpacing(8) self.status_filter_label = QLabel("挂号状态:") self.status_filter_label.setObjectName("FilterRowLabel") filter_row.addWidget(self.status_filter_label) @@ -663,26 +710,26 @@ class AppointmentsPage(QWidget): filter_row.addWidget(button) self.confirmed_buttons[""].setChecked(True) - filter_row.addStretch(1) - self.more_filters_button = QPushButton("更多筛选") + filter_row.addStretch(1) + self.more_filters_button = QPushButton("更多筛选") self.more_filters_button.setCheckable(True) self.more_filters_button.setProperty("filterChoice", True) self.more_filters_button.clicked.connect(self._toggle_advanced_filters) - filter_row.addWidget(self.more_filters_button) - - layout.addLayout(filter_row) - self.advanced_filters = QWidget(frame) - advanced_row = QHBoxLayout(self.advanced_filters) - advanced_row.setContentsMargins(0, 0, 0, 0) - advanced_row.setSpacing(10) - self.advanced_filters.hide() + filter_row.addWidget(self.more_filters_button) + + layout.addLayout(filter_row) + self.advanced_filters = QWidget(frame) + advanced_row = QHBoxLayout(self.advanced_filters) + advanced_row.setContentsMargins(0, 0, 0, 0) + advanced_row.setSpacing(10) + self.advanced_filters.hide() self.dept_filter = QComboBox() self.dept_filter.addItem("全部部门", "") self.dept_filter.setMinimumWidth(150) self.dept_filter.currentIndexChanged.connect(self._search) self.dept_filter.hide() - advanced_row.addWidget(self.dept_filter) + advanced_row.addWidget(self.dept_filter) self.doctor_input = QLineEdit(frame) self.doctor_input.setPlaceholderText("医生") @@ -690,23 +737,23 @@ class AppointmentsPage(QWidget): self.doctor_input.setMaximumWidth(120) self.doctor_input.hide() self.doctor_input.returnPressed.connect(self._search) - advanced_row.addWidget(self.doctor_input) - advanced_row.addStretch(1) + advanced_row.addWidget(self.doctor_input) + advanced_row.addStretch(1) custom = QPushButton("自定义日期") custom.setProperty("variant", "ghost") custom.clicked.connect(self._open_custom_date) custom.hide() self.custom_date_button = custom - advanced_row.addWidget(custom) + advanced_row.addWidget(custom) reset = QPushButton("重置") reset.setProperty("variant", "ghost") reset.clicked.connect(self._reset_filters) reset.hide() self.reset_filter_button = reset - advanced_row.addWidget(reset) - layout.addWidget(self.advanced_filters) + advanced_row.addWidget(reset) + layout.addWidget(self.advanced_filters) return frame def _build_content(self) -> QWidget: @@ -728,8 +775,8 @@ class AppointmentsPage(QWidget): card.setObjectName("AppointmentMainCard") card.setMinimumHeight(0) layout = QVBoxLayout(card) - layout.setContentsMargins(0, 0, 0, 0) - layout.setSpacing(0) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(0) compatibility_host = QWidget(card) compatibility_host.hide() @@ -773,14 +820,14 @@ class AppointmentsPage(QWidget): if isinstance(widget, QPushButton): widget.setProperty("compactAction", True) - self.toolbar = QFrame(card) - self.toolbar.setObjectName("AppointmentToolbar") - self.toolbar.setFixedHeight(58) - actions = QHBoxLayout(self.toolbar) - actions.setContentsMargins(10, 4, 18, 14) - actions.setSpacing(16) + self.toolbar = QFrame(card) + self.toolbar.setObjectName("AppointmentToolbar") + self.toolbar.setFixedHeight(58) + actions = QHBoxLayout(self.toolbar) + actions.setContentsMargins(10, 4, 18, 14) + actions.setSpacing(16) self.toolbar_edit_button = QPushButton("编辑患者", card) - self.toolbar_edit_button.setProperty("variant", "secondary") + self.toolbar_edit_button.setProperty("variant", "secondary") self.toolbar_edit_button.setProperty("compactAction", True) self.toolbar_edit_button.setVisible( _canonical_allowed(self.permissions, "tcm.diagnosis/edit", default=False) @@ -823,33 +870,33 @@ class AppointmentsPage(QWidget): actions.addWidget(self.inspector_toggle_button) refresh = QPushButton("刷新", card) refresh.setProperty("variant", "ghost") - refresh.setProperty("compactAction", True) - refresh.setIcon(icon("refresh", "#5D6B80", 16)) + refresh.setProperty("compactAction", True) + refresh.setIcon(icon("refresh", "#5D6B80", 16)) refresh.clicked.connect(lambda: self.refresh()) actions.addWidget(refresh) - layout.addWidget(self.toolbar) + layout.addWidget(self.toolbar) self.table = SortableTable( [ - TableColumn("_selected", "", 48, alignment=Qt.AlignmentFlag.AlignCenter), - TableColumn("id", "ID", 56, alignment=Qt.AlignmentFlag.AlignCenter), + TableColumn("_selected", "", 48, alignment=Qt.AlignmentFlag.AlignCenter), + TableColumn("id", "ID", 56, alignment=Qt.AlignmentFlag.AlignCenter), TableColumn( "patient_name", "患者", - 114, - alignment=Qt.AlignmentFlag.AlignCenter, + 114, + alignment=Qt.AlignmentFlag.AlignCenter, ), - TableColumn("gender", "性别 / 年龄", 122, formatter=_gender_age_cell, alignment=Qt.AlignmentFlag.AlignCenter), - TableColumn("appointment_date", "挂号信息", 296, formatter=_appointment_info_cell), - TableColumn("diagnosis_confirmed", "确认", 100, formatter=_confirmed_cell, alignment=Qt.AlignmentFlag.AlignCenter), - TableColumn("revisit_time", "复诊", 80, formatter=_revisit_cell, alignment=Qt.AlignmentFlag.AlignCenter), - TableColumn("assistant_name", "助理", 109, alignment=Qt.AlignmentFlag.AlignCenter), - TableColumn("has_prescription", "开方", 107, formatter=_prescription_cell, alignment=Qt.AlignmentFlag.AlignCenter), - TableColumn("unserved_days", "未服务天数", 108, formatter=_unserved_cell, alignment=Qt.AlignmentFlag.AlignCenter), + TableColumn("gender", "性别 / 年龄", 122, formatter=_gender_age_cell, alignment=Qt.AlignmentFlag.AlignCenter), + TableColumn("appointment_date", "挂号信息", 296, formatter=_appointment_info_cell), + TableColumn("diagnosis_confirmed", "确认", 100, formatter=_confirmed_cell, alignment=Qt.AlignmentFlag.AlignCenter), + TableColumn("revisit_time", "复诊", 80, formatter=_revisit_cell, alignment=Qt.AlignmentFlag.AlignCenter), + TableColumn("assistant_name", "助理", 109, alignment=Qt.AlignmentFlag.AlignCenter), + TableColumn("has_prescription", "开方", 107, formatter=_prescription_cell, alignment=Qt.AlignmentFlag.AlignCenter), + TableColumn("unserved_days", "未服务天数", 108, formatter=_unserved_cell, alignment=Qt.AlignmentFlag.AlignCenter), TableColumn( "_im_consult", "IM 问诊", - 129, + 129, alignment=Qt.AlignmentFlag.AlignCenter, ), ] @@ -860,55 +907,55 @@ class AppointmentsPage(QWidget): self.table.setItemDelegateForColumn(4, _AppointmentInfoDelegate(self.table)) self.table.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) header = self.table.horizontalHeader() - header.setFixedHeight(41) + header.setFixedHeight(41) header.setMinimumSectionSize(28) - header.setDefaultAlignment(Qt.AlignmentFlag.AlignCenter) + header.setDefaultAlignment(Qt.AlignmentFlag.AlignCenter) header.setStretchLastSection(False) header.setSectionResizeMode(4, QHeaderView.ResizeMode.Stretch) header.setSectionResizeMode(10, QHeaderView.ResizeMode.Fixed) - self.table.verticalHeader().setDefaultSectionSize(88) + self.table.verticalHeader().setDefaultSectionSize(88) self.table.itemSelectionChanged.connect(self._selection_changed) self.table.itemDoubleClicked.connect(lambda _item: self._open_detail()) layout.addWidget(self.table, 1) - self.pager = InfiniteList(self._page_size) - self.pager.bind(self.table) + self.pager = InfiniteList(self._page_size) + self.pager.bind(self.table) layout.addWidget(self.pager) return card def _apply_responsive_layout(self) -> None: - """Keep the approved spacing, with denser controls on smaller desktops.""" + """Keep the approved spacing, with denser controls on smaller desktops.""" narrow = self.width() < 1120 for preset in ("yesterday", "day_before", "tomorrow", "day_after"): self.date_buttons[preset].setVisible(not narrow) self.date_overflow_button.setVisible(narrow) self.status_filter_label.setVisible(not narrow) - self.confirm_filter_label.setVisible(not narrow) - compact = self.height() < 800 - self.layout().setContentsMargins(30 if not narrow else 16, 18 if not compact else 12, - 27 if not narrow else 16, 8) - self.patient_input.setFixedWidth(270 if self.width() >= 1180 else 200) - self.filter_panel.layout().setContentsMargins(16, 16 if not compact else 8, 16, 14 if not compact else 8) - self.filter_panel.layout().setSpacing(18 if not compact else 8) - self.toolbar.setFixedHeight(58 if not compact else 48) - self.toolbar.layout().setContentsMargins(10, 4, 18, 14 if not compact else 6) - self._compact_rows = compact - self._fit_table_columns() - self._fit_table_rows() - self._responsive_narrow = narrow - - def _fit_table_columns(self) -> None: - # Preserve all 11 columns; below the readable minimum the table scrolls. - widths = (48, 56, 114, 122, 296, 100, 80, 109, 107, 108, 129) - scale = min(1.0, max(0.85, (self.width() - 58) / sum(widths))) - for column, width in enumerate(widths): - if column != 4: - self.table.setColumnWidth(column, round(width * scale)) - self.table.horizontalHeader().setSectionResizeMode( - 4, QHeaderView.ResizeMode.Interactive if self.width() < 1080 else QHeaderView.ResizeMode.Stretch - ) - if self.width() < 1080: - self.table.setColumnWidth(4, 270) + self.confirm_filter_label.setVisible(not narrow) + compact = self.height() < 800 + self.layout().setContentsMargins(30 if not narrow else 16, 18 if not compact else 12, + 27 if not narrow else 16, 8) + self.patient_input.setFixedWidth(270 if self.width() >= 1180 else 200) + self.filter_panel.layout().setContentsMargins(16, 16 if not compact else 8, 16, 14 if not compact else 8) + self.filter_panel.layout().setSpacing(18 if not compact else 8) + self.toolbar.setFixedHeight(58 if not compact else 48) + self.toolbar.layout().setContentsMargins(10, 4, 18, 14 if not compact else 6) + self._compact_rows = compact + self._fit_table_columns() + self._fit_table_rows() + self._responsive_narrow = narrow + + def _fit_table_columns(self) -> None: + # Preserve all 11 columns; below the readable minimum the table scrolls. + widths = (48, 56, 114, 122, 296, 100, 80, 109, 107, 108, 129) + scale = min(1.0, max(0.85, (self.width() - 58) / sum(widths))) + for column, width in enumerate(widths): + if column != 4: + self.table.setColumnWidth(column, round(width * scale)) + self.table.horizontalHeader().setSectionResizeMode( + 4, QHeaderView.ResizeMode.Interactive if self.width() < 1080 else QHeaderView.ResizeMode.Stretch + ) + if self.width() < 1080: + self.table.setColumnWidth(4, 270) def resizeEvent(self, event: Any) -> None: super().resizeEvent(event) @@ -969,8 +1016,8 @@ class AppointmentsPage(QWidget): button.setChecked(key == value) self._search() - def _toggle_advanced_filters(self, checked: bool) -> None: - self.advanced_filters.setVisible(checked) + def _toggle_advanced_filters(self, checked: bool) -> None: + self.advanced_filters.setVisible(checked) self.dept_filter.setVisible(checked) self.doctor_input.setVisible(checked and self._is_admin) self.custom_date_button.setVisible(checked) @@ -1101,36 +1148,36 @@ class AppointmentsPage(QWidget): filters["assistant_unassigned"] = 1 return filters - def refresh(self, *, silent: bool = False) -> None: - self._generation += 1 + def refresh(self, *, silent: bool = False) -> None: + self._generation += 1 generation = self._generation self._loading = True # 列表加载不再挂横幅。横幅占布局空间,弹出与收起各触发一次重排, # 每刷新一次表格就上下跳一次——而轮询定时器每 5 秒就刷新一次。 # 已有数据时保持旧行可见、静默替换;失败仍然照常报错。 - filters = MappingProxyType(self._query_filters()) - page_size = self._page_size - self.pager.reload( - lambda page: invoke( + filters = MappingProxyType(self._query_filters()) + page_size = self._page_size + self.pager.reload( + lambda page: invoke( self.repository, "list_appointments", page_no=page, page_size=page_size, **filters, ), - apply=lambda result: self._loaded(result, generation, silent), - on_error=lambda error: self._load_error(error, generation, silent), - runner=run_async, - query_key=filters, - on_finished=lambda: self._load_finished(generation), - ) + apply=lambda result: self._loaded(result, generation, silent), + on_error=lambda error: self._load_error(error, generation, silent), + runner=run_async, + query_key=filters, + on_finished=lambda: self._load_finished(generation), + ) def _loaded(self, result: Any, generation: int, silent: bool) -> None: if generation != self._generation: return - rows = page_items(result) - total = page_total(result) - self._page = self.pager.page + rows = page_items(result) + total = page_total(result) + self._page = self.pager.page extend = get_value(result, "extend", {}) or {} signature = ( self._page, @@ -1196,6 +1243,12 @@ class AppointmentsPage(QWidget): key = str(first_value(row, "appointment_date", default="") or "") if key: visible_dates[key] = visible_dates.get(key, 0) + 1 + if hasattr(self, "week_strip"): + merged_counts = dict(visible_dates) + for k, v in date_counts.items(): + if len(str(k)) == 10: + merged_counts[str(k)] = _as_int(v) + self.week_strip.set_day_counts(merged_counts) for preset, button in self.date_buttons.items(): label = self._date_stat_labels[preset] if preset == "": @@ -1232,30 +1285,30 @@ class AppointmentsPage(QWidget): style.unpolish(self.unassigned_stat_button) style.polish(self.unassigned_stat_button) - def _install_table_selectors(self) -> None: - for row_index in range(self.table.rowCount()): - host = QWidget(self.table) - host.setProperty("appointmentSelectionHost", True) - host.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + def _install_table_selectors(self) -> None: + for row_index in range(self.table.rowCount()): + host = QWidget(self.table) + host.setProperty("appointmentSelectionHost", True) + host.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) layout = QHBoxLayout(host) layout.setContentsMargins(0, 0, 0, 0) layout.setAlignment(Qt.AlignmentFlag.AlignCenter) selector = QCheckBox(host) selector.setProperty("appointmentSelector", True) selector.setToolTip("选择患者") - selector.clicked.connect(lambda _checked=False, cell=host: self._select_patient(cell)) + selector.clicked.connect(lambda _checked=False, cell=host: self._select_patient(cell)) layout.addWidget(selector) self.table.setCellWidget(row_index, 0, host) item = self.table.item(row_index, 0) if item is not None: - item.setText("") - - def _select_patient(self, cell: QWidget) -> None: - # Sorting moves cell widgets: resolve the visible row at click time. - row_index = self.table.indexAt(cell.pos()).row() - if row_index >= 0: - self.table.selectRow(row_index) - self._selection_changed() + item.setText("") + + def _select_patient(self, cell: QWidget) -> None: + # Sorting moves cell widgets: resolve the visible row at click time. + row_index = self.table.indexAt(cell.pos()).row() + if row_index >= 0: + self.table.selectRow(row_index) + self._selection_changed() def _install_appointment_info_cells(self) -> None: for row_index in range(self.table.rowCount()): @@ -1265,8 +1318,8 @@ class AppointmentsPage(QWidget): host.setProperty("appointmentInfoHost", True) host.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) layout = QVBoxLayout(host) - layout.setContentsMargins(15, 8, 15, 8) - layout.setSpacing(4) + layout.setContentsMargins(15, 8, 15, 8) + layout.setSpacing(4) heading = QHBoxLayout() heading.setContentsMargins(0, 0, 0, 0) heading.setSpacing(5) @@ -1275,12 +1328,12 @@ class AppointmentsPage(QWidget): status.setProperty("tableAppointmentStatus", True) status.setProperty( "tableAppointmentStatusKind", - {1: "warning", 4: "warning", 2: "muted"}.get(_status_value(row), "primary"), + {1: "warning", 4: "warning", 2: "muted"}.get(_status_value(row), "primary"), ) heading.addWidget(status) - doctor = QLabel(display_text(first_value(row, "doctor_name"), "未分配"), host) - doctor.setToolTip(doctor.text()) - doctor.setMinimumWidth(0) + doctor = QLabel(display_text(first_value(row, "doctor_name"), "未分配"), host) + doctor.setToolTip(doctor.text()) + doctor.setMinimumWidth(0) heading.addWidget(doctor) heading.addStretch(1) if _status_value(row) == 1 and _canonical_allowed( @@ -1301,31 +1354,31 @@ class AppointmentsPage(QWidget): host, ) date_label.setProperty("tableAppointmentMeta", True) - date_row = QHBoxLayout() - date_row.setContentsMargins(0, 0, 0, 0) - date_row.setSpacing(6) - date_row.addWidget(date_label) - mode_label = QLabel(appointment_type_description(appointment_type_value(row)), host) - mode_label.setObjectName("AppointmentModeLabel") - mode_label.setProperty("tableAppointmentMeta", True) - date_row.addWidget(mode_label) - date_row.addStretch(1) - layout.addLayout(date_row) + date_row = QHBoxLayout() + date_row.setContentsMargins(0, 0, 0, 0) + date_row.setSpacing(6) + date_row.addWidget(date_label) + mode_label = QLabel(appointment_type_description(appointment_type_value(row)), host) + mode_label.setObjectName("AppointmentModeLabel") + mode_label.setProperty("tableAppointmentMeta", True) + date_row.addWidget(mode_label) + date_row.addStretch(1) + layout.addLayout(date_row) channel = display_text( first_value(row, "channel_name", "channel_source_name", "source_name"), "—", ) channel_label = QLabel(f"最近渠道:{channel}", host) - channel_label.setProperty("tableAppointmentMeta", True) - channel_label.setToolTip(channel_label.text()) - channel_label.setMinimumWidth(0) + channel_label.setProperty("tableAppointmentMeta", True) + channel_label.setToolTip(channel_label.text()) + channel_label.setMinimumWidth(0) layout.addWidget(channel_label) self.table.setCellWidget(row_index, 4, host) patient = self.table.item(row_index, 2) if patient is not None: - font = QFont(heading_family()) - font.setPixelSize(14) - font.setWeight(QFont.Weight.Medium) + font = QFont(heading_family()) + font.setPixelSize(14) + font.setWeight(QFont.Weight.Medium) patient.setFont(font) def _install_im_consult_actions(self) -> None: @@ -1347,8 +1400,8 @@ class AppointmentsPage(QWidget): layout.setContentsMargins(5, 0, 5, 0) layout.setAlignment(Qt.AlignmentFlag.AlignCenter) - is_text = appointment_type_value(row) == "text" - button = QPushButton("图文沟通" if is_text else "IM 问诊", host) + is_text = appointment_type_value(row) == "text" + button = QPushButton("图文沟通" if is_text else "IM 问诊", host) button.setObjectName("AppointmentImConsultButton") button.setProperty("appointmentImAction", True) patient_name = display_text(first_value(row, "patient_name"), "患者") @@ -1376,8 +1429,8 @@ class AppointmentsPage(QWidget): elif status_error: tooltip = status_error else: - tooltip = ("打开图文问诊,可发送文字、图片和文件;不支持音视频通话" - if is_text else "打开患者 IM,可发送消息;通话能力由本次挂号决定") + tooltip = ("打开图文问诊,可发送文字、图片和文件;不支持音视频通话" + if is_text else "打开患者 IM,可发送消息;通话能力由本次挂号决定") button.setToolTip(tooltip) button.clicked.connect( lambda _checked=False, source=row: self._run_video_row_action( @@ -1411,11 +1464,11 @@ class AppointmentsPage(QWidget): if (widget := self.table.cellWidget(row_index, column)) is not None), default=0, ) - # Cell padding is owned by the layouts, so long/multiline records - # can grow without shrinking the approved body font. - self.table.setRowHeight( - row_index, max(80 if getattr(self, "_compact_rows", False) else 88, - height, widget_height + 1) + # Cell padding is owned by the layouts, so long/multiline records + # can grow without shrinking the approved body font. + self.table.setRowHeight( + row_index, max(80 if getattr(self, "_compact_rows", False) else 88, + height, widget_height + 1) ) def _load_error(self, error: Exception, generation: int, silent: bool) -> None: @@ -1425,13 +1478,13 @@ class AppointmentsPage(QWidget): return self.banner.show_message(friendly_error(error), "danger") - def _load_finished(self, generation: int) -> None: - if generation == self._generation: - self._loading = False - - def _poll_refresh(self) -> None: - if self.isVisible() and not self.pager.loading: - self.refresh(silent=True) + def _load_finished(self, generation: int) -> None: + if generation == self._generation: + self._loading = False + + def _poll_refresh(self) -> None: + if self.isVisible() and not self.pager.loading: + self.refresh(silent=True) def _update_tab_badges(self) -> None: for label, value in STATUS_TABS: @@ -1445,81 +1498,81 @@ class AppointmentsPage(QWidget): text = f"{label} ({count})" if count else label self.tab_bar.setTabText(index, text) - def _on_inspector_closed(self) -> None: - if hasattr(self, "inspector_toggle_button"): - self.inspector_toggle_button.setChecked(False) - - def _toggle_clinical_inspector(self, checked: bool) -> None: - if not hasattr(self, "inspector_panel"): - return - if not checked: - self.inspector_panel.hide() - return - self._sync_clinical_inspector(force_open=True) - - def _sync_clinical_inspector(self, *, force_open: bool = False) -> None: - if not hasattr(self, "inspector_panel"): - return - if not force_open and not self.inspector_panel.isVisible(): - return - row = self.table.current_data() if hasattr(self, "table") else None - if row is None: - if force_open: - self.inspector_panel.set_summary( - title="未选中挂号记录", - subtitle="请在左侧表格中单击任意患者行以实时预览临床摘要", - rows=[("提示", "支持无弹窗快速核查挂号时段、医助与接诊操作")], - actions=[], - ) - return - patient = display_text(first_value(row, "patient_name", "name", default="患者")) - phone = display_text(first_value(row, "phone", "mobile", "patient_phone", default="—")) - doctor = display_text(first_value(row, "doctor_name", default="—")) - assistant = display_text(first_value(row, "assistant_name", default="—")) - appt_time = display_text(first_value(row, "appointment_time", "time_text", default="—")) - appt_date = display_text(first_value(row, "appointment_date", default="")) - mode_desc = appointment_type_description(appointment_type_value(row)) - actions: list[tuple[str, str, Any]] = [] - if self.toolbar_edit_button.isEnabled(): - actions.append(("编辑四诊病历", "primary", self._edit_patient)) - if self.toolbar_ai_consult_button.isEnabled(): - actions.append(("启动 AI 辨证分析", "secondary", self._open_ai_consult)) - if self.toolbar_cancel_button.isEnabled(): - actions.append(("取消当前挂号", "danger", self._cancel_selected)) - self.inspector_panel.set_summary( - title=patient, - subtitle=f"{mode_desc} · 手机 {phone}", - rows=[ - ("预约时间", f"{appt_date} {appt_time}".strip()), - ("接诊医生", doctor), - ("协作医助", assistant), - ("挂号编号", str(first_value(row, "id", default="—"))), - ], - actions=actions, - ) - - def _selection_changed(self) -> None: - for row_index in range(self.table.rowCount()): - host = self.table.cellWidget(row_index, 0) - if host is None: - continue - selected = self.table.selectionModel().isRowSelected(row_index) - selector = host.findChild(QCheckBox) - if selector is not None: - selector.setChecked(selected) - if host.property("selected") != selected: - host.setProperty("selected", selected) - host.style().unpolish(host) - host.style().polish(host) - host.update() - row = self.table.current_data() + def _on_inspector_closed(self) -> None: + if hasattr(self, "inspector_toggle_button"): + self.inspector_toggle_button.setChecked(False) + + def _toggle_clinical_inspector(self, checked: bool) -> None: + if not hasattr(self, "inspector_panel"): + return + if not checked: + self.inspector_panel.hide() + return + self._sync_clinical_inspector(force_open=True) + + def _sync_clinical_inspector(self, *, force_open: bool = False) -> None: + if not hasattr(self, "inspector_panel"): + return + if not force_open and not self.inspector_panel.isVisible(): + return + row = self.table.current_data() if hasattr(self, "table") else None + if row is None: + if force_open: + self.inspector_panel.set_summary( + title="未选中挂号记录", + subtitle="请在左侧表格中单击任意患者行以实时预览临床摘要", + rows=[("提示", "支持无弹窗快速核查挂号时段、医助与接诊操作")], + actions=[], + ) + return + patient = display_text(first_value(row, "patient_name", "name", default="患者")) + phone = display_text(first_value(row, "phone", "mobile", "patient_phone", default="—")) + doctor = display_text(first_value(row, "doctor_name", default="—")) + assistant = display_text(first_value(row, "assistant_name", default="—")) + appt_time = display_text(first_value(row, "appointment_time", "time_text", default="—")) + appt_date = display_text(first_value(row, "appointment_date", default="")) + mode_desc = appointment_type_description(appointment_type_value(row)) + actions: list[tuple[str, str, Any]] = [] + if self.toolbar_edit_button.isEnabled(): + actions.append(("编辑四诊病历", "primary", self._edit_patient)) + if self.toolbar_ai_consult_button.isEnabled(): + actions.append(("启动 AI 辨证分析", "secondary", self._open_ai_consult)) + if self.toolbar_cancel_button.isEnabled(): + actions.append(("取消当前挂号", "danger", self._cancel_selected)) + self.inspector_panel.set_summary( + title=patient, + subtitle=f"{mode_desc} · 手机 {phone}", + rows=[ + ("预约时间", f"{appt_date} {appt_time}".strip()), + ("接诊医生", doctor), + ("协作医助", assistant), + ("挂号编号", str(first_value(row, "id", default="—"))), + ], + actions=actions, + ) + + def _selection_changed(self) -> None: + for row_index in range(self.table.rowCount()): + host = self.table.cellWidget(row_index, 0) + if host is None: + continue + selected = self.table.selectionModel().isRowSelected(row_index) + selector = host.findChild(QCheckBox) + if selector is not None: + selector.setChecked(selected) + if host.property("selected") != selected: + host.setProperty("selected", selected) + host.style().unpolish(host) + host.style().polish(host) + host.update() + row = self.table.current_data() has_row = row is not None status = _status_value(row) if has_row else 0 not_completed = has_row and status != 3 self.edit_button.setEnabled(has_row and _diagnosis_id(row) > 0) - self.qr_button.setEnabled( - not_completed - and can_appointment_video(appointment_type_value(row)) + self.qr_button.setEnabled( + not_completed + and can_appointment_video(appointment_type_value(row)) and _video_patient_id(row) > 0 and _as_int(first_value(row, "doctor_id", default=0)) > 0 ) @@ -1541,14 +1594,16 @@ class AppointmentsPage(QWidget): ) self.cancel_button.setEnabled(has_row and status == 1) self.toolbar_edit_button.setEnabled(has_row and _diagnosis_id(row) > 0) - self.toolbar_qr_button.setEnabled( - not_completed - and can_appointment_video(appointment_type_value(row)) + self.toolbar_qr_button.setEnabled( + not_completed + and can_appointment_video(appointment_type_value(row)) and _video_patient_id(row) > 0 and _as_int(first_value(row, "doctor_id", default=0)) > 0 ) self.toolbar_cancel_button.setEnabled(has_row and status == 1) self._sync_clinical_inspector() + if self.patient_context_store is not None and row is not None: + self.patient_context_store.update_from_row(row) def _current_row(self) -> Any | None: return self.table.current_data() @@ -1632,8 +1687,8 @@ class AppointmentsPage(QWidget): self.video_requested.emit( { "source": "appointments", - "appointment_id": appointment_id, - "appointment_type": appointment_type_value(row), + "appointment_id": appointment_id, + "appointment_type": appointment_type_value(row), "patient_id": patient_id, "diagnosis_id": diagnosis_id, "patient_name": first_value(row, "patient_name", default="患者"), @@ -1655,12 +1710,12 @@ class AppointmentsPage(QWidget): if not all(callable(getattr(self.repository, name, None)) for name in required_methods): show_toast(self, "当前仓库未提供视频二维码能力。", "warning") return - row = self._current_row() - if row is None or _status_value(row) == 3: - return - if not can_appointment_video(appointment_type_value(row)): - show_toast(self, "本次挂号不支持视频问诊二维码。", "warning") - return + row = self._current_row() + if row is None or _status_value(row) == 3: + return + if not can_appointment_video(appointment_type_value(row)): + show_toast(self, "本次挂号不支持视频问诊二维码。", "warning") + return diagnosis_id = _diagnosis_id(row) patient_id = _video_patient_id(row) doctor_id = _as_int(first_value(row, "doctor_id", default=0)) @@ -1934,7 +1989,7 @@ class AppointmentsPage(QWidget): if _diagnosis_id(row) <= 0 or _appointment_id(row) <= 0: show_toast(self, "该预约缺少诊单信息,请先编辑患者。", "warning") return - mode = {"查看": "view", "重新开方": "reissue"}.get(prescription_action_label(row), "open") + mode = {"查看": "view", "重新开方": "reissue"}.get(prescription_action_label(row), "open") self._begin_prescription_load(row, mode=mode) def _view_case(self) -> None: @@ -2019,20 +2074,20 @@ class AppointmentsPage(QWidget): expected_id = _as_int( first_value(row, "current_prescription_id", default=0) ) - if not prescription_matches_appointment( - existing, appointment_id=_appointment_id(row), diagnosis_id=_diagnosis_id(row), previous_id=expected_id, - ): - self.banner.show_message("返回的处方与当前挂号不一致,已停止操作。", "warning") - return - if mode == "view" and (not approved or voided): + if not prescription_matches_appointment( + existing, appointment_id=_appointment_id(row), diagnosis_id=_diagnosis_id(row), previous_id=expected_id, + ): + self.banner.show_message("返回的处方与当前挂号不一致,已停止操作。", "warning") + return + if mode == "view" and (not approved or voided): self.banner.show_message( "当前挂号的处方状态已变化,请刷新列表后重试。", "warning", ) return - if voided and can_reissue_prescription(existing, self.current_user, self.permissions): - self._open_new_prescription(reissue_prescription_seed(existing)) - elif not approved and not prescription_edit_is_locked(existing): + if voided and can_reissue_prescription(existing, self.current_user, self.permissions): + self._open_new_prescription(reissue_prescription_seed(existing)) + elif not approved and not prescription_edit_is_locked(existing): self._open_existing_prescription_editor(existing) else: dialog = PrescriptionDetailDialog( @@ -2040,16 +2095,16 @@ class AppointmentsPage(QWidget): can_open_diagnosis=_canonical_allowed( self.permissions, "tcm.diagnosis/readonlyDetail", default=False ), - allow_void=True, + allow_void=True, parent=self, ) dialog.diagnosis_requested.connect(self._open_diagnosis_id) - if dialog.exec() == PRESCRIPTION_VOIDED_RESULT: - self._after_prescription_void() - if expected_id > 0 and actual_id != expected_id and not self._mutation_pending: - self.refresh(silent=True) + if dialog.exec() == PRESCRIPTION_VOIDED_RESULT: + self._after_prescription_void() + if expected_id > 0 and actual_id != expected_id and not self._mutation_pending: + self.refresh(silent=True) return - if mode in {"view", "reissue"}: + if mode in {"view", "reissue"}: self.banner.show_message( "当前挂号没有可查看的处方,请刷新列表后重试。", "warning", @@ -2062,55 +2117,55 @@ class AppointmentsPage(QWidget): if prescription_id <= 0: self.banner.show_message("处方编号不完整,无法编辑。", "danger") return - def save_changes(payload: Any) -> Any: - return invoke(self.repository, "update_prescription", prescription=prescription_id, changes=payload) - + def save_changes(payload: Any) -> Any: + return invoke(self.repository, "update_prescription", prescription=prescription_id, changes=payload) + dialog = PrescriptionEditorDialog( self.repository, prescription, mode="edit", current_user=self.current_user, - save_draft=save_changes, - allow_void=True, + save_draft=save_changes, + allow_void=True, parent=self, ) diagnosis_signal = getattr(dialog, "diagnosis_requested", None) if diagnosis_signal is not None: diagnosis_signal.connect(self._open_diagnosis_id) - result = dialog.exec() - if result == PRESCRIPTION_VOIDED_RESULT: - self._after_prescription_void() + result = dialog.exec() + if result == PRESCRIPTION_VOIDED_RESULT: + self._after_prescription_void() + return + if result != QDialog.DialogCode.Accepted: + return + self._action_generation += 1 + generation = self._action_generation + saved_draft = getattr(dialog, "saved_draft", None) + if saved_draft is not None: + self._prescription_updated(generation, saved_draft) return - if result != QDialog.DialogCode.Accepted: - return - self._action_generation += 1 - generation = self._action_generation - saved_draft = getattr(dialog, "saved_draft", None) - if saved_draft is not None: - self._prescription_updated(generation, saved_draft) - return frozen_payload = MappingProxyType(dialog.payload()) self._mutation_pending = True self.banner.show_message("正在保存处方…", "info") run_async( - lambda: save_changes(frozen_payload), - on_success=lambda result: self._prescription_updated(generation, result), + lambda: save_changes(frozen_payload), + on_success=lambda result: self._prescription_updated(generation, result), on_error=lambda error: self._action_error(error, generation), on_finished=lambda: self._mutation_finished(generation), ) - def _prescription_updated(self, generation: int, prescription: Any = None) -> None: + def _prescription_updated(self, generation: int, prescription: Any = None) -> None: if generation != self._action_generation: return - message, kind = saved_prescription_message(prescription, "处方已保存并重新进入待审核。") - self.banner.show_message(message, kind) - resume_saved_prescription(self.repository, prescription, self) + message, kind = saved_prescription_message(prescription, "处方已保存并重新进入待审核。") + self.banner.show_message(message, kind) + resume_saved_prescription(self.repository, prescription, self) + self.refresh(silent=True) + + def _after_prescription_void(self) -> None: + show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success") self.refresh(silent=True) - def _after_prescription_void(self) -> None: - show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success") - self.refresh(silent=True) - def _begin_case_record_load(self, row: Any) -> None: snapshot = deepcopy(row) diagnosis_id = _diagnosis_id(snapshot) @@ -2187,23 +2242,23 @@ class AppointmentsPage(QWidget): self._diagnosis_dialog().open_view_only(diagnosis_id) def _open_prescription_editor(self, record: Any, case_record: Any) -> None: - self._open_new_prescription(self._prescription_seed(record, case_record)) - - def _open_new_prescription(self, seed: dict[str, Any]) -> None: - def save_new(payload: dict[str, Any]) -> Any: - authoritative = { - "diagnosis_id": seed["diagnosis_id"], - "appointment_id": seed["appointment_id"], - "case_record": deepcopy(seed.get("case_record", {})), - } - return invoke(self.repository, "create_prescription", prescription=MappingProxyType(payload | authoritative)) - + self._open_new_prescription(self._prescription_seed(record, case_record)) + + def _open_new_prescription(self, seed: dict[str, Any]) -> None: + def save_new(payload: dict[str, Any]) -> Any: + authoritative = { + "diagnosis_id": seed["diagnosis_id"], + "appointment_id": seed["appointment_id"], + "case_record": deepcopy(seed.get("case_record", {})), + } + return invoke(self.repository, "create_prescription", prescription=MappingProxyType(payload | authoritative)) + dialog = PrescriptionEditorDialog( self.repository, seed, mode="add", current_user=self.current_user, - save_draft=save_new, + save_draft=save_new, parent=self, ) diagnosis_signal = getattr(dialog, "diagnosis_requested", None) @@ -2213,26 +2268,26 @@ class AppointmentsPage(QWidget): return self._action_generation += 1 generation = self._action_generation - saved_draft = getattr(dialog, "saved_draft", None) - if saved_draft is not None: - self._prescription_created(generation, saved_draft) - return - payload = dialog.payload() - self._mutation_pending = True + saved_draft = getattr(dialog, "saved_draft", None) + if saved_draft is not None: + self._prescription_created(generation, saved_draft) + return + payload = dialog.payload() + self._mutation_pending = True self.banner.show_message("正在提交处方…", "info") run_async( - lambda: save_new(payload), - on_success=lambda result: self._prescription_created(generation, result), + lambda: save_new(payload), + on_success=lambda result: self._prescription_created(generation, result), on_error=lambda error: self._action_error(error, generation), on_finished=lambda: self._mutation_finished(generation), ) - def _prescription_created(self, generation: int, prescription: Any = None) -> None: + def _prescription_created(self, generation: int, prescription: Any = None) -> None: if generation != self._action_generation: return - message, kind = saved_prescription_message(prescription, "处方已开具并提交审核。") - self.banner.show_message(message, kind) - resume_saved_prescription(self.repository, prescription, self) + message, kind = saved_prescription_message(prescription, "处方已开具并提交审核。") + self.banner.show_message(message, kind) + resume_saved_prescription(self.repository, prescription, self) self.refresh(silent=True) def _prescription_error(self, error: Exception, generation: int) -> None: @@ -2339,7 +2394,7 @@ class AppointmentsPage(QWidget): ("时段", period_text), ( "预约类型", - appointment_type_description(appointment_type_value(detail)), + appointment_type_description(appointment_type_value(detail)), ), ], ), diff --git a/app/src/doctor_workstation/ui/pages/consultations.py b/app/src/doctor_workstation/ui/pages/consultations.py index b9930fac0..37b4c3f02 100755 --- a/app/src/doctor_workstation/ui/pages/consultations.py +++ b/app/src/doctor_workstation/ui/pages/consultations.py @@ -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() diff --git a/app/src/doctor_workstation/ui/pages/patients.py b/app/src/doctor_workstation/ui/pages/patients.py index 35a68e2f1..72fe73f07 100755 --- a/app/src/doctor_workstation/ui/pages/patients.py +++ b/app/src/doctor_workstation/ui/pages/patients.py @@ -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) diff --git a/app/src/doctor_workstation/ui/pages/prescription_library.py b/app/src/doctor_workstation/ui/pages/prescription_library.py index 3a6480cdb..7a7d2ce01 100755 --- a/app/src/doctor_workstation/ui/pages/prescription_library.py +++ b/app/src/doctor_workstation/ui/pages/prescription_library.py @@ -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 diff --git a/app/src/doctor_workstation/ui/pages/prescriptions.py b/app/src/doctor_workstation/ui/pages/prescriptions.py index bc53917ce..4ed0929ef 100755 --- a/app/src/doctor_workstation/ui/pages/prescriptions.py +++ b/app/src/doctor_workstation/ui/pages/prescriptions.py @@ -8,31 +8,31 @@ from html import escape from math import ceil from typing import Any -from PySide6.QtCore import ( - QDateTime, - QEvent, - QModelIndex, - QPersistentModelIndex, - QPointF, - QRectF, - QSize, - Qt, - QTimer, -) +from PySide6.QtCore import ( + QDateTime, + QEvent, + QModelIndex, + QPersistentModelIndex, + QPointF, + QRectF, + QSize, + Qt, + QTimer, +) from PySide6.QtGui import ( QColor, QFont, QFontMetrics, QIcon, - QKeySequence, - QMouseEvent, + QKeySequence, + QMouseEvent, QPainter, QPen, QTextDocument, QTextOption, ) -from PySide6.QtWidgets import ( - QAbstractItemView, +from PySide6.QtWidgets import ( + QAbstractItemView, QApplication, QComboBox, QDateTimeEdit, @@ -45,8 +45,8 @@ from PySide6.QtWidgets import ( QLabel, QLineEdit, QListWidget, - QListWidgetItem, - QMenu, + QListWidgetItem, + QMenu, QMessageBox, QPushButton, QScrollArea, @@ -56,27 +56,27 @@ from PySide6.QtWidgets import ( QStyledItemDelegate, QStyleOptionButton, QStyleOptionViewItem, - QTextEdit, + QTextEdit, QToolTip, QVBoxLayout, QWidget, ) -from ...core.esign import esign_status -from .. import icons, motion -from ..design_system import PALETTE, clinical_stylesheet -from ..dialogs.issued_prescription_ai import ( - PrescriptionAiStatisticsDialog, - agreement_safe_batch, - agreement_text, - batch_running, - can_open_issued_ai, - present_issued_prescription_ai, - state_text, - status_tooltip, -) +from ...core.esign import esign_status +from .. import icons, motion +from ..design_system import PALETTE, clinical_stylesheet +from ..dialogs.issued_prescription_ai import ( + PrescriptionAiStatisticsDialog, + agreement_safe_batch, + agreement_text, + batch_running, + can_open_issued_ai, + present_issued_prescription_ai, + state_text, + status_tooltip, +) from ..dialogs.prescription import ( - PRESCRIBE_PERMISSIONS, + PRESCRIBE_PERMISSIONS, AuditPrescriptionDialog, DiagnosisDetailDialog, PatchPatientDialog, @@ -84,28 +84,30 @@ from ..dialogs.prescription import ( PrescriptionEditorDialog, PrescriptionOrderDialog, PrescriptionOrderListDialog, - can_reissue_prescription, - can_void_issued_prescription, - confirm_prescription_void, - prescription_edit_is_locked, - reissue_prescription_seed, + can_reissue_prescription, + can_void_issued_prescription, + confirm_prescription_void, + prescription_edit_is_locked, + reissue_prescription_seed, ) -from ..dialogs.prescription_esign import ( - PrescriptionEsignDialog, +from ..dialogs.prescription_esign import ( + PrescriptionEsignDialog, awaiting_prescription_upload, - can_continue_prescription_esign, + can_continue_prescription_esign, can_review_uploaded_prescription, can_upload_prescription, - resume_saved_prescription, + resume_saved_prescription, review_signature_time, review_submission_time, - saved_prescription_message, - signature_state, -) + saved_prescription_message, + signature_state, +) from ..filter_disclosure import FilterDisclosure from ..infinite_list import InfiniteList from ..prescriptions_style import prescriptions_stylesheet from ..reception_style import body_family, heading_family +from ..state import PatientContextStore +from ..visuals.context_bridge_bar import SpatialContextBridgeBar from ..widgets import ( EmptyState, MessageBanner, @@ -262,11 +264,11 @@ _ROLE_AVATAR = Qt.ItemDataRole.UserRole + 11 _ROLE_LEAD_ICON = Qt.ItemDataRole.UserRole + 12 _TAG_PALETTE = { - "accent": (PALETTE["accent"], PALETTE["accent_soft"]), - "success": (PALETTE["success"], PALETTE["success_soft"]), - "warning": (PALETTE["warning"], PALETTE["warning_soft"]), - "danger": (PALETTE["danger"], PALETTE["danger_soft"]), - "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), + "accent": (PALETTE["accent"], PALETTE["accent_soft"]), + "success": (PALETTE["success"], PALETTE["success_soft"]), + "warning": (PALETTE["warning"], PALETTE["warning_soft"]), + "danger": (PALETTE["danger"], PALETTE["danger_soft"]), + "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), } @@ -326,7 +328,7 @@ class _RowDecorationDelegate(QStyledItemDelegate): glyph, QRectF(glyph.rect()), ) - painter.setPen(QColor(PALETTE["heading"])) + painter.setPen(QColor(PALETTE["heading"])) painter.setFont(style_option.font) text_rect = rect.adjusted(28, 0, -8, 0) painter.drawText( @@ -339,17 +341,17 @@ class _RowDecorationDelegate(QStyledItemDelegate): else: initial = str(avatar)[:1] or "医" circle = QRectF(rect.left() + 8, rect.center().y() - 10, 20, 20) - painter.setPen(QPen(QColor(PALETTE["line"]), 1.0)) - painter.setBrush(QColor(PALETTE["surface_alt"])) + painter.setPen(QPen(QColor(PALETTE["line"]), 1.0)) + painter.setBrush(QColor(PALETTE["surface_alt"])) painter.drawEllipse(circle.adjusted(0.5, 0.5, -0.5, -0.5)) initial_font = QFont(style_option.font) initial_font.setPixelSize(10) initial_font.setWeight(QFont.Weight.Medium) painter.setFont(initial_font) - painter.setPen(QColor(PALETTE["muted"])) + painter.setPen(QColor(PALETTE["muted"])) painter.drawText(circle, Qt.AlignmentFlag.AlignCenter, initial) painter.setFont(style_option.font) - painter.setPen(QColor(PALETTE["heading"])) + painter.setPen(QColor(PALETTE["heading"])) name_rect = rect.adjusted(35, 0, -8, 0) painter.drawText( name_rect, @@ -382,8 +384,8 @@ def _row_action_button( button.setAccessibleName(tooltip) button.setToolTip(tooltip) button.setCursor(Qt.CursorShape.PointingHandCursor) - width = max(64, button.fontMetrics().horizontalAdvance(label) + 26) if label else 28 - button.setFixedSize(width, 28) + width = max(64, button.fontMetrics().horizontalAdvance(label) + 26) if label else 28 + button.setFixedSize(width, 28) if kind: button.setIcon(_painted_icon(kind, "danger" if danger else "accent", 15)) button.setIconSize(QSize(15, 15)) @@ -444,15 +446,15 @@ def prescription_status(row: Any) -> tuple[str, str]: return "已驳回", "danger" if status == 1: return "已通过", "success" - signature = signature_state(row) + signature = signature_state(row) if awaiting_prescription_upload(row, signature) and not _voided(row): return "待上传处方", "warning" - if signature.get("required") is True and signature.get("status") not in {"signed", "voided"}: - if signature.get("status") == "signing": - return "签名处理中", "warning" - if signature.get("status") == "uncertain": - return ("待验签" if signature.get("can_retry_verify") is True else "签署结果待确认", "warning") - return "待签名", "warning" + if signature.get("required") is True and signature.get("status") not in {"signed", "voided"}: + if signature.get("status") == "signing": + return "签名处理中", "warning" + if signature.get("status") == "uncertain": + return ("待验签" if signature.get("can_retry_verify") is True else "签署结果待确认", "warning") + return "待签名", "warning" return "待审核", "warning" @@ -473,7 +475,7 @@ def can_create_order(row: Any) -> bool: ) -def _is_pending_audit(row: Any) -> bool: +def _is_pending_audit(row: Any) -> bool: return ( row is not None and _int(first_value(row, "audit_status", "status"), 0) == 0 @@ -481,43 +483,43 @@ def _is_pending_audit(row: Any) -> bool: ) -def can_audit(row: Any) -> bool: +def can_audit(row: Any) -> bool: return _is_pending_audit(row) and can_review_uploaded_prescription(row, signature_state(row)) - - + + def can_edit_or_delete(row: Any) -> bool: return row is not None and not is_approved_active(row) -def _voided(row: Any) -> bool: - return _int(first_value(row, "void_status", "is_void"), 0) == 1 - - -def _can_change_issued_prescription(row: Any) -> bool: - return can_edit_or_delete(row) and not prescription_edit_is_locked(row) - - +def _voided(row: Any) -> bool: + return _int(first_value(row, "void_status", "is_void"), 0) == 1 + + +def _can_change_issued_prescription(row: Any) -> bool: + return can_edit_or_delete(row) and not prescription_edit_is_locked(row) + + def _formula(value: Any) -> str: text = str(value or "").strip().lower() return "辅方" if text in {"2", "aux", "auxiliary", "辅方"} else "主方" -def _is_blank_prescription(row: Any) -> bool: - if row is None or _truthy(get_value(row, "is_system_auto")): - return True - raw = getattr(row, "raw", None) - source = raw if isinstance(raw, Mapping) and raw else row - missing = object() - herbs = get_value(source, "herbs", missing) - # Compact historical rows may omit herbs; omission is not an empty prescription. - if herbs is missing: - return False - return not isinstance(herbs, (list, tuple)) or not any( - str(get_value(herb, "name", "") or "").strip() for herb in herbs - ) - - -def _order_warnings(row: Any) -> list[str]: +def _is_blank_prescription(row: Any) -> bool: + if row is None or _truthy(get_value(row, "is_system_auto")): + return True + raw = getattr(row, "raw", None) + source = raw if isinstance(raw, Mapping) and raw else row + missing = object() + herbs = get_value(source, "herbs", missing) + # Compact historical rows may omit herbs; omission is not an empty prescription. + if herbs is missing: + return False + return not isinstance(herbs, (list, tuple)) or not any( + str(get_value(herb, "name", "") or "").strip() for herb in herbs + ) + + +def _order_warnings(row: Any) -> list[str]: """Match the PC list's linked-order checks, including blank herb rows.""" raw = getattr(row, "raw", None) @@ -565,11 +567,11 @@ class _PrescriptionNumberDelegate(QStyledItemDelegate): text_option.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere) document.setDefaultTextOption(text_option) paragraphs = [ - f'
{escape(number)}
', - f'ID: {escape(record_id)}
', + f'{escape(number)}
', + f'ID: {escape(record_id)}
', ] paragraphs.extend( - f'' + f'
' + escape(warning) + "
" for warning in _order_warnings(row) @@ -634,7 +636,7 @@ def _audit_cell(_value: Any, row: Any) -> str: def _void_cell(_value: Any, row: Any) -> str: - return "作废" if _voided(row) else "—" + return "作废" if _voided(row) else "—" def _doctor_cell(_value: Any, row: Any) -> str: @@ -646,165 +648,165 @@ def _create_time_cell(value: Any, _row: Any) -> str: return format_record_time(raw) -class _DoctorOptionDelegate(QStyledItemDelegate): - """Draw an explicit checked state independent of native item indicators.""" - - def sizeHint(self, option: Any, index: QModelIndex) -> QSize: - return QSize(220, 36) - - def paint(self, painter: QPainter, option: Any, index: QModelIndex) -> None: - checked = index.data(Qt.ItemDataRole.CheckStateRole) == Qt.CheckState.Checked.value - painter.save() - painter.setRenderHint(QPainter.RenderHint.Antialiasing) - rect = option.rect.adjusted(2, 1, -2, -1) - hovered = bool(option.state & QStyle.StateFlag.State_MouseOver) - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor(PALETTE["accent_soft"] if checked else PALETTE["canvas"] if hovered else PALETTE["surface"])) - painter.drawRoundedRect(rect, 5, 5) - box = QRectF(rect.left() + 10, rect.center().y() - 8, 16, 16) - painter.setPen(QPen(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"]), 1)) - painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["surface"])) - painter.drawRoundedRect(box, 3, 3) - if checked: - pen = QPen(QColor(PALETTE["surface"]), 2) - pen.setCapStyle(Qt.PenCapStyle.RoundCap) - painter.setPen(pen) - x, y = int(box.x()), int(box.y()) - painter.drawLine(x + 4, y + 8, x + 7, y + 11) - painter.drawLine(x + 7, y + 11, x + 12, y + 5) - font = QFont(body_family()) - font.setPixelSize(13) - painter.setFont(font) - painter.setPen(QColor(PALETTE["text"])) - text_rect = rect.adjusted(38, 0, -54, 0) - label = painter.fontMetrics().elidedText(str(index.data() or ""), Qt.TextElideMode.ElideRight, text_rect.width()) - painter.drawText(text_rect, Qt.AlignmentFlag.AlignVCenter, label) - if checked: - painter.setPen(QColor(PALETTE["accent"])) - painter.drawText(rect.adjusted(0, 0, -12, 0), Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, "已选") - if option.state & QStyle.StateFlag.State_HasFocus: - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.setPen(QPen(QColor(PALETTE["line_strong"]), 1)) - painter.drawRoundedRect(rect, 5, 5) - painter.restore() - - def editorEvent(self, event: Any, model: Any, option: Any, index: QModelIndex) -> bool: - # The list handles whole-row toggles, independent of the native checkbox hit area. - return False - - -class _DoctorOptionsList(QListWidget): - @staticmethod - def _toggle(item: QListWidgetItem | None) -> None: - if item is not None and item.flags() & Qt.ItemFlag.ItemIsEnabled: - item.setCheckState(Qt.CheckState.Unchecked if item.checkState() == Qt.CheckState.Checked - else Qt.CheckState.Checked) - - def mousePressEvent(self, event: Any) -> None: - if event.button() == Qt.MouseButton.LeftButton: - item = self.itemAt(event.position().toPoint()) - self.setCurrentItem(item) - self._toggle(item) - event.accept() - return - super().mousePressEvent(event) - - def mouseReleaseEvent(self, event: Any) -> None: - if event.button() == Qt.MouseButton.LeftButton: - event.accept() - return - super().mouseReleaseEvent(event) - - def keyPressEvent(self, event: Any) -> None: - if event.key() == Qt.Key.Key_Space: - if not event.isAutoRepeat(): - self._toggle(self.currentItem()) - event.accept() - return - super().keyPressEvent(event) - - -class _DoctorSelectionDialog(QDialog): - def __init__(self, options: Mapping[int, str], selected: set[int], parent: QWidget) -> None: - super().__init__(parent) - self.setObjectName("DoctorSelectionDialog") - self.setWindowTitle("选择医生") - self.resize(420, 500) - self.setStyleSheet(clinical_stylesheet(""" - QDialog#DoctorSelectionDialog { background: $ds_surface; color: $ds_text; } - QListWidget#DoctorOptionsList { background: $ds_surface; border: 1px solid $ds_line; border-radius: 6px; padding: 3px; } - QLabel#DoctorSelectionCount { color: $ds_accent; font-size: 13px; } - QDialog#DoctorSelectionDialog QLineEdit { border: 1px solid $ds_line; border-radius: 6px; } - QDialog#DoctorSelectionDialog QLineEdit:focus { border-color: $ds_accent; } - QDialog#DoctorSelectionDialog QPushButton { background: $ds_surface; color: $ds_text; border: 1px solid $ds_line; border-radius: 6px; } - QDialog#DoctorSelectionDialog QPushButton:hover { background: $ds_canvas; border-color: $ds_line_strong; } - QDialog#DoctorSelectionDialog QPushButton:disabled { color: $ds_disabled; } - QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection { background: $ds_accent; color: $ds_surface; border-color: $ds_accent; } - QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; } - """)) - layout = QVBoxLayout(self) - layout.setContentsMargins(16, 16, 16, 16) - layout.setSpacing(10) - self.search = QLineEdit(self) - self.search.setObjectName("DoctorOptionSearch") - self.search.setPlaceholderText("搜索医生姓名") - self.search.setClearButtonEnabled(True) - layout.addWidget(self.search) - summary = QHBoxLayout() - self.count_label = QLabel(self) - self.count_label.setObjectName("DoctorSelectionCount") - summary.addWidget(self.count_label, 1) - self.clear_button = QPushButton("清空选择", self) - self.clear_button.clicked.connect(self._clear) - summary.addWidget(self.clear_button) - layout.addLayout(summary) - self.listing = _DoctorOptionsList(self) - self.listing.setObjectName("DoctorOptionsList") - self.listing.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection) - self.listing.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.listing.setMouseTracking(True) - self.listing.setItemDelegate(_DoctorOptionDelegate(self.listing)) - for doctor_id, name in sorted(options.items(), key=lambda item: item[1]): - item = QListWidgetItem(name) - item.setToolTip(name) - item.setData(Qt.ItemDataRole.UserRole, doctor_id) - item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable) - item.setCheckState(Qt.CheckState.Checked if doctor_id in selected else Qt.CheckState.Unchecked) - self.listing.addItem(item) - layout.addWidget(self.listing, 1) - self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel | QDialogButtonBox.StandardButton.Ok, self) - self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText("确定") - self.buttons.button(QDialogButtonBox.StandardButton.Ok).setObjectName("ConfirmDoctorSelection") - self.buttons.button(QDialogButtonBox.StandardButton.Cancel).setText("取消") - self.buttons.accepted.connect(self.accept) - self.buttons.rejected.connect(self.reject) - layout.addWidget(self.buttons) - self.listing.itemChanged.connect(self._update_summary) - self.search.textChanged.connect(self._filter) - self._update_summary() - - def selected_ids(self) -> set[int]: - return {_int(self.listing.item(i).data(Qt.ItemDataRole.UserRole)) - for i in range(self.listing.count()) - if self.listing.item(i).checkState() == Qt.CheckState.Checked} - - def _update_summary(self, *_args: Any) -> None: - count = len(self.selected_ids()) - self.count_label.setText(f"已选 {count} 位医生") - self.clear_button.setEnabled(count > 0) - - def _filter(self, text: str) -> None: - query = text.strip().casefold() - for i in range(self.listing.count()): - item = self.listing.item(i) - item.setHidden(query not in item.text().casefold()) - - def _clear(self) -> None: - for i in range(self.listing.count()): - self.listing.item(i).setCheckState(Qt.CheckState.Unchecked) - - -class DoctorMultiSelect(QWidget): +class _DoctorOptionDelegate(QStyledItemDelegate): + """Draw an explicit checked state independent of native item indicators.""" + + def sizeHint(self, option: Any, index: QModelIndex) -> QSize: + return QSize(220, 36) + + def paint(self, painter: QPainter, option: Any, index: QModelIndex) -> None: + checked = index.data(Qt.ItemDataRole.CheckStateRole) == Qt.CheckState.Checked.value + painter.save() + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + rect = option.rect.adjusted(2, 1, -2, -1) + hovered = bool(option.state & QStyle.StateFlag.State_MouseOver) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(PALETTE["accent_soft"] if checked else PALETTE["canvas"] if hovered else PALETTE["surface"])) + painter.drawRoundedRect(rect, 5, 5) + box = QRectF(rect.left() + 10, rect.center().y() - 8, 16, 16) + painter.setPen(QPen(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"]), 1)) + painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["surface"])) + painter.drawRoundedRect(box, 3, 3) + if checked: + pen = QPen(QColor(PALETTE["surface"]), 2) + pen.setCapStyle(Qt.PenCapStyle.RoundCap) + painter.setPen(pen) + x, y = int(box.x()), int(box.y()) + painter.drawLine(x + 4, y + 8, x + 7, y + 11) + painter.drawLine(x + 7, y + 11, x + 12, y + 5) + font = QFont(body_family()) + font.setPixelSize(13) + painter.setFont(font) + painter.setPen(QColor(PALETTE["text"])) + text_rect = rect.adjusted(38, 0, -54, 0) + label = painter.fontMetrics().elidedText(str(index.data() or ""), Qt.TextElideMode.ElideRight, text_rect.width()) + painter.drawText(text_rect, Qt.AlignmentFlag.AlignVCenter, label) + if checked: + painter.setPen(QColor(PALETTE["accent"])) + painter.drawText(rect.adjusted(0, 0, -12, 0), Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, "已选") + if option.state & QStyle.StateFlag.State_HasFocus: + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.setPen(QPen(QColor(PALETTE["line_strong"]), 1)) + painter.drawRoundedRect(rect, 5, 5) + painter.restore() + + def editorEvent(self, event: Any, model: Any, option: Any, index: QModelIndex) -> bool: + # The list handles whole-row toggles, independent of the native checkbox hit area. + return False + + +class _DoctorOptionsList(QListWidget): + @staticmethod + def _toggle(item: QListWidgetItem | None) -> None: + if item is not None and item.flags() & Qt.ItemFlag.ItemIsEnabled: + item.setCheckState(Qt.CheckState.Unchecked if item.checkState() == Qt.CheckState.Checked + else Qt.CheckState.Checked) + + def mousePressEvent(self, event: Any) -> None: + if event.button() == Qt.MouseButton.LeftButton: + item = self.itemAt(event.position().toPoint()) + self.setCurrentItem(item) + self._toggle(item) + event.accept() + return + super().mousePressEvent(event) + + def mouseReleaseEvent(self, event: Any) -> None: + if event.button() == Qt.MouseButton.LeftButton: + event.accept() + return + super().mouseReleaseEvent(event) + + def keyPressEvent(self, event: Any) -> None: + if event.key() == Qt.Key.Key_Space: + if not event.isAutoRepeat(): + self._toggle(self.currentItem()) + event.accept() + return + super().keyPressEvent(event) + + +class _DoctorSelectionDialog(QDialog): + def __init__(self, options: Mapping[int, str], selected: set[int], parent: QWidget) -> None: + super().__init__(parent) + self.setObjectName("DoctorSelectionDialog") + self.setWindowTitle("选择医生") + self.resize(420, 500) + self.setStyleSheet(clinical_stylesheet(""" + QDialog#DoctorSelectionDialog { background: $ds_surface; color: $ds_text; } + QListWidget#DoctorOptionsList { background: $ds_surface; border: 1px solid $ds_line; border-radius: 6px; padding: 3px; } + QLabel#DoctorSelectionCount { color: $ds_accent; font-size: 13px; } + QDialog#DoctorSelectionDialog QLineEdit { border: 1px solid $ds_line; border-radius: 6px; } + QDialog#DoctorSelectionDialog QLineEdit:focus { border-color: $ds_accent; } + QDialog#DoctorSelectionDialog QPushButton { background: $ds_surface; color: $ds_text; border: 1px solid $ds_line; border-radius: 6px; } + QDialog#DoctorSelectionDialog QPushButton:hover { background: $ds_canvas; border-color: $ds_line_strong; } + QDialog#DoctorSelectionDialog QPushButton:disabled { color: $ds_disabled; } + QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection { background: $ds_accent; color: $ds_surface; border-color: $ds_accent; } + QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; } + """)) + layout = QVBoxLayout(self) + layout.setContentsMargins(16, 16, 16, 16) + layout.setSpacing(10) + self.search = QLineEdit(self) + self.search.setObjectName("DoctorOptionSearch") + self.search.setPlaceholderText("搜索医生姓名") + self.search.setClearButtonEnabled(True) + layout.addWidget(self.search) + summary = QHBoxLayout() + self.count_label = QLabel(self) + self.count_label.setObjectName("DoctorSelectionCount") + summary.addWidget(self.count_label, 1) + self.clear_button = QPushButton("清空选择", self) + self.clear_button.clicked.connect(self._clear) + summary.addWidget(self.clear_button) + layout.addLayout(summary) + self.listing = _DoctorOptionsList(self) + self.listing.setObjectName("DoctorOptionsList") + self.listing.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection) + self.listing.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.listing.setMouseTracking(True) + self.listing.setItemDelegate(_DoctorOptionDelegate(self.listing)) + for doctor_id, name in sorted(options.items(), key=lambda item: item[1]): + item = QListWidgetItem(name) + item.setToolTip(name) + item.setData(Qt.ItemDataRole.UserRole, doctor_id) + item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable) + item.setCheckState(Qt.CheckState.Checked if doctor_id in selected else Qt.CheckState.Unchecked) + self.listing.addItem(item) + layout.addWidget(self.listing, 1) + self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel | QDialogButtonBox.StandardButton.Ok, self) + self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText("确定") + self.buttons.button(QDialogButtonBox.StandardButton.Ok).setObjectName("ConfirmDoctorSelection") + self.buttons.button(QDialogButtonBox.StandardButton.Cancel).setText("取消") + self.buttons.accepted.connect(self.accept) + self.buttons.rejected.connect(self.reject) + layout.addWidget(self.buttons) + self.listing.itemChanged.connect(self._update_summary) + self.search.textChanged.connect(self._filter) + self._update_summary() + + def selected_ids(self) -> set[int]: + return {_int(self.listing.item(i).data(Qt.ItemDataRole.UserRole)) + for i in range(self.listing.count()) + if self.listing.item(i).checkState() == Qt.CheckState.Checked} + + def _update_summary(self, *_args: Any) -> None: + count = len(self.selected_ids()) + self.count_label.setText(f"已选 {count} 位医生") + self.clear_button.setEnabled(count > 0) + + def _filter(self, text: str) -> None: + query = text.strip().casefold() + for i in range(self.listing.count()): + item = self.listing.item(i) + item.setHidden(query not in item.text().casefold()) + + def _clear(self) -> None: + for i in range(self.listing.count()): + self.listing.item(i).setCheckState(Qt.CheckState.Unchecked) + + +class DoctorMultiSelect(QWidget): """Compact checkable doctor selector fed by list rows/extend data.""" def __init__(self, parent: QWidget | None = None) -> None: @@ -832,14 +834,14 @@ class DoctorMultiSelect(QWidget): self._options[doctor_id] = name self._update_text() - def _choose(self) -> None: - dialog = _DoctorSelectionDialog(self._options, self._selected, self) - try: - if dialog.exec() == QDialog.DialogCode.Accepted: - self._selected = dialog.selected_ids() - {0} - self._update_text() - finally: - dialog.deleteLater() + def _choose(self) -> None: + dialog = _DoctorSelectionDialog(self._options, self._selected, self) + try: + if dialog.exec() == QDialog.DialogCode.Accepted: + self._selected = dialog.selected_ids() - {0} + self._update_text() + finally: + dialog.deleteLater() def _update_text(self) -> None: if not self._selected: @@ -849,9 +851,9 @@ class DoctorMultiSelect(QWidget): self.button.setText("、".join(names[:2]) + (f" 等{len(names)}人" if len(names) > 2 else "")) -def _blue_prescription_icon(kind: str, color: str = PALETTE["accent"], size: int = 15) -> QIcon: +def _blue_prescription_icon(kind: str, color: str = PALETTE["accent"], size: int = 15) -> QIcon: result = QIcon(icons.icon(kind, color, size)) - result.addPixmap(icons.pixmap(kind, PALETTE["disabled"], size), QIcon.Mode.Disabled) + result.addPixmap(icons.pixmap(kind, PALETTE["disabled"], size), QIcon.Mode.Disabled) return result @@ -859,7 +861,7 @@ class _PrescriptionCombo(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() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect())) painter.end() @@ -868,7 +870,7 @@ class _PrescriptionDateTime(QDateTimeEdit): def paintEvent(self, event: Any) -> None: super().paintEvent(event) painter = QPainter(self) - glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14) + glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14) painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect())) painter.end() @@ -881,7 +883,7 @@ class _PrescriptionDoctorButton(QPushButton): option.text = self.fontMetrics().elidedText(self.text(), Qt.TextElideMode.ElideRight, max(1, self.width() - 48)) painter = QPainter(self) self.style().drawControl(QStyle.ControlElement.CE_PushButton, option, painter, self) - glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14) + glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14) painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect())) painter.end() @@ -893,13 +895,13 @@ class _PrescriptionDoctorButton(QPushButton): def _prescription_cell_background(painter: QPainter, option: Any, index: QModelIndex) -> None: 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 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)) @@ -931,7 +933,7 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate): font = QFont(body_family()) font.setPixelSize(14) painter.setFont(font) - painter.setPen(QColor(PALETTE["text"])) + painter.setPen(QColor(PALETTE["text"])) text = str(index.data(Qt.ItemDataRole.DisplayRole) or "") column = index.column() if column == 0: @@ -944,9 +946,9 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate): elif column in (3, 6): kind = index.data(_ROLE_TAG_KIND) foreground, background = { - "accent": (PALETTE["accent"], PALETTE["accent_soft"]), "success": (PALETTE["accent"], PALETTE["accent_soft"]), - "warning": (PALETTE["warning"], PALETTE["warning_soft"]), "danger": (PALETTE["danger"], PALETTE["danger_soft"]), - }.get(kind, (PALETTE["muted"], PALETTE["surface_alt"])) + "accent": (PALETTE["accent"], PALETTE["accent_soft"]), "success": (PALETTE["accent"], PALETTE["accent_soft"]), + "warning": (PALETTE["warning"], PALETTE["warning_soft"]), "danger": (PALETTE["danger"], PALETTE["danger_soft"]), + }.get(kind, (PALETTE["muted"], PALETTE["surface_alt"])) font.setPixelSize(13) painter.setFont(font) label = painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, max(1, rect.width() - 12)) @@ -959,7 +961,7 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate): painter.setPen(QColor(foreground)) painter.drawText(pill, Qt.AlignmentFlag.AlignCenter, label) elif column != 2: - lines = text.rsplit(" · ", 2) if column == 5 else text.rsplit(" ", 1) if column == 10 else text.splitlines() if column == 12 else [text] + lines = text.rsplit(" · ", 2) if column == 5 else text.rsplit(" ", 1) if column == 10 else text.splitlines() if column == 12 else [text] if len(lines) > 1: primary, secondary = lines[0], " · ".join(lines[1:]) if column == 5 else lines[1] if column == 5: @@ -974,7 +976,7 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate): font = QFont(body_family()) font.setPixelSize(13) painter.setFont(font) - painter.setPen(QColor(PALETTE["muted"])) + painter.setPen(QColor(PALETTE["muted"])) second_rect = first_rect.translated(0, 26) painter.drawText(second_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, painter.fontMetrics().elidedText(secondary, Qt.TextElideMode.ElideRight, rect.width())) else: @@ -998,11 +1000,11 @@ class _PrescriptionNumberBlueDelegate(_PrescriptionNumberDelegate): text_option.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere) document.setDefaultTextOption(text_option) paragraphs = [ - f'{escape(number)}
', - f'ID: {escape(record_id)}
', + f'{escape(number)}
', + f'ID: {escape(record_id)}
', ] paragraphs.extend( - f'' + escape(warning) + "
" + f'' + escape(warning) + "
" for warning in _order_warnings(row) ) document.setHtml("".join(paragraphs)) @@ -1024,184 +1026,184 @@ class _PrescriptionNumberBlueDelegate(_PrescriptionNumberDelegate): return QSize(width, max(80, ceil(document.size().height()) + 28)) -class _PrescriptionCopyText(QTextEdit): - """One transient, read-only text surface for the active painted cell.""" - - def __init__(self, table: _PrescriptionBlueTable) -> None: - super().__init__(table.viewport()) - self.table = table - self.setObjectName("PrescriptionCopyText") - self.setReadOnly(True) - self.setFrameShape(QFrame.Shape.NoFrame) - self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.setStyleSheet( - f"QTextEdit#PrescriptionCopyText {{background:{PALETTE['accent_soft']};" - f"color:{PALETTE['text']};border:0;padding:0;" - f"selection-background-color:{PALETTE['accent']};selection-color:white;}}" - ) - self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) - self.customContextMenuRequested.connect( - lambda point: table.customContextMenuRequested.emit(self.viewport().mapTo(table.viewport(), point)) - ) - self.hide() - - def keyPressEvent(self, event: Any) -> None: # noqa: N802 - if event.matches(QKeySequence.StandardKey.Copy): - if self.textCursor().hasSelection(): - self.copy() - else: - self.table.copy_cell() - event.accept() - elif event.key() == Qt.Key.Key_Escape: - self.table._hide_copy_text() - self.table.setFocus() - event.accept() - else: - super().keyPressEvent(event) - - def wheelEvent(self, event: Any) -> None: # noqa: N802 - self.table._hide_copy_text() - QApplication.sendEvent(self.table.viewport(), event) - - +class _PrescriptionCopyText(QTextEdit): + """One transient, read-only text surface for the active painted cell.""" + + def __init__(self, table: _PrescriptionBlueTable) -> None: + super().__init__(table.viewport()) + self.table = table + self.setObjectName("PrescriptionCopyText") + self.setReadOnly(True) + self.setFrameShape(QFrame.Shape.NoFrame) + self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.setStyleSheet( + f"QTextEdit#PrescriptionCopyText {{background:{PALETTE['accent_soft']};" + f"color:{PALETTE['text']};border:0;padding:0;" + f"selection-background-color:{PALETTE['accent']};selection-color:white;}}" + ) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.customContextMenuRequested.connect( + lambda point: table.customContextMenuRequested.emit(self.viewport().mapTo(table.viewport(), point)) + ) + self.hide() + + def keyPressEvent(self, event: Any) -> None: # noqa: N802 + if event.matches(QKeySequence.StandardKey.Copy): + if self.textCursor().hasSelection(): + self.copy() + else: + self.table.copy_cell() + event.accept() + elif event.key() == Qt.Key.Key_Escape: + self.table._hide_copy_text() + self.table.setFocus() + event.accept() + else: + super().keyPressEvent(event) + + def wheelEvent(self, event: Any) -> None: # noqa: N802 + self.table._hide_copy_text() + QApplication.sendEvent(self.table.viewport(), event) + + class _PrescriptionBlueTable(SortableTable): - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self._copy_index = QPersistentModelIndex() - self._copy_drag = False - self.copy_text = _PrescriptionCopyText(self) - for signal in ( - self.model().modelAboutToBeReset, self.model().layoutAboutToBeChanged, - self.model().rowsAboutToBeRemoved, self.model().rowsAboutToBeInserted, - self.horizontalScrollBar().valueChanged, self.verticalScrollBar().valueChanged, - self.horizontalHeader().sectionResized, self.horizontalHeader().sectionMoved, - ): - signal.connect(self._hide_copy_text) - self.model().dataChanged.connect(self._copy_data_changed) - self.selectionModel().currentChanged.connect(self._copy_current_changed) - - @staticmethod - def _copyable(index: QModelIndex) -> bool: - return index.isValid() and index.column() in (1, 3, 4, 5, 6, 7, 8, 9, 10) - - def cell_copy_text(self, index: QModelIndex) -> str: - if not self._copyable(index): - return "" - if index.column() == 1: - return str(index.data(Qt.ItemDataRole.AccessibleTextRole) or index.data() or "") - return str(index.data() or "") - - def row_copy_text(self, row: int) -> str: - header = self.horizontalHeader() - return "\t".join( - self.cell_copy_text(self.model().index(row, column)).replace("\n", " ") - for column in (header.logicalIndex(visual) for visual in range(self.columnCount())) - if column not in (0, 2) and not self.isColumnHidden(column) - ) - - def copy_cell(self) -> None: - text = self.cell_copy_text(self.currentIndex()) - if text: - QApplication.clipboard().setText(text) - - def _hide_copy_text(self, *_args: Any) -> None: - self.copy_text.hide() - self._copy_index = QPersistentModelIndex() - self._copy_drag = False - - def _copy_current_changed(self, current: QModelIndex, _previous: QModelIndex) -> None: - if current != self._copy_index: - self._hide_copy_text() - - def _copy_data_changed(self, top: QModelIndex, bottom: QModelIndex, *_args: Any) -> None: - if (self._copy_index.isValid() - and top.row() <= self._copy_index.row() <= bottom.row() - and top.column() <= self._copy_index.column() <= bottom.column()): - self._hide_copy_text() - - def _show_copy_text(self, index: QModelIndex) -> None: - self._copy_index = QPersistentModelIndex(index) - self.copy_text.setGeometry(self.visualRect(index).adjusted(1, 1, -1, -1)) - text = self.cell_copy_text(index) - if index.column() == 5: - parts = text.rsplit(" · ", 2) - text = parts[0] + ("\n" + " · ".join(parts[1:]) if len(parts) > 1 else "") - elif index.column() == 10: - text = "\n".join(text.rsplit(" ", 1)) - font = QFont(body_family()) - font.setPixelSize(14) - self.copy_text.setFont(font) - self.copy_text.setPlainText(text) - document = self.copy_text.document() - document.setDocumentMargin(0) - document.setTextWidth(max(1, self.copy_text.width() - 24)) - top = max(11, round((self.copy_text.height() - document.size().height()) / 2)) - self.copy_text.setViewportMargins(11, top, 11, 0) - self.copy_text.show() - self.copy_text.raise_() - self.copy_text.setFocus(Qt.FocusReason.MouseFocusReason) - - def _forward_copy_mouse(self, event: QMouseEvent) -> None: - target = self.copy_text.viewport() - local = QPointF(target.mapFromGlobal(event.globalPosition().toPoint())) - forwarded = QMouseEvent( - event.type(), local, event.globalPosition(), event.button(), event.buttons(), event.modifiers() - ) - QApplication.sendEvent(target, forwarded) - event.accept() - - def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - index = self.indexAt(event.position().toPoint()) - self._hide_copy_text() - super().mousePressEvent(event) - if event.button() == Qt.MouseButton.LeftButton and self._copyable(index): - self._show_copy_text(index) - self._copy_drag = True - self._forward_copy_mouse(event) - - def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 - if self._copy_drag: - self._forward_copy_mouse(event) - return - self.viewport().setCursor( - Qt.CursorShape.IBeamCursor if self._copyable(self.indexAt(event.position().toPoint())) - else Qt.CursorShape.ArrowCursor - ) - super().mouseMoveEvent(event) - - def mouseDoubleClickEvent(self, event: QMouseEvent) -> None: # noqa: N802 - index = self.indexAt(event.position().toPoint()) - if event.button() == Qt.MouseButton.LeftButton and self._copyable(index): - self.setCurrentIndex(index) - if self._copy_index != index: - self._show_copy_text(index) - self._forward_copy_mouse(event) - return - super().mouseDoubleClickEvent(event) - - def mouseReleaseEvent(self, event: QMouseEvent) -> None: # noqa: N802 - if self._copy_drag: - self._forward_copy_mouse(event) - self._copy_drag = False - return - super().mouseReleaseEvent(event) - - def keyPressEvent(self, event: Any) -> None: # noqa: N802 - if event.matches(QKeySequence.StandardKey.Copy): - if self._copyable(self.currentIndex()): - self.copy_cell() - elif self.currentRow() >= 0: - QApplication.clipboard().setText(self.row_copy_text(self.currentRow())) - event.accept() - return - super().keyPressEvent(event) - - def resizeEvent(self, event: Any) -> None: # noqa: N802 - if hasattr(self, "copy_text"): - self._hide_copy_text() - super().resizeEvent(event) - + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._copy_index = QPersistentModelIndex() + self._copy_drag = False + self.copy_text = _PrescriptionCopyText(self) + for signal in ( + self.model().modelAboutToBeReset, self.model().layoutAboutToBeChanged, + self.model().rowsAboutToBeRemoved, self.model().rowsAboutToBeInserted, + self.horizontalScrollBar().valueChanged, self.verticalScrollBar().valueChanged, + self.horizontalHeader().sectionResized, self.horizontalHeader().sectionMoved, + ): + signal.connect(self._hide_copy_text) + self.model().dataChanged.connect(self._copy_data_changed) + self.selectionModel().currentChanged.connect(self._copy_current_changed) + + @staticmethod + def _copyable(index: QModelIndex) -> bool: + return index.isValid() and index.column() in (1, 3, 4, 5, 6, 7, 8, 9, 10) + + def cell_copy_text(self, index: QModelIndex) -> str: + if not self._copyable(index): + return "" + if index.column() == 1: + return str(index.data(Qt.ItemDataRole.AccessibleTextRole) or index.data() or "") + return str(index.data() or "") + + def row_copy_text(self, row: int) -> str: + header = self.horizontalHeader() + return "\t".join( + self.cell_copy_text(self.model().index(row, column)).replace("\n", " ") + for column in (header.logicalIndex(visual) for visual in range(self.columnCount())) + if column not in (0, 2) and not self.isColumnHidden(column) + ) + + def copy_cell(self) -> None: + text = self.cell_copy_text(self.currentIndex()) + if text: + QApplication.clipboard().setText(text) + + def _hide_copy_text(self, *_args: Any) -> None: + self.copy_text.hide() + self._copy_index = QPersistentModelIndex() + self._copy_drag = False + + def _copy_current_changed(self, current: QModelIndex, _previous: QModelIndex) -> None: + if current != self._copy_index: + self._hide_copy_text() + + def _copy_data_changed(self, top: QModelIndex, bottom: QModelIndex, *_args: Any) -> None: + if (self._copy_index.isValid() + and top.row() <= self._copy_index.row() <= bottom.row() + and top.column() <= self._copy_index.column() <= bottom.column()): + self._hide_copy_text() + + def _show_copy_text(self, index: QModelIndex) -> None: + self._copy_index = QPersistentModelIndex(index) + self.copy_text.setGeometry(self.visualRect(index).adjusted(1, 1, -1, -1)) + text = self.cell_copy_text(index) + if index.column() == 5: + parts = text.rsplit(" · ", 2) + text = parts[0] + ("\n" + " · ".join(parts[1:]) if len(parts) > 1 else "") + elif index.column() == 10: + text = "\n".join(text.rsplit(" ", 1)) + font = QFont(body_family()) + font.setPixelSize(14) + self.copy_text.setFont(font) + self.copy_text.setPlainText(text) + document = self.copy_text.document() + document.setDocumentMargin(0) + document.setTextWidth(max(1, self.copy_text.width() - 24)) + top = max(11, round((self.copy_text.height() - document.size().height()) / 2)) + self.copy_text.setViewportMargins(11, top, 11, 0) + self.copy_text.show() + self.copy_text.raise_() + self.copy_text.setFocus(Qt.FocusReason.MouseFocusReason) + + def _forward_copy_mouse(self, event: QMouseEvent) -> None: + target = self.copy_text.viewport() + local = QPointF(target.mapFromGlobal(event.globalPosition().toPoint())) + forwarded = QMouseEvent( + event.type(), local, event.globalPosition(), event.button(), event.buttons(), event.modifiers() + ) + QApplication.sendEvent(target, forwarded) + event.accept() + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + index = self.indexAt(event.position().toPoint()) + self._hide_copy_text() + super().mousePressEvent(event) + if event.button() == Qt.MouseButton.LeftButton and self._copyable(index): + self._show_copy_text(index) + self._copy_drag = True + self._forward_copy_mouse(event) + + def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if self._copy_drag: + self._forward_copy_mouse(event) + return + self.viewport().setCursor( + Qt.CursorShape.IBeamCursor if self._copyable(self.indexAt(event.position().toPoint())) + else Qt.CursorShape.ArrowCursor + ) + super().mouseMoveEvent(event) + + def mouseDoubleClickEvent(self, event: QMouseEvent) -> None: # noqa: N802 + index = self.indexAt(event.position().toPoint()) + if event.button() == Qt.MouseButton.LeftButton and self._copyable(index): + self.setCurrentIndex(index) + if self._copy_index != index: + self._show_copy_text(index) + self._forward_copy_mouse(event) + return + super().mouseDoubleClickEvent(event) + + def mouseReleaseEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if self._copy_drag: + self._forward_copy_mouse(event) + self._copy_drag = False + return + super().mouseReleaseEvent(event) + + def keyPressEvent(self, event: Any) -> None: # noqa: N802 + if event.matches(QKeySequence.StandardKey.Copy): + if self._copyable(self.currentIndex()): + self.copy_cell() + elif self.currentRow() >= 0: + QApplication.clipboard().setText(self.row_copy_text(self.currentRow())) + event.accept() + return + super().keyPressEvent(event) + + def resizeEvent(self, event: Any) -> None: # noqa: N802 + if hasattr(self, "copy_text"): + self._hide_copy_text() + super().resizeEvent(event) + def setCellWidget(self, row: int, column: int, widget: QWidget) -> None: # noqa: N802 super().setCellWidget(row, column, widget) if column == 2: @@ -1209,7 +1211,7 @@ class _PrescriptionBlueTable(SortableTable): for button in widget.findChildren(QPushButton): kind = {"查看处方": "eye", "编辑处方": "pencil", "删除处方": "trash"}.get(button.accessibleName()) if kind: - button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"])) + button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"])) class PrescriptionsPage(QWidget): @@ -1238,26 +1240,28 @@ class PrescriptionsPage(QWidget): self._detail_target = 0 self._diagnosis_detail_generation = 0 self._diagnosis_detail_target = 0 - self._mutation_pending = False - self._audit_check_pending = False - self._ai_statuses: dict[int, dict[str, Any]] = {} - self._ai_enabled = False - self._agreement_visible = False - self._capability_agreement_visible = False - self._ai_capability_token = 0 - self._ai_capability_pending = False - self._ai_request_token = 0 - self._ai_pending = False - self._ai_timer = QTimer(self) - self._ai_timer.setInterval(5000) - self._ai_timer.timeout.connect(self._load_ai_statuses) - self._ai_scroll_timer = QTimer(self) - self._ai_scroll_timer.setSingleShot(True) - self._ai_scroll_timer.setInterval(180) - self._ai_scroll_timer.timeout.connect(self._load_ai_statuses) + self._mutation_pending = False + self._audit_check_pending = False + self._ai_statuses: dict[int, dict[str, Any]] = {} + self._ai_enabled = False + self._agreement_visible = False + self._capability_agreement_visible = False + self._ai_capability_token = 0 + self._ai_capability_pending = False + self._ai_request_token = 0 + self._ai_pending = False + self._ai_timer = QTimer(self) + self._ai_timer.setInterval(5000) + self._ai_timer.timeout.connect(self._load_ai_statuses) + self._ai_scroll_timer = QTimer(self) + self._ai_scroll_timer.setSingleShot(True) + self._ai_scroll_timer.setInterval(180) + self._ai_scroll_timer.timeout.connect(self._load_ai_statuses) 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("PrescriptionWorkspaceScroll") self.scroll.setWidgetResizable(True) @@ -1267,7 +1271,7 @@ class PrescriptionsPage(QWidget): self.content.setObjectName("PrescriptionWorkspaceContent") 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( @@ -1285,16 +1289,16 @@ class PrescriptionsPage(QWidget): self.orders_button.setCursor(Qt.CursorShape.PointingHandCursor) self.orders_button.setVisible(has_permission(permissions, "tcm.prescriptionOrder/lists")) self.orders_button.clicked.connect(lambda: self._open_orders()) - header.add_action(self.orders_button) - self.ai_statistics_button = QPushButton("AI 一致度统计", header) - self.ai_statistics_button.hide() - self.ai_statistics_button.clicked.connect(self._open_ai_statistics) - header.add_action(self.ai_statistics_button) + header.add_action(self.orders_button) + self.ai_statistics_button = QPushButton("AI 一致度统计", header) + self.ai_statistics_button.hide() + self.ai_statistics_button.clicked.connect(self._open_ai_statistics) + header.add_action(self.ai_statistics_button) self.add_button = QPushButton("新增处方", header) self.add_button.setObjectName("PrescriptionAddButton") self.add_button.setMinimumWidth(122) self.add_button.setProperty("variant", "primary") - self.add_button.setIcon(_blue_prescription_icon("plus", PALETTE["surface"])) + self.add_button.setIcon(_blue_prescription_icon("plus", PALETTE["surface"])) self.add_button.setIconSize(QSize(15, 15)) self.add_button.setCursor(Qt.CursorShape.PointingHandCursor) self.add_button.setVisible(has_permission(permissions, "cf.prescription/add")) @@ -1302,20 +1306,43 @@ class PrescriptionsPage(QWidget): header.add_action(self.add_button) root.addWidget(header) filters = self._build_filters() - self.filter_card = filters - root.addWidget(filters) - self.filter_disclosure = FilterDisclosure(self, [filters]) - header.add_action(self.filter_disclosure.button) - header.set_compact() + self.filter_card = filters + root.addWidget(filters) + self.filter_disclosure = FilterDisclosure(self, [filters]) + header.add_action(self.filter_disclosure.button) + header.set_compact() + self.spatial_bridge = SpatialContextBridgeBar( + "电子处方双签流转与药师审方中心 · 已通过处方锁定归档", + on_filter_patient=self._filter_by_context_patient, + parent=self.content, + ) + self.spatial_bridge.setVisible(False) + root.insertWidget(1, self.spatial_bridge) self.banner = MessageBanner() root.addWidget(self.banner) table_card = self._build_table_card() self.table_card = table_card root.addWidget(table_card, 1) for button, kind in ((self.view_button, "eye"), (self.edit_button, "pencil"), (self.delete_button, "trash")): - button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"])) + button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"])) self._load_doctor_options() + 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, 'tcm.prescriptionOrder/lists'): + self.spatial_bridge.add_action_widget(self.orders_button) + if has_permission(self.permissions, 'cf.prescription/add'): + self.spatial_bridge.add_action_widget(self.add_button) + self.spatial_bridge.add_action_widget(self.filter_disclosure.button) + self.spatial_bridge.setVisible(True) + + def _filter_by_context_patient(self, patient_name: str) -> None: + self.patient_filter.setText(patient_name) + self._search() + def _build_filters(self) -> QWidget: frame = QFrame() frame.setObjectName("PrescriptionFilterBar") @@ -1435,10 +1462,10 @@ class PrescriptionsPage(QWidget): toolbar.addWidget(self.count_badge) toolbar.addStretch(1) self.view_button = self._action_button("查看", "cf.prescription/read", self._view_selected) - toolbar.addWidget(self.view_button) - self.ai_report_button = self._action_button("AI 报告", "tcm.prescriptionAi/reports", self._open_ai_report) - self.ai_report_button.hide() - toolbar.addWidget(self.ai_report_button) + toolbar.addWidget(self.view_button) + self.ai_report_button = self._action_button("AI 报告", "tcm.prescriptionAi/reports", self._open_ai_report) + self.ai_report_button.hide() + toolbar.addWidget(self.ai_report_button) self.patch_button = self._action_button( "修改患者", "tcm.prescription/patchPatient", self._patch_selected ) @@ -1455,10 +1482,10 @@ class PrescriptionsPage(QWidget): "审核", "cf.prescription/audit", self._audit_selected ) toolbar.addWidget(self.audit_button) - self.void_button = self._action_button("作废", None, self._void_selected, danger=True) - toolbar.addWidget(self.void_button) - self.reissue_button = self._action_button("重新开方", None, self._reissue_selected) - toolbar.addWidget(self.reissue_button) + self.void_button = self._action_button("作废", None, self._void_selected, danger=True) + toolbar.addWidget(self.void_button) + self.reissue_button = self._action_button("重新开方", None, self._reissue_selected) + toolbar.addWidget(self.reissue_button) self.delete_button = self._action_button( "删除", "cf.prescription/del", self._delete_selected, danger=True ) @@ -1466,20 +1493,20 @@ class PrescriptionsPage(QWidget): refresh = QPushButton("刷新") refresh.setProperty("variant", "ghost") refresh.setCursor(Qt.CursorShape.PointingHandCursor) - refresh.setIcon(_blue_prescription_icon("refresh", PALETTE["muted"])) + refresh.setIcon(_blue_prescription_icon("refresh", PALETTE["muted"])) refresh.setIconSize(QSize(15, 15)) refresh.clicked.connect(self.refresh) - toolbar.addWidget(refresh) - layout.addWidget(toolbar_scroll) - self.ai_status_notice = QLabel("AI 分析:正在检查服务状态。", card) - self.ai_status_notice.setObjectName("PrescriptionAiStatusNotice") - self.ai_status_notice.setProperty("role", "muted") - self.ai_status_notice.setTextFormat(Qt.TextFormat.PlainText) - self.ai_status_notice.setWordWrap(True) - self.ai_status_notice.setMargin(12) - self.ai_status_notice.setAccessibleName("AI 分析状态") - layout.addWidget(self.ai_status_notice) - self.stack = QStackedWidget() + toolbar.addWidget(refresh) + layout.addWidget(toolbar_scroll) + self.ai_status_notice = QLabel("AI 分析:正在检查服务状态。", card) + self.ai_status_notice.setObjectName("PrescriptionAiStatusNotice") + self.ai_status_notice.setProperty("role", "muted") + self.ai_status_notice.setTextFormat(Qt.TextFormat.PlainText) + self.ai_status_notice.setWordWrap(True) + self.ai_status_notice.setMargin(12) + self.ai_status_notice.setAccessibleName("AI 分析状态") + layout.addWidget(self.ai_status_notice) + self.stack = QStackedWidget() table_host = QWidget() table_layout = QVBoxLayout(table_host) table_layout.setContentsMargins(0, 0, 0, 0) @@ -1496,9 +1523,9 @@ class PrescriptionsPage(QWidget): TableColumn("void_status", "作废", 72, _void_cell), TableColumn("doctor_name", "医生信息", 180, _doctor_cell), TableColumn("assistant_name", "医助", 125), - TableColumn("create_time", "创建时间", 180, _create_time_cell), - TableColumn("__ai_status__", "AI 分析", 144, lambda _value, _row: "—"), - TableColumn("__ai_agreement__", "与 AI 一致度", 130, lambda _value, _row: "—"), + TableColumn("create_time", "创建时间", 180, _create_time_cell), + TableColumn("__ai_status__", "AI 分析", 144, lambda _value, _row: "—"), + TableColumn("__ai_agreement__", "与 AI 一致度", 130, lambda _value, _row: "—"), ] ) self.table.setObjectName("PrescriptionTable") @@ -1511,14 +1538,14 @@ class PrescriptionsPage(QWidget): self.table.horizontalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive) self.table.horizontalHeader().moveSection(2, 10) - # 紧凑配比列宽(总计 1124px),确保 1440px 与 1536px 桌面视窗下右侧「操作」列完整呈现无横向溢出 - for column, width in enumerate((40, 174, 134, 88, 76, 132, 92, 64, 122, 78, 124)): - self.table.setColumnWidth(column, width) - self.table.setColumnHidden(11, True) - self.table.setColumnHidden(12, True) - self.table.horizontalHeaderItem(12).setToolTip("分别显示千问、OpenAI 的药味与剂量一致度;点击查看逐味贡献。") - self.table.horizontalHeader().viewport().installEventFilter(self) - self.table.verticalScrollBar().valueChanged.connect(lambda _value: self._schedule_ai_statuses()) + # 紧凑配比列宽(总计 1124px),确保 1440px 与 1536px 桌面视窗下右侧「操作」列完整呈现无横向溢出 + for column, width in enumerate((40, 174, 134, 88, 76, 132, 92, 64, 122, 78, 124)): + self.table.setColumnWidth(column, width) + self.table.setColumnHidden(11, True) + self.table.setColumnHidden(12, True) + self.table.horizontalHeaderItem(12).setToolTip("分别显示千问、OpenAI 的药味与剂量一致度;点击查看逐味贡献。") + self.table.horizontalHeader().viewport().installEventFilter(self) + self.table.verticalScrollBar().valueChanged.connect(lambda _value: self._schedule_ai_statuses()) self.table.setWordWrap(False) # Rows are not uniform: the number column's delegate grows a row that # carries an order warning so the warning text stays readable without a @@ -1528,13 +1555,13 @@ class PrescriptionsPage(QWidget): self.table.setItemDelegate(_PrescriptionInfoDelegate(self.table)) self.table.setItemDelegateForColumn(1, _PrescriptionNumberBlueDelegate(self.table)) self.table.horizontalHeader().sectionResized.connect(self._number_column_resized) - self.table.horizontalHeaderItem(0).setIcon(_blue_prescription_icon("checkbox", PALETTE["disabled"], 14)) + self.table.horizontalHeaderItem(0).setIcon(_blue_prescription_icon("checkbox", PALETTE["disabled"], 14)) self.table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignmentFlag.AlignCenter) self.table.itemSelectionChanged.connect(self._selection_changed) - self.table.itemDoubleClicked.connect(lambda _item: self._view_selected()) - self.table.itemClicked.connect(lambda item: self._open_ai_report() if item.column() in {11, 12} else None) - self.table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) - self.table.customContextMenuRequested.connect(self._open_ai_context_menu) + self.table.itemDoubleClicked.connect(lambda _item: self._view_selected()) + self.table.itemClicked.connect(lambda item: self._open_ai_report() if item.column() in {11, 12} else None) + self.table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.table.customContextMenuRequested.connect(self._open_ai_context_menu) table_layout.addWidget(self.table, 1) self.pager = InfiniteList(self._page_size) self.pager.bind(self.table) @@ -1578,27 +1605,27 @@ class PrescriptionsPage(QWidget): self.filter_grid.setColumnStretch(column, stretch) self.filter_card.setFixedHeight(200 if compact else 144) - def _number_column_resized(self, column: int, _old_size: int, _new_size: int) -> None: + def _number_column_resized(self, column: int, _old_size: int, _new_size: int) -> None: if column == 1: - self.table.resizeRowsToContents() - - def eventFilter(self, watched: Any, event: Any) -> bool: - if hasattr(self, "table") and watched is self.table.horizontalHeader().viewport() and event.type() in {QEvent.Type.MouseButtonPress, QEvent.Type.MouseButtonRelease, QEvent.Type.MouseButtonDblClick}: - header = self.table.horizontalHeader() - position = event.position().toPoint() - column = header.logicalIndexAt(position) - if column in {11, 12} and event.button() == Qt.MouseButton.LeftButton: - relative = position.x() - header.sectionViewportPosition(column) - # Keep native column resizing, but never rank mixed-model display - # text or treat unavailable values as numeric zero through sorting. - if 5 < relative < header.sectionSize(column) - 5: - return True - return super().eventFilter(watched, event) + self.table.resizeRowsToContents() + + def eventFilter(self, watched: Any, event: Any) -> bool: + if hasattr(self, "table") and watched is self.table.horizontalHeader().viewport() and event.type() in {QEvent.Type.MouseButtonPress, QEvent.Type.MouseButtonRelease, QEvent.Type.MouseButtonDblClick}: + header = self.table.horizontalHeader() + position = event.position().toPoint() + column = header.logicalIndexAt(position) + if column in {11, 12} and event.button() == Qt.MouseButton.LeftButton: + relative = position.x() - header.sectionViewportPosition(column) + # Keep native column resizing, but never rank mixed-model display + # text or treat unavailable values as numeric zero through sorting. + if 5 < relative < header.sectionSize(column) - 5: + return True + return super().eventFilter(watched, event) def _action_button( self, text: str, - permission: str | None, + permission: str | None, handler: Callable[[], None], *, danger: bool = False, @@ -1611,7 +1638,7 @@ class PrescriptionsPage(QWidget): "查看": "eye", "编辑": "pencil", "删除": "trash", - "重新开方": "plus", + "重新开方": "plus", "上传处方": "send", }.get(text) if icon_kind: @@ -1621,7 +1648,7 @@ class PrescriptionsPage(QWidget): button.setIconSize(QSize(15, 15)) if danger: button.setProperty("variant", "danger") - button.setVisible(permission is not None and has_permission(self.permissions, permission)) + button.setVisible(permission is not None and has_permission(self.permissions, permission)) button.setEnabled(False) button.clicked.connect(handler) return button @@ -1676,16 +1703,16 @@ class PrescriptionsPage(QWidget): self.doctor_filter.clear() self._search() - def refresh(self) -> None: - self._ai_timer.stop() - self._ai_request_token += 1 - self._ai_pending = False - self._ai_statuses.clear() + def refresh(self) -> None: + self._ai_timer.stop() + self._ai_request_token += 1 + self._ai_pending = False + self._ai_statuses.clear() self._loading = True self._refresh_pending = False self._generation += 1 generation = self._generation - self._load_ai_capabilities() + self._load_ai_capabilities() page_size = self._page_size start_time, end_time = self._date_filters() filters: dict[str, Any] = { @@ -1719,9 +1746,9 @@ class PrescriptionsPage(QWidget): if generation != self._generation: return rows = page_items(result) - self.table.set_rows(rows) - self._decorate_rows() - self._render_ai_statuses() + self.table.set_rows(rows) + self._decorate_rows() + self._render_ai_statuses() total = page_total(result, len(rows)) self.pager.update_state(requested_page, total) self.count_badge.setText(f"共 {total} 条") @@ -1743,23 +1770,23 @@ class PrescriptionsPage(QWidget): self.banner.clear() if rows and self.table.currentRow() < 0: self.table.selectRow(0) - self._selection_changed() - self._load_ai_statuses() + self._selection_changed() + self._load_ai_statuses() - def _decorate_rows(self) -> None: - """Apply the reference table's tags, checkbox, avatar, and row actions.""" - - sorting = self.table.isSortingEnabled() - self.table.setUpdatesEnabled(False) - self.table.setSortingEnabled(False) - try: - self._decorate_rows_locked() - finally: - self.table.setSortingEnabled(sorting) - self.table.setUpdatesEnabled(True) + def _decorate_rows(self) -> None: + """Apply the reference table's tags, checkbox, avatar, and row actions.""" + + sorting = self.table.isSortingEnabled() + self.table.setUpdatesEnabled(False) + self.table.setSortingEnabled(False) + try: + self._decorate_rows_locked() + finally: + self.table.setSortingEnabled(sorting) + self.table.setUpdatesEnabled(True) def _decorate_rows_locked(self) -> None: - action_width = max(self.table.columnWidth(2), 178 if self._ai_enabled else 144) + action_width = max(self.table.columnWidth(2), 178 if self._ai_enabled else 144) for row_index in range(self.table.rowCount()): selector = self.table.item(row_index, 0) if selector is None: @@ -1781,7 +1808,7 @@ class PrescriptionsPage(QWidget): sn_item = self.table.item(row_index, 1) if sn_item is not None: - sn_item.setForeground(QColor(PALETTE["heading"])) + sn_item.setForeground(QColor(PALETTE["heading"])) font = sn_item.font() font.setWeight(QFont.Weight.Normal) sn_item.setFont(font) @@ -1819,7 +1846,7 @@ class PrescriptionsPage(QWidget): actions.setContentsMargins(3, 0, 3, 0) actions.setSpacing(3) actions.addStretch(1) - if has_permission(self.permissions, "cf.prescription/read"): + if has_permission(self.permissions, "cf.prescription/read"): actions.addWidget( _row_action_button( "eye", @@ -1829,15 +1856,15 @@ class PrescriptionsPage(QWidget): ), actions_host, ) - ) - if self._ai_enabled and can_open_issued_ai(self.permissions) and not _is_blank_prescription(row): - actions.addWidget( - _row_action_button( - "eye", "AI 报告", - lambda _checked=False, target=row: self._run_row_action(target, self._open_ai_report), - actions_host, label="AI", - ) - ) + ) + if self._ai_enabled and can_open_issued_ai(self.permissions) and not _is_blank_prescription(row): + actions.addWidget( + _row_action_button( + "eye", "AI 报告", + lambda _checked=False, target=row: self._run_row_action(target, self._open_ai_report), + actions_host, label="AI", + ) + ) if self._can_upload(row): actions.addWidget( _row_action_button( @@ -1846,10 +1873,10 @@ class PrescriptionsPage(QWidget): actions_host, label="上传处方", mutation=True, ) ) - can_reissue = self._can_reissue(row) - can_change = _can_change_issued_prescription(row) - show_changes = can_change or not _voided(row) - if show_changes and has_permission(self.permissions, "cf.prescription/edit"): + can_reissue = self._can_reissue(row) + can_change = _can_change_issued_prescription(row) + show_changes = can_change or not _voided(row) + if show_changes and has_permission(self.permissions, "cf.prescription/edit"): actions.addWidget( _row_action_button( "pencil", @@ -1858,28 +1885,28 @@ class PrescriptionsPage(QWidget): target, self._edit_selected ), actions_host, - enabled=can_change, + enabled=can_change, label="编辑", mutation=True, ) ) - if self._can_void(row): - actions.addWidget( - _row_action_button( - "close", "作废处方", - lambda _checked=False, target=row: self._run_row_action(target, self._void_selected), - actions_host, danger=True, label="作废", mutation=True, - ) - ) - if can_reissue: - actions.addWidget( - _row_action_button( - "plus", "重新开方", - lambda _checked=False, target=row: self._run_row_action(target, self._reissue_selected), - actions_host, label="重新开方", mutation=True, - ) - ) - if show_changes and has_permission(self.permissions, "cf.prescription/del"): + if self._can_void(row): + actions.addWidget( + _row_action_button( + "close", "作废处方", + lambda _checked=False, target=row: self._run_row_action(target, self._void_selected), + actions_host, danger=True, label="作废", mutation=True, + ) + ) + if can_reissue: + actions.addWidget( + _row_action_button( + "plus", "重新开方", + lambda _checked=False, target=row: self._run_row_action(target, self._reissue_selected), + actions_host, label="重新开方", mutation=True, + ) + ) + if show_changes and has_permission(self.permissions, "cf.prescription/del"): actions.addWidget( _row_action_button( "trash", @@ -1889,244 +1916,244 @@ class PrescriptionsPage(QWidget): ), actions_host, danger=True, - enabled=can_change, + enabled=can_change, mutation=True, ) ) actions.addStretch(1) - action_width = max(action_width, actions.sizeHint().width() + 4) + action_width = max(action_width, actions.sizeHint().width() + 4) self.table.setCellWidget(row_index, 2, actions_host) - self.table.setColumnWidth(2, action_width) + self.table.setColumnWidth(2, action_width) self._sync_row_mutation_actions() - self.table.resizeRowsToContents() - - def _visible_ai_ids(self) -> list[int]: - if not self.isVisible() or not self.table.isVisible(): - return [] - ids = [] - viewport = self.table.viewport().rect() - for index in range(self.table.rowCount()): - item = self.table.item(index, 0) - # Column 0 may be horizontally off-screen; use row geometry only. - top = self.table.rowViewportPosition(index) - if item is None or top + self.table.rowHeight(index) <= 0 or top >= viewport.height(): - continue - row = item.data(Qt.ItemDataRole.UserRole) - if _is_blank_prescription(row): - continue - value = _int(first_value(row, "id", "prescription_id"), 0) - if value > 0: - ids.append(value) - return list(dict.fromkeys(ids))[:100] - - def _schedule_ai_statuses(self) -> None: - if self.isVisible(): - self._ai_scroll_timer.start() - - def _load_ai_statuses(self) -> None: - only_blank = self.table.rowCount() > 0 and all( - _is_blank_prescription(self.table.item(index, 0).data(Qt.ItemDataRole.UserRole)) - for index in range(self.table.rowCount()) - ) - self.ai_status_notice.setVisible(not only_blank) - if only_blank: - self._ai_timer.stop() - self._set_ai_columns(False) - return - method = getattr(self.repository, "list_prescription_ai_statuses", None) - if not has_permission(self.permissions, "tcm.prescriptionAi/statuses", default=False): - self._set_ai_columns(False) - self.ai_status_notice.setText("AI 分析:当前账号没有查看分析状态的权限,请联系管理员授权。") - return - if not callable(method): - self.ai_status_notice.setText("AI 分析:当前数据模式暂不支持此功能。") - return - if self._ai_pending: - return - ids = self._visible_ai_ids() - ids = [value for value in ids if value not in self._ai_statuses or batch_running(self._ai_statuses[value])] - if not ids: - self._ai_timer.stop() - if self.table.rowCount() == 0: - self.ai_status_notice.setText("AI 分析:当前列表没有处方,暂无可查看的分析结果。") - return - self._ai_pending = True - self._ai_request_token += 1 - token, generation = self._ai_request_token, self._generation - run_async( - lambda: method(ids), - on_success=lambda result: self._ai_statuses_ready(result, ids, token, generation), - on_error=lambda error: self._ai_statuses_error(error, token, generation), - on_finished=lambda: self._ai_statuses_finished(token), - ) - - def _ai_statuses_finished(self, token: int) -> None: - if token == self._ai_request_token: - self._ai_pending = False - - def _set_ai_columns(self, enabled: bool) -> None: - changed = enabled != self._ai_enabled - self._ai_enabled = enabled - for column in (11, 12): - self.table.setColumnHidden(column, not (enabled and self._agreement_visible)) - if enabled: - header = self.table.horizontalHeader() - header.moveSection(header.visualIndex(11), header.visualIndex(4) + 1) - header.moveSection(header.visualIndex(12), header.visualIndex(11) + 1) - self.table.setColumnWidth(11, 144) - self.table.setColumnWidth(12, 130) - if changed: - self._decorate_rows() - - def _set_agreement_visible(self, visible: bool) -> None: - self._agreement_visible = visible - for column in (11, 12): - self.table.setColumnHidden(column, not (self._ai_enabled and visible)) - self.ai_statistics_button.setVisible( - visible and has_permission(self.permissions, "tcm.prescriptionAi/statistics", default=False) - and callable(getattr(self.repository, "prescription_ai_statistics", None))) - if not visible: - self._ai_statuses = {key: agreement_safe_batch(row, False) for key, row in self._ai_statuses.items()} - for index in range(self.table.rowCount()): - item = self.table.item(index, 12) - if item is not None: - item.setText("") - item.setToolTip("") - item.setData(Qt.ItemDataRole.AccessibleTextRole, "") - - def _load_ai_capabilities(self) -> None: - self._ai_capability_token += 1 - token, generation = self._ai_capability_token, self._generation - self._ai_request_token += 1 - self._ai_pending = False - self._capability_agreement_visible = False - self._set_agreement_visible(False) - method = getattr(self.repository, "get_prescription_ai_capabilities", None) - self._ai_capability_pending = callable(method) - if not callable(method): - return - run_async(method, - on_success=lambda result: self._ai_capabilities_ready(result, token, generation), - on_error=lambda _error: self._ai_capabilities_ready({}, token, generation)) - - def _ai_capabilities_ready(self, result: Any, token: int, generation: int) -> None: - if token != self._ai_capability_token or generation != self._generation: - return - self._ai_capability_pending = False - self._capability_agreement_visible = _row_mapping(result).get("agreement_visible") is True - self._set_agreement_visible(self._capability_agreement_visible) - if self._capability_agreement_visible: - # A previous deny discarded scores, including completed cached batches. - # Fetch them again after a fresh grant rather than displaying that cache. - self._ai_statuses.clear() - if self.isVisible() and not self._loading: - self._load_ai_statuses() - - def _ai_statuses_ready(self, result: Any, ids: list[int], token: int, generation: int) -> None: - if token != self._ai_request_token or generation != self._generation or not self.isVisible(): - return - data = _row_mapping(result) - self._set_agreement_visible(self._capability_agreement_visible and data.get("agreement_visible") is True) - self._set_ai_columns(data.get("enabled") is True) - if not self._ai_enabled: - self._ai_timer.stop() - notice = "AI 分析未启用:暂不生成报告或一致度,请联系管理员启用。" - if can_open_issued_ai(self.permissions): - notice += "已有报告仍可从“AI 报告”查看。" - self.ai_status_notice.setText(notice) - self.ai_status_notice.setToolTip("") - self.ai_report_button.setToolTip("自动分析未启用;仍可查看已保存的历史报告。") - return - self.ai_status_notice.setText("AI 分析已启用:保存手工处方后自动生成两份报告。" - + ("可查看药味与剂量一致度。" if self._agreement_visible else "")) - self.ai_status_notice.setToolTip("") - self.ai_report_button.setToolTip("查看两份 AI 报告和候选处方。" - + ("可查看逐味对照。" if self._agreement_visible else "")) - for value in ids: - self._ai_statuses[value] = {} - for batch in data.get("items") or []: - value = _int(get_value(batch, "prescription_id"), 0) - if value in ids: - self._ai_statuses[value] = agreement_safe_batch(batch, self._agreement_visible and _row_mapping(batch).get("agreement_visible") is True) - self._render_ai_statuses() - if any(batch_running(self._ai_statuses.get(value)) for value in self._visible_ai_ids()): - self._ai_timer.start() - else: - self._ai_timer.stop() - - def _render_ai_statuses(self) -> None: - sorting = self.table.isSortingEnabled() - self.table.setSortingEnabled(False) - changed = False - try: - for index in range(self.table.rowCount()): - row = self.table.item(index, 0).data(Qt.ItemDataRole.UserRole) - value = _int(first_value(row, "id", "prescription_id"), 0) - batch = self._ai_statuses.get(value) - blank = _is_blank_prescription(row) - if batch is None and not blank: - continue - state = "" if blank else (state_text(batch) if batch else "尚无分析记录") - agreement = "" if blank or not self._agreement_visible else agreement_text(batch) - for column, text in ((11, state), (12, agreement)): - item = self.table.item(index, column) - if item.text() != text: - item.setText(text) - changed = True - item.setToolTip("" if blank or column == 12 and not self._agreement_visible else status_tooltip(batch)) - item.setData(Qt.ItemDataRole.AccessibleTextRole, text) - if changed: - self.table.resizeRowsToContents() - finally: - self.table.setSortingEnabled(sorting) - - def _ai_statuses_error(self, error: Exception, token: int, generation: int) -> None: - if token == self._ai_request_token and generation == self._generation: - self._ai_timer.stop() - self._set_agreement_visible(False) - self._set_ai_columns(False) - self.ai_status_notice.setText("AI 分析暂不可用:请稍后刷新;持续无法使用时,请联系管理员检查服务。") - self.ai_status_notice.setToolTip(friendly_error(error)) - self.ai_report_button.setToolTip("AI 状态暂不可用:" + friendly_error(error)) - - def _open_ai_report(self) -> None: - row = self._selected() - if _is_blank_prescription(row): - return - value = _int(first_value(row, "id", "prescription_id"), 0) - if value > 0: - present_issued_prescription_ai(self.repository, self.permissions, self, prescription_id=value) - - def _open_ai_context_menu(self, position: Any) -> None: - item = self.table.itemAt(position) - if item is None: - return - self.table.setCurrentItem(item) - row = self._selected() - menu = QMenu(self.table) - selected = self.table.copy_text.textCursor().selectedText() if self.table.copy_text.isVisible() else "" - if selected: - menu.addAction("复制选中文字", lambda: QApplication.clipboard().setText(selected.replace("\u2029", "\n"))) - text = self.table.cell_copy_text(self.table.indexFromItem(item)) - if text: - menu.addAction("复制单元格", lambda: QApplication.clipboard().setText(text)) - row_text = self.table.row_copy_text(item.row()) - menu.addAction("复制整行", lambda: QApplication.clipboard().setText(row_text)) - if (can_open_issued_ai(self.permissions) - and callable(getattr(self.repository, "list_prescription_ai_reports", None)) - and not _is_blank_prescription(row)): - menu.addSeparator() - action = menu.addAction("AI 报告 / 逐味对照" if self._agreement_visible else "AI 报告") - action.triggered.connect(lambda: self._run_row_action(row, self._open_ai_report)) - self._ai_context_menu = menu - menu.popup(self.table.viewport().mapToGlobal(position)) - - def _open_ai_statistics(self) -> None: - if not self._agreement_visible or not has_permission(self.permissions, "tcm.prescriptionAi/statistics", default=False): - return - dialog = PrescriptionAiStatisticsDialog(self.repository, self.permissions, self) - dialog.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True) - dialog.show() + self.table.resizeRowsToContents() + + def _visible_ai_ids(self) -> list[int]: + if not self.isVisible() or not self.table.isVisible(): + return [] + ids = [] + viewport = self.table.viewport().rect() + for index in range(self.table.rowCount()): + item = self.table.item(index, 0) + # Column 0 may be horizontally off-screen; use row geometry only. + top = self.table.rowViewportPosition(index) + if item is None or top + self.table.rowHeight(index) <= 0 or top >= viewport.height(): + continue + row = item.data(Qt.ItemDataRole.UserRole) + if _is_blank_prescription(row): + continue + value = _int(first_value(row, "id", "prescription_id"), 0) + if value > 0: + ids.append(value) + return list(dict.fromkeys(ids))[:100] + + def _schedule_ai_statuses(self) -> None: + if self.isVisible(): + self._ai_scroll_timer.start() + + def _load_ai_statuses(self) -> None: + only_blank = self.table.rowCount() > 0 and all( + _is_blank_prescription(self.table.item(index, 0).data(Qt.ItemDataRole.UserRole)) + for index in range(self.table.rowCount()) + ) + self.ai_status_notice.setVisible(not only_blank) + if only_blank: + self._ai_timer.stop() + self._set_ai_columns(False) + return + method = getattr(self.repository, "list_prescription_ai_statuses", None) + if not has_permission(self.permissions, "tcm.prescriptionAi/statuses", default=False): + self._set_ai_columns(False) + self.ai_status_notice.setText("AI 分析:当前账号没有查看分析状态的权限,请联系管理员授权。") + return + if not callable(method): + self.ai_status_notice.setText("AI 分析:当前数据模式暂不支持此功能。") + return + if self._ai_pending: + return + ids = self._visible_ai_ids() + ids = [value for value in ids if value not in self._ai_statuses or batch_running(self._ai_statuses[value])] + if not ids: + self._ai_timer.stop() + if self.table.rowCount() == 0: + self.ai_status_notice.setText("AI 分析:当前列表没有处方,暂无可查看的分析结果。") + return + self._ai_pending = True + self._ai_request_token += 1 + token, generation = self._ai_request_token, self._generation + run_async( + lambda: method(ids), + on_success=lambda result: self._ai_statuses_ready(result, ids, token, generation), + on_error=lambda error: self._ai_statuses_error(error, token, generation), + on_finished=lambda: self._ai_statuses_finished(token), + ) + + def _ai_statuses_finished(self, token: int) -> None: + if token == self._ai_request_token: + self._ai_pending = False + + def _set_ai_columns(self, enabled: bool) -> None: + changed = enabled != self._ai_enabled + self._ai_enabled = enabled + for column in (11, 12): + self.table.setColumnHidden(column, not (enabled and self._agreement_visible)) + if enabled: + header = self.table.horizontalHeader() + header.moveSection(header.visualIndex(11), header.visualIndex(4) + 1) + header.moveSection(header.visualIndex(12), header.visualIndex(11) + 1) + self.table.setColumnWidth(11, 144) + self.table.setColumnWidth(12, 130) + if changed: + self._decorate_rows() + + def _set_agreement_visible(self, visible: bool) -> None: + self._agreement_visible = visible + for column in (11, 12): + self.table.setColumnHidden(column, not (self._ai_enabled and visible)) + self.ai_statistics_button.setVisible( + visible and has_permission(self.permissions, "tcm.prescriptionAi/statistics", default=False) + and callable(getattr(self.repository, "prescription_ai_statistics", None))) + if not visible: + self._ai_statuses = {key: agreement_safe_batch(row, False) for key, row in self._ai_statuses.items()} + for index in range(self.table.rowCount()): + item = self.table.item(index, 12) + if item is not None: + item.setText("") + item.setToolTip("") + item.setData(Qt.ItemDataRole.AccessibleTextRole, "") + + def _load_ai_capabilities(self) -> None: + self._ai_capability_token += 1 + token, generation = self._ai_capability_token, self._generation + self._ai_request_token += 1 + self._ai_pending = False + self._capability_agreement_visible = False + self._set_agreement_visible(False) + method = getattr(self.repository, "get_prescription_ai_capabilities", None) + self._ai_capability_pending = callable(method) + if not callable(method): + return + run_async(method, + on_success=lambda result: self._ai_capabilities_ready(result, token, generation), + on_error=lambda _error: self._ai_capabilities_ready({}, token, generation)) + + def _ai_capabilities_ready(self, result: Any, token: int, generation: int) -> None: + if token != self._ai_capability_token or generation != self._generation: + return + self._ai_capability_pending = False + self._capability_agreement_visible = _row_mapping(result).get("agreement_visible") is True + self._set_agreement_visible(self._capability_agreement_visible) + if self._capability_agreement_visible: + # A previous deny discarded scores, including completed cached batches. + # Fetch them again after a fresh grant rather than displaying that cache. + self._ai_statuses.clear() + if self.isVisible() and not self._loading: + self._load_ai_statuses() + + def _ai_statuses_ready(self, result: Any, ids: list[int], token: int, generation: int) -> None: + if token != self._ai_request_token or generation != self._generation or not self.isVisible(): + return + data = _row_mapping(result) + self._set_agreement_visible(self._capability_agreement_visible and data.get("agreement_visible") is True) + self._set_ai_columns(data.get("enabled") is True) + if not self._ai_enabled: + self._ai_timer.stop() + notice = "AI 分析未启用:暂不生成报告或一致度,请联系管理员启用。" + if can_open_issued_ai(self.permissions): + notice += "已有报告仍可从“AI 报告”查看。" + self.ai_status_notice.setText(notice) + self.ai_status_notice.setToolTip("") + self.ai_report_button.setToolTip("自动分析未启用;仍可查看已保存的历史报告。") + return + self.ai_status_notice.setText("AI 分析已启用:保存手工处方后自动生成两份报告。" + + ("可查看药味与剂量一致度。" if self._agreement_visible else "")) + self.ai_status_notice.setToolTip("") + self.ai_report_button.setToolTip("查看两份 AI 报告和候选处方。" + + ("可查看逐味对照。" if self._agreement_visible else "")) + for value in ids: + self._ai_statuses[value] = {} + for batch in data.get("items") or []: + value = _int(get_value(batch, "prescription_id"), 0) + if value in ids: + self._ai_statuses[value] = agreement_safe_batch(batch, self._agreement_visible and _row_mapping(batch).get("agreement_visible") is True) + self._render_ai_statuses() + if any(batch_running(self._ai_statuses.get(value)) for value in self._visible_ai_ids()): + self._ai_timer.start() + else: + self._ai_timer.stop() + + def _render_ai_statuses(self) -> None: + sorting = self.table.isSortingEnabled() + self.table.setSortingEnabled(False) + changed = False + try: + for index in range(self.table.rowCount()): + row = self.table.item(index, 0).data(Qt.ItemDataRole.UserRole) + value = _int(first_value(row, "id", "prescription_id"), 0) + batch = self._ai_statuses.get(value) + blank = _is_blank_prescription(row) + if batch is None and not blank: + continue + state = "" if blank else (state_text(batch) if batch else "尚无分析记录") + agreement = "" if blank or not self._agreement_visible else agreement_text(batch) + for column, text in ((11, state), (12, agreement)): + item = self.table.item(index, column) + if item.text() != text: + item.setText(text) + changed = True + item.setToolTip("" if blank or column == 12 and not self._agreement_visible else status_tooltip(batch)) + item.setData(Qt.ItemDataRole.AccessibleTextRole, text) + if changed: + self.table.resizeRowsToContents() + finally: + self.table.setSortingEnabled(sorting) + + def _ai_statuses_error(self, error: Exception, token: int, generation: int) -> None: + if token == self._ai_request_token and generation == self._generation: + self._ai_timer.stop() + self._set_agreement_visible(False) + self._set_ai_columns(False) + self.ai_status_notice.setText("AI 分析暂不可用:请稍后刷新;持续无法使用时,请联系管理员检查服务。") + self.ai_status_notice.setToolTip(friendly_error(error)) + self.ai_report_button.setToolTip("AI 状态暂不可用:" + friendly_error(error)) + + def _open_ai_report(self) -> None: + row = self._selected() + if _is_blank_prescription(row): + return + value = _int(first_value(row, "id", "prescription_id"), 0) + if value > 0: + present_issued_prescription_ai(self.repository, self.permissions, self, prescription_id=value) + + def _open_ai_context_menu(self, position: Any) -> None: + item = self.table.itemAt(position) + if item is None: + return + self.table.setCurrentItem(item) + row = self._selected() + menu = QMenu(self.table) + selected = self.table.copy_text.textCursor().selectedText() if self.table.copy_text.isVisible() else "" + if selected: + menu.addAction("复制选中文字", lambda: QApplication.clipboard().setText(selected.replace("\u2029", "\n"))) + text = self.table.cell_copy_text(self.table.indexFromItem(item)) + if text: + menu.addAction("复制单元格", lambda: QApplication.clipboard().setText(text)) + row_text = self.table.row_copy_text(item.row()) + menu.addAction("复制整行", lambda: QApplication.clipboard().setText(row_text)) + if (can_open_issued_ai(self.permissions) + and callable(getattr(self.repository, "list_prescription_ai_reports", None)) + and not _is_blank_prescription(row)): + menu.addSeparator() + action = menu.addAction("AI 报告 / 逐味对照" if self._agreement_visible else "AI 报告") + action.triggered.connect(lambda: self._run_row_action(row, self._open_ai_report)) + self._ai_context_menu = menu + menu.popup(self.table.viewport().mapToGlobal(position)) + + def _open_ai_statistics(self) -> None: + if not self._agreement_visible or not has_permission(self.permissions, "tcm.prescriptionAi/statistics", default=False): + return + dialog = PrescriptionAiStatisticsDialog(self.repository, self.permissions, self) + dialog.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True) + dialog.show() def _run_row_action(self, row: Any, callback: Callable[[], None]) -> None: target_id = _int(first_value(row, "id", "prescription_id", default=None), 0) @@ -2161,43 +2188,43 @@ class PrescriptionsPage(QWidget): def _selection_changed(self) -> None: row = self.table.current_data() active = not self._mutation_pending - self.view_button.setEnabled(active and row is not None) - ai_available = ( - not _is_blank_prescription(row) - and can_open_issued_ai(self.permissions) - and callable(getattr(self.repository, "list_prescription_ai_reports", None)) - ) - self.ai_report_button.setVisible(ai_available) - self.ai_report_button.setEnabled(ai_available) + self.view_button.setEnabled(active and row is not None) + ai_available = ( + not _is_blank_prescription(row) + and can_open_issued_ai(self.permissions) + and callable(getattr(self.repository, "list_prescription_ai_reports", None)) + ) + self.ai_report_button.setVisible(ai_available) + self.ai_report_button.setEnabled(ai_available) self.patch_button.setEnabled(active and can_patch_patient(row)) self.create_order_button.setEnabled(active and can_create_order(row)) - can_change = _can_change_issued_prescription(row) - self.edit_button.setEnabled(active and can_change) - pending_audit = _is_pending_audit(row) + can_change = _can_change_issued_prescription(row) + self.edit_button.setEnabled(active and can_change) + pending_audit = _is_pending_audit(row) state = signature_state(row) can_sign = pending_audit and can_continue_prescription_esign(state, self.permissions, row) can_review = has_permission(self.permissions, "cf.prescription/audit") and can_audit(row) can_upload = self._can_upload(row) self.upload_button.setVisible(can_upload) self.upload_button.setEnabled(active and can_upload) - self.audit_button.setText("继续签署" if can_sign else "审核") + self.audit_button.setText("继续签署" if can_sign else "审核") self.audit_button.setVisible(can_sign or can_review) self.audit_button.setEnabled( active and not self._audit_check_pending and (can_sign or can_review) ) - can_void = self._can_void(row) - self.void_button.setVisible(can_void) - self.void_button.setEnabled(active and can_void) - can_reissue = self._can_reissue(row) - self.reissue_button.setVisible(can_reissue) - self.reissue_button.setEnabled(active and can_reissue) - self.delete_button.setEnabled(active and can_change) - - def _can_void(self, row: Any) -> bool: - return can_void_issued_prescription(row) - - def _can_reissue(self, row: Any) -> bool: - return can_reissue_prescription(row, self.current_user, self.permissions) + can_void = self._can_void(row) + self.void_button.setVisible(can_void) + self.void_button.setEnabled(active and can_void) + can_reissue = self._can_reissue(row) + self.reissue_button.setVisible(can_reissue) + self.reissue_button.setEnabled(active and can_reissue) + self.delete_button.setEnabled(active and can_change) + + def _can_void(self, row: Any) -> bool: + return can_void_issued_prescription(row) + + def _can_reissue(self, row: Any) -> bool: + return can_reissue_prescription(row, self.current_user, self.permissions) def _can_upload(self, row: Any) -> bool: return ( @@ -2274,10 +2301,10 @@ class PrescriptionsPage(QWidget): row = self._selected() if row is None or not has_permission(self.permissions, "cf.prescription/read"): return - was_signed = signature_state(row).get("status") == "signed" - self._load_detail(row, lambda detail: self._show_detail(detail, was_signed=was_signed)) + was_signed = signature_state(row).get("status") == "signed" + self._load_detail(row, lambda detail: self._show_detail(detail, was_signed=was_signed)) - def _show_detail(self, detail: Any, *, was_signed: bool = False) -> None: + def _show_detail(self, detail: Any, *, was_signed: bool = False) -> None: if not has_permission(self.permissions, "cf.prescription/read"): return dialog = PrescriptionDetailDialog( @@ -2293,7 +2320,7 @@ class PrescriptionsPage(QWidget): if review_submission_time(detail, dialog.esign) != submitted_at or ( not was_signed and dialog.esign.get("status") == "signed" ): - self.refresh() + self.refresh() def _open_diagnosis(self, diagnosis_id: int) -> None: if not has_permission(self.permissions, "tcm.diagnosis/readonlyDetail"): @@ -2347,60 +2374,60 @@ class PrescriptionsPage(QWidget): self.banner.show_message(friendly_error(error), "danger") def _add_prescription(self) -> None: - if has_permission(self.permissions, "cf.prescription/add"): - self._open_new_prescription() - - def _open_new_prescription(self, seed: dict[str, Any] | None = None) -> None: - if self._mutation_pending or not has_permission(self.permissions, PRESCRIBE_PERMISSIONS): + if has_permission(self.permissions, "cf.prescription/add"): + self._open_new_prescription() + + def _open_new_prescription(self, seed: dict[str, Any] | None = None) -> None: + if self._mutation_pending or not has_permission(self.permissions, PRESCRIBE_PERMISSIONS): return dialog = PrescriptionEditorDialog( self.repository, - seed, + seed, mode="add", current_user=self.current_user, - save_draft=lambda payload: self.repository.create_prescription(payload), + save_draft=lambda payload: self.repository.create_prescription(payload), parent=self, ) dialog.diagnosis_requested.connect(self._open_diagnosis) if dialog.exec() == QDialog.DialogCode.Accepted: - saved = getattr(dialog, "saved_draft", None) - if saved is not None: - self._prescription_saved(saved, "处方已新增并提交审核。") - else: - self._save_prescription(dialog.payload(), None) - - def _void_selected(self) -> None: - row = self._selected() - if self._mutation_pending or not self._can_void(row): - return - prescription_id = _int(first_value(row, "id", "prescription_id")) - if prescription_id <= 0: - self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning") - return - if not confirm_prescription_void(self, row): - return - self._set_mutation_pending(True) - run_async( - lambda: self.repository.void_prescription(prescription_id), - on_success=lambda _result: self._mutation_success("处方已作废。"), - on_error=self._mutation_error, - on_finished=lambda: self._set_mutation_pending(False), - ) - - def _reissue_selected(self) -> None: - row = self._selected() - if self._mutation_pending or not self._can_reissue(row): - return - self._load_detail( - row, lambda detail: self._open_reissue(merge_prescription_detail(row, detail)), - message="正在准备重新开方…", - ) - - def _open_reissue(self, detail: dict[str, Any]) -> None: - if not self._can_reissue(detail): - self.banner.show_message("该处方当前不可重新开方,请刷新列表后重试。", "warning") - return - self._open_new_prescription(reissue_prescription_seed(detail)) + saved = getattr(dialog, "saved_draft", None) + if saved is not None: + self._prescription_saved(saved, "处方已新增并提交审核。") + else: + self._save_prescription(dialog.payload(), None) + + def _void_selected(self) -> None: + row = self._selected() + if self._mutation_pending or not self._can_void(row): + return + prescription_id = _int(first_value(row, "id", "prescription_id")) + if prescription_id <= 0: + self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning") + return + if not confirm_prescription_void(self, row): + return + self._set_mutation_pending(True) + run_async( + lambda: self.repository.void_prescription(prescription_id), + on_success=lambda _result: self._mutation_success("处方已作废。"), + on_error=self._mutation_error, + on_finished=lambda: self._set_mutation_pending(False), + ) + + def _reissue_selected(self) -> None: + row = self._selected() + if self._mutation_pending or not self._can_reissue(row): + return + self._load_detail( + row, lambda detail: self._open_reissue(merge_prescription_detail(row, detail)), + message="正在准备重新开方…", + ) + + def _open_reissue(self, detail: dict[str, Any]) -> None: + if not self._can_reissue(detail): + self.banner.show_message("该处方当前不可重新开方,请刷新列表后重试。", "warning") + return + self._open_new_prescription(reissue_prescription_seed(detail)) def _edit_selected(self) -> None: row = self._selected() @@ -2408,7 +2435,7 @@ class PrescriptionsPage(QWidget): row is None or self._mutation_pending or not has_permission(self.permissions, "cf.prescription/edit") - or not _can_change_issued_prescription(row) + or not _can_change_issued_prescription(row) ): return self._load_detail( @@ -2418,32 +2445,32 @@ class PrescriptionsPage(QWidget): ) def _open_editor(self, detail: Any) -> None: - if not _can_change_issued_prescription(detail): + if not _can_change_issued_prescription(detail): self.banner.show_message("该处方状态已变化,当前不能编辑。", "warning") return - prescription_id = _int(first_value(detail, "id", "prescription_id"), 0) + prescription_id = _int(first_value(detail, "id", "prescription_id"), 0) dialog = PrescriptionEditorDialog( self.repository, detail, mode="edit", current_user=self.current_user, - save_draft=lambda payload: self.repository.update_prescription(prescription_id, changes=payload), + save_draft=lambda payload: self.repository.update_prescription(prescription_id, changes=payload), parent=self, ) dialog.diagnosis_requested.connect(self._open_diagnosis) if dialog.exec() == QDialog.DialogCode.Accepted: - saved = getattr(dialog, "saved_draft", None) - if saved is not None: - self._prescription_saved(saved, "处方已保存并重新进入待审核。") - else: - self._save_prescription(dialog.payload(), prescription_id) + saved = getattr(dialog, "saved_draft", None) + if saved is not None: + self._prescription_saved(saved, "处方已保存并重新进入待审核。") + else: + self._save_prescription(dialog.payload(), prescription_id) def _save_prescription( self, payload: dict[str, Any], prescription_id: int | None, ) -> None: - permission = "cf.prescription/edit" if prescription_id else PRESCRIBE_PERMISSIONS + permission = "cf.prescription/edit" if prescription_id else PRESCRIBE_PERMISSIONS if not has_permission(self.permissions, permission): return self._set_mutation_pending(True) @@ -2464,16 +2491,16 @@ class PrescriptionsPage(QWidget): message = "处方已新增并提交审核。" run_async( operation, - on_success=lambda result: self._prescription_saved(result, message), + on_success=lambda result: self._prescription_saved(result, message), on_error=self._mutation_error, on_finished=lambda: self._set_mutation_pending(False), ) - - def _prescription_saved(self, prescription: Any, fallback: str) -> None: - message, kind = saved_prescription_message(prescription, fallback) - self.banner.show_message(message, kind) - show_toast(self, message, kind, 3600) - if resume_saved_prescription(self.repository, prescription, self): + + def _prescription_saved(self, prescription: Any, fallback: str) -> None: + message, kind = saved_prescription_message(prescription, fallback) + self.banner.show_message(message, kind) + show_toast(self, message, kind, 3600) + if resume_saved_prescription(self.repository, prescription, self): self._mutation_success("医生签署已完成,等待药师审核。") else: self.refresh() @@ -2484,7 +2511,7 @@ class PrescriptionsPage(QWidget): row is None or self._mutation_pending or not has_permission(self.permissions, "cf.prescription/del") - or not _can_change_issued_prescription(row) + or not _can_change_issued_prescription(row) ): return answer = QMessageBox.warning( @@ -2557,79 +2584,79 @@ class PrescriptionsPage(QWidget): def _audit_selected(self) -> None: row = self._selected() - if self._mutation_pending or self._audit_check_pending or not _is_pending_audit(row): - return - can_review = has_permission(self.permissions, "cf.prescription/audit") + if self._mutation_pending or self._audit_check_pending or not _is_pending_audit(row): + return + can_review = has_permission(self.permissions, "cf.prescription/audit") local_state = signature_state(row) signing_action = can_continue_prescription_esign(local_state, self.permissions, row) if not (signing_action or (can_review and can_audit(row))): return - prescription_id = _int(first_value(row, "id", "prescription_id"), 0) - if prescription_id <= 0: - self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning") - return - status_method = getattr(self.repository, "get_prescription_esign_status", None) - if not callable(status_method): - self.banner.show_message("无法查询处方签署状态,请联系管理员。", "warning") + prescription_id = _int(first_value(row, "id", "prescription_id"), 0) + if prescription_id <= 0: + self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning") return - - def checked(state: dict[str, Any]) -> None: - selected = self._selected() - if ( - self._mutation_pending - or not _is_pending_audit(selected) - or _int(first_value(selected, "id", "prescription_id"), 0) != prescription_id - ): - return + status_method = getattr(self.repository, "get_prescription_esign_status", None) + if not callable(status_method): + self.banner.show_message("无法查询处方签署状态,请联系管理员。", "warning") + return + + def checked(state: dict[str, Any]) -> None: + selected = self._selected() + if ( + self._mutation_pending + or not _is_pending_audit(selected) + or _int(first_value(selected, "id", "prescription_id"), 0) != prescription_id + ): + return if can_continue_prescription_esign(state, self.permissions, selected): - draft = {**_row_mapping(selected), "id": prescription_id, "esign": state} - dialog = PrescriptionEsignDialog(self.repository, draft, parent=self) - dialog.exec() - if dialog.state.get("status") == "signed": + draft = {**_row_mapping(selected), "id": prescription_id, "esign": state} + dialog = PrescriptionEsignDialog(self.repository, draft, parent=self) + dialog.exec() + if dialog.state.get("status") == "signed": self._mutation_success("医生签署已完成,等待药师审核。") - return - status = state["status"] + return + status = state["status"] eligible_status = (state["required"] and status == "signed") or (not state["required"] and status == "legacy") if eligible_status and can_review_uploaded_prescription(selected, state): - if signing_action: - if status == "signed": + if signing_action: + if status == "signed": self._mutation_success("医生签署已完成,等待药师审核。") - else: - self.refresh() - elif can_review: + else: + self.refresh() + elif can_review: self._open_audit_dialog(selected, state) - return - if status == "voided": - message = "处方已作废,请刷新列表。" + return + if status == "voided": + message = "处方已作废,请刷新列表。" elif awaiting_prescription_upload(selected, state) or review_submission_time(selected, state) == 0: message = "请开方医生上传处方后再审核。" - elif _truthy(first_value(selected, "is_system_auto")): - message = "请开方医生编辑并补全系统占号处方,再完成电子签署。" - elif not state["enabled"]: - message = "审核前须完成电子签署。请联系管理员启用签署服务。" - elif status == "signing": - message = "处方正在电子签署,请稍后再审核。" - elif status == "uncertain": - message = "请开方医生核对处方签署结果,确认完成后再审核。" + elif _truthy(first_value(selected, "is_system_auto")): + message = "请开方医生编辑并补全系统占号处方,再完成电子签署。" + elif not state["enabled"]: + message = "审核前须完成电子签署。请联系管理员启用签署服务。" + elif status == "signing": + message = "处方正在电子签署,请稍后再审核。" + elif status == "uncertain": + message = "请开方医生核对处方签署结果,确认完成后再审核。" elif status == "signed": message = "医生签署尚未通过验签,请核对签署状态后再审核。" - else: - message = "请开方医生完成电子签署后再审核。" - self.banner.show_message(message, "warning") - - def finished() -> None: - self._audit_check_pending = False - self._selection_changed() - - self._audit_check_pending = True - self._selection_changed() - run_async( - lambda: esign_status(status_method(prescription_id)), - on_success=checked, - on_error=self._mutation_error, - on_finished=finished, - ) - + else: + message = "请开方医生完成电子签署后再审核。" + self.banner.show_message(message, "warning") + + def finished() -> None: + self._audit_check_pending = False + self._selection_changed() + + self._audit_check_pending = True + self._selection_changed() + run_async( + lambda: esign_status(status_method(prescription_id)), + on_success=checked, + on_error=self._mutation_error, + on_finished=finished, + ) + def _open_audit_dialog(self, row: Any, state: Mapping[str, Any]) -> None: allow_approval = state.get("review_required") is not True or bool(review_signature_time(state)) dialog = AuditPrescriptionDialog(row, self, allow_approval=allow_approval) @@ -2719,25 +2746,25 @@ class PrescriptionsPage(QWidget): self.banner.show_message(message, "danger") show_toast(self, message, "danger", 5000) - def showEvent(self, event: Any) -> None: + def showEvent(self, event: Any) -> None: super().showEvent(event) - if self.table.rowCount() == 0 and not self._loading: - self.refresh() - elif not self._loading: - self._load_ai_capabilities() - - def hideEvent(self, event: Any) -> None: - self._ai_timer.stop() - self._ai_scroll_timer.stop() - self._ai_request_token += 1 - self._ai_capability_token += 1 - self._ai_capability_pending = False - self._ai_pending = False - super().hideEvent(event) + if self.table.rowCount() == 0 and not self._loading: + self.refresh() + elif not self._loading: + self._load_ai_capabilities() + + def hideEvent(self, event: Any) -> None: + self._ai_timer.stop() + self._ai_scroll_timer.stop() + self._ai_request_token += 1 + self._ai_capability_token += 1 + self._ai_capability_pending = False + self._ai_pending = False + super().hideEvent(event) __all__ = [ - "InfiniteList", + "InfiniteList", "PrescriptionsPage", "can_audit", "can_create_order", diff --git a/app/src/doctor_workstation/ui/pages/reception.py b/app/src/doctor_workstation/ui/pages/reception.py index 07f4b31d5..3b1db4075 100755 --- a/app/src/doctor_workstation/ui/pages/reception.py +++ b/app/src/doctor_workstation/ui/pages/reception.py @@ -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 diff --git a/app/src/doctor_workstation/ui/shell_spatial.py b/app/src/doctor_workstation/ui/shell_spatial.py new file mode 100644 index 000000000..2e5876da6 --- /dev/null +++ b/app/src/doctor_workstation/ui/shell_spatial.py @@ -0,0 +1,1106 @@ +"""Zero-sidebar Spatial Clinical OS 3.0 shell inspired by Alveo × Serene.ai.""" + +from __future__ import annotations + +from collections.abc import Callable +from functools import wraps +from typing import Any + +from PySide6.QtCore import QPointF, QRectF, QSize, Qt, QTimer, Signal +from PySide6.QtGui import ( + QColor, + QFont, + QKeySequence, + QMouseEvent, + QPainter, + QPainterPath, + QPen, + QShortcut, +) +from PySide6.QtWidgets import ( + QApplication, + QButtonGroup, + QFrame, + QHBoxLayout, + QLabel, + QLineEdit, + QMainWindow, + QMenu, + QPushButton, + QStackedWidget, + QVBoxLayout, + QWidget, +) + +from . import icons, motion +from .chat_notifications import ( + CONSULTATION_COMPLETE, + PATIENT_OPENED_CHAT, + ChatNotification, + ChatNotificationCenter, +) +from .command_palette import CommandEntry, CommandPaletteDialog +from .dialogs.ai_consult import can_open_ai_consult, present_ai_consult +from .dialogs.ai_consult_picker import select_and_present_ai_consult +from .dialogs.diagnosis import DiagnosisDialog +from .dialogs.esign_doctor import EsignDoctorDialog +from .dialogs.local_audio_queue import LocalAudioQueueDialog +from .dialogs.prescription_esign import can_open_esign_doctor +from .reception_style import heading_family +from .shell import ( + _SHELL_MINIMUM_SIZE, + _bounded_initial_window_size, + _resolve_navigation, +) +from .state import PatientContextStore, PatientSnapshot +from .viewmodels import derive_cockpit_snapshot +from .visuals.aurora_sheet import CollapsibleObsidianSheet +from .widgets import EmptyState, first_value, get_value, has_permission, show_toast + +_SPATIAL_NAV_LABELS = { + "reception": "接诊总览", + "appointments": "门诊日程", + "patients": "在管患者", + "prescription_library": "处方智库", + "prescriptions": "已开处方", + "consultations": "诊单档案", +} + +_SPATIAL_HERO_TITLES = { + "reception": ("中医糖代谢专科 / 线上联合门诊 / 全息接诊单元", "全息辨证接诊舱"), + "appointments": ("中医糖代谢专科 / 门诊排班管理 / 号源队列", "门诊日程与号源流"), + "patients": ("中医糖代谢专科 / 慢病全周期管理 / 随访队列", "在管慢病患者档案"), + "prescription_library": ("中医糖代谢专科 / 经方与协定方库 / 辨证施治", "专科经方与协定智库"), + "prescriptions": ("中医糖代谢专科 / CA 双签流转 / 电子处方中心", "已开处方与药师审方"), + "consultations": ("中医糖代谢专科 / 望闻问切归档 / 病历检索", "全量四诊问诊档案"), +} + +_SPATIAL_NAV_PRIORITY = { + "reception": 0, + "appointments": 1, + "patients": 2, + "prescription_library": 3, + "prescriptions": 4, + "consultations": 5, +} + +SPATIAL_SHELL_QSS = """ +QWidget#SpatialTopHeader { + background: transparent; +} +QFrame#SpatialPillNavIsland { + background-color: #FFFFFF; + border: 1px solid #E1ECE8; + border-radius: 22px; +} +QPushButton#SpatialNavPill { + min-height: 36px; + max-height: 36px; + padding: 0 16px; + border: 0; + border-radius: 18px; + background-color: transparent; + color: #546A67; + font-size: 13px; + font-weight: 500; +} +QPushButton#SpatialNavPill:hover { + background-color: #EFF5F3; + color: #10201E; +} +QPushButton#SpatialNavPill:checked { + background-color: #111918; + color: #FFFFFF; + font-weight: 600; +} +QPushButton#SpatialAiNavPill { + min-height: 36px; + max-height: 36px; + padding: 0 15px; + border: 1px solid #DFEAE6; + border-radius: 18px; + background-color: #F7FAF9; + color: #14322E; + font-size: 13px; + font-weight: 600; +} +QPushButton#SpatialAiNavPill:hover { + background-color: #E4F3EE; + border-color: #9ED0C3; + color: #0E6F5C; +} +QPushButton#SpatialAiNavPill[activeSheet="true"] { + background-color: #0E6F5C; + border-color: #0E6F5C; + color: #FFFFFF; +} +QFrame#SpatialSearchCapsule { + background-color: #FFFFFF; + border: 1px solid #E1ECE8; + border-radius: 20px; +} +QFrame#SpatialSearchCapsule:focus-within { + border: 1px solid #0E6F5C; +} +QLineEdit#SpatialGlobalSearch { + background: transparent; + border: 0; + color: #132523; + font-size: 13px; + padding: 0 4px; +} +QPushButton#SpatialKbdBadge { + background-color: #F2F6F5; + color: #677E7A; + border: 1px solid #DFE9E6; + border-radius: 10px; + padding: 0 8px; + min-height: 22px; + max-height: 22px; + font-size: 11px; + font-weight: 600; +} +QPushButton#SpatialCircleButton { + min-width: 38px; + max-width: 38px; + min-height: 38px; + max-height: 38px; + border-radius: 19px; + background-color: #FFFFFF; + border: 1px solid #E1ECE8; + color: #2B403E; + padding: 0; +} +QPushButton#SpatialCircleButton:hover { + background-color: #EAF4F1; + border-color: #B9DCD3; +} +QPushButton#SpatialWindowControl { + min-width: 32px; + max-width: 32px; + min-height: 32px; + max-height: 32px; + border-radius: 16px; + background-color: transparent; + border: 0; + color: #536966; + font-size: 14px; +} +QPushButton#SpatialWindowControl:hover { + background-color: #E4ECE9; + color: #10201E; +} +QPushButton#SpatialWindowClose:hover { + background-color: #E0584C; + color: #FFFFFF; +} +QPushButton#SpatialDoctorCapsule { + min-height: 42px; + max-height: 42px; + padding: 0 14px 0 10px; + border-radius: 21px; + background-color: #FFFFFF; + border: 1px solid #E1ECE8; + color: #11201E; + font-size: 13px; + font-weight: 600; +} +QPushButton#SpatialDoctorCapsule:hover { + background-color: #F6FAF9; + border-color: #C3DAD4; +} +QFrame#SpatialPatientCapsule { + background-color: #FFFFFF; + border: 1px solid #E1ECE8; + border-radius: 24px; +} +QPushButton#SpatialSecondaryPill { + min-height: 42px; + max-height: 42px; + padding: 0 18px; + border-radius: 21px; + background-color: #FFFFFF; + border: 1px solid #DCE7E4; + color: #192D2B; + font-size: 13px; + font-weight: 600; +} +QPushButton#SpatialSecondaryPill:hover { + background-color: #EDF6F3; + border-color: #9BCBC0; + color: #0E6F5C; +} +QPushButton#SpatialPrimaryEmeraldPill { + min-height: 42px; + max-height: 42px; + padding: 0 20px; + border-radius: 21px; + background-color: #0E6F5C; + border: 0; + color: #FFFFFF; + font-size: 13px; + font-weight: 600; +} +QPushButton#SpatialPrimaryEmeraldPill:hover { + background-color: #0A5B4B; +} +QPushButton#SpatialPrimaryEmeraldPill:disabled { + background-color: #C9D9D5; + color: #FFFFFF; +} +""" + + +class _AlveoJadeEmblem(QWidget): + """Alveo × Zhenyangtang twin-meridian jade pill emblem.""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setFixedSize(36, 36) + + def paintEvent(self, _event: object) -> None: # noqa: N802 + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + rect = QRectF(1.0, 1.0, 34.0, 34.0) + bg = QPainterPath() + bg.addRoundedRect(rect, 17.0, 17.0) + painter.fillPath(bg, QColor("#0E6F5C")) + + # Twin rounded vertical jade-white pillars + subtle champagne gold dot + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor("#FFFFFF")) + painter.drawRoundedRect(QRectF(11.0, 10.0, 5.2, 16.0), 2.6, 2.6) + painter.drawRoundedRect(QRectF(19.8, 10.0, 5.2, 16.0), 2.6, 2.6) + painter.setBrush(QColor("#DFC793")) + painter.drawEllipse(QPointF(28.5, 9.5), 2.4, 2.4) + + +class _SpatialCanvas(QWidget): + """Rounded mist-celadon (#F1F5F3) window ground with native edge resize.""" + + _RESIZE_MARGIN = 7 + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setMouseTracking(True) + + def _edges(self, pos: QPointF) -> Qt.Edge: + m = self._RESIZE_MARGIN + w, h = self.width(), self.height() + edges = Qt.Edge(0) + if pos.x() <= m: + edges |= Qt.Edge.LeftEdge + elif pos.x() >= w - m: + edges |= Qt.Edge.RightEdge + if pos.y() <= m: + edges |= Qt.Edge.TopEdge + elif pos.y() >= h - m: + edges |= Qt.Edge.BottomEdge + return edges + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton and not self.window().isMaximized(): + edges = self._edges(event.position()) + handle = self.window().windowHandle() + if edges and handle is not None and handle.startSystemResize(edges): + event.accept() + return + super().mousePressEvent(event) + + def paintEvent(self, _event: object) -> None: # noqa: N802 + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + radius = 0.0 if self.window().isMaximized() else 20.0 + rect = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5) + path = QPainterPath() + path.addRoundedRect(rect, radius, radius) + painter.fillPath(path, QColor("#F1F5F3")) + if radius > 0: + painter.setPen(QPen(QColor("#DCE6E3"), 1.0)) + painter.drawPath(path) + + +class _DraggableHeaderBar(QWidget): + """Top capsule bar supporting native window dragging & double-click maximize.""" + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + child = self.childAt(event.position().toPoint()) + if child is None or isinstance(child, QLabel): + handle = self.window().windowHandle() + if handle is not None and handle.startSystemMove(): + event.accept() + return + super().mousePressEvent(event) + + def mouseDoubleClickEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + win = self.window() + if win.isMaximized(): + win.showNormal() + else: + win.showMaximized() + event.accept() + return + super().mouseDoubleClickEvent(event) + + +class SpatialShellWindow(QMainWindow): + """Zero-sidebar Clinical OS 3.0 application shell (Alveo × Serene.ai).""" + + logout_requested = Signal() + close_requested = Signal() + video_requested = Signal(dict) + page_changed = Signal(str) + update_check_requested = Signal() + + _LOADING_FLAGS = ("_loading", "_queue_loading", "_detail_loading") + + def __init__( + self, + repository: Any, + session: Any, + permissions: Any = None, + parent: QWidget | None = None, + ) -> None: + super().__init__(parent) + self.setProperty("doctorMainWindow", True) + self.setWindowTitle("甄养堂 · 临床智医工作站") + self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True) + self.setStyleSheet("QMainWindow { background: transparent; }\n" + SPATIAL_SHELL_QSS) + + self.repository = repository + self.login_payload = session + self.session = get_value(session, "session", None) or session + self.current_user = ( + get_value(session, "user", None) + or get_value(self.session, "user", None) + or get_value(session, "current_user", None) + or session + ) + if permissions is not None: + self.permissions = permissions + else: + session_permissions = get_value(self.session, "permissions", None) + self.permissions = ( + session_permissions + if session_permissions is not None + else get_value(self.current_user, "permissions", None) + ) + self._can_ai_assistant = can_open_ai_consult(self.permissions) + session_menu = get_value(self.session, "menu", None) + self.menu = session_menu if session_menu is not None else get_value(session, "menu", []) + self.demo_mode = bool( + get_value(session, "demo_mode", False) + or get_value(self.session, "metadata.demo", False) + or get_value(self.session, "metadata.demo_mode", False) + ) + + raw_nav = _resolve_navigation(self.menu, self.permissions, demo_mode=self.demo_mode) + self.navigation = sorted( + raw_nav, + key=lambda entry: _SPATIAL_NAV_PRIORITY.get(entry[0].key, 99), + ) + + self.patient_context_store = PatientContextStore(self) + self.patient_context_store.active_patient_changed.connect(self._on_patient_context_changed) + self.patient_context_store.bottom_sheet_mode_changed.connect(self._sync_ai_sheet_button) + + self.pages: dict[str, QWidget] = {} + self.nav_buttons: dict[str, QPushButton] = {} + self.page_titles: dict[int, str] = {} + self._active_page_key: str | None = None + self._activation_page: QWidget | None = None + self._activation_generation = 0 + self._activation_refreshed = False + self._online = True + self._local_audio_settings_dialog: LocalAudioQueueDialog | None = None + self._global_diagnosis_dialog: DiagnosisDialog | None = None + + self.chat_notifications = ChatNotificationCenter(repository, self) + self.chat_notifications.notification_activated.connect(self._open_chat_notification) + + self.setMinimumSize(_SHELL_MINIMUM_SIZE) + screen = self.screen() or QApplication.primaryScreen() + available_size = screen.availableGeometry().size() if screen is not None else None + self.resize(_bounded_initial_window_size(available_size)) + + canvas = _SpatialCanvas(self) + canvas.setObjectName("SpatialAppCanvas") + self.setCentralWidget(canvas) + + root = QVBoxLayout(canvas) + root.setContentsMargins(20, 14, 20, 14) + root.setSpacing(10) + + self.topbar = self._build_top_capsule_bar() + root.addWidget(self.topbar) + + self.sub_hero = self._build_context_sub_hero() + root.addWidget(self.sub_hero) + + self.stack = QStackedWidget(canvas) + self.stack.setObjectName("SpatialPageStack") + self.stack.setStyleSheet("QStackedWidget#SpatialPageStack { background: transparent; border: 0; }") + root.addWidget(self.stack, 1) + + # Serene.ai Pull-Up Deep Obsidian Aurora-Glass Bottom Sheet + self.ai_bottom_sheet = CollapsibleObsidianSheet(canvas) + self.ai_bottom_sheet.expanded_changed.connect(self._on_sheet_expanded_changed) + self.ai_bottom_sheet.open_ai_report_requested.connect(self._open_active_patient_ai_report) + self.ai_bottom_sheet.open_ai_consult_requested.connect(self._open_active_patient_ai_consult) + self.ai_bottom_sheet.model_selected.connect(self._on_sheet_model_selected) + self.ai_bottom_sheet.set_view_model(derive_cockpit_snapshot().aurora) + root.addWidget(self.ai_bottom_sheet) + + self._register_pages() + self._bind_shortcuts() + + def _build_top_capsule_bar(self) -> QWidget: + bar = _DraggableHeaderBar(self) + bar.setObjectName("SpatialTopHeader") + bar.setFixedHeight(52) + layout = QHBoxLayout(bar) + layout.setContentsMargins(2, 0, 2, 0) + layout.setSpacing(12) + + # Left Brand Mark (Alveo × Serene minimal geometric brand) + brand_wrap = QWidget(bar) + brand_row = QHBoxLayout(brand_wrap) + brand_row.setContentsMargins(0, 0, 4, 0) + brand_row.setSpacing(10) + self.brand_mark = _AlveoJadeEmblem(brand_wrap) + brand_row.addWidget(self.brand_mark) + + brand_text = QLabel("甄养堂", brand_wrap) + b_font = QFont(heading_family()) + b_font.setPixelSize(18) + b_font.setWeight(QFont.Weight.DemiBold) + brand_text.setFont(b_font) + brand_text.setStyleSheet("color: #0F1F1D; background: transparent;") + brand_row.addWidget(brand_text) + + brand_tag = QLabel("clinical.os", brand_wrap) + brand_tag.setStyleSheet("color: #7A908C; font-size: 13px; background: transparent;") + brand_row.addWidget(brand_tag) + layout.addWidget(brand_wrap) + + layout.addStretch(1) + + # Center Floating Pill Navigation Island (Zero-sidebar centerpiece!) + self.nav_island = QFrame(bar) + self.nav_island.setObjectName("SpatialPillNavIsland") + self.nav_island.setFixedHeight(44) + self.nav_layout = QHBoxLayout(self.nav_island) + self.nav_layout.setContentsMargins(4, 3, 4, 3) + self.nav_layout.setSpacing(3) + layout.addWidget(self.nav_island) + + # Separate AI Coach / Syndrome Lab Pill right beside or inside island + if self._can_ai_assistant: + self.ai_nav_button = QPushButton("AI 辨证师", self.nav_island) + self.ai_nav_button.setObjectName("SpatialAiNavPill") + self.ai_nav_button.setIcon(icons.icon("ai", "#0E6F5C", 15)) + self.ai_nav_button.setIconSize(QSize(15, 15)) + self.ai_nav_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.ai_nav_button.setToolTip("展开底部黑曜极光 AI 辨证舱(Ctrl+])") + self.ai_nav_button.clicked.connect(self.toggle_ai_bottom_sheet) + + layout.addStretch(1) + + # Right Global Search Capsule + Utility Circles + Doctor Identity Pill + Window Controls + self.search_capsule = QFrame(bar) + self.search_capsule.setObjectName("SpatialSearchCapsule") + self.search_capsule.setFixedSize(244, 40) + s_layout = QHBoxLayout(self.search_capsule) + s_layout.setContentsMargins(12, 0, 8, 0) + s_layout.setSpacing(6) + search_icon_lbl = QLabel(self.search_capsule) + search_icon_lbl.setPixmap(icons.icon("search", "#6C827E", 15).pixmap(15, 15)) + s_layout.addWidget(search_icon_lbl) + + self.global_search = QLineEdit(self.search_capsule) + self.global_search.setObjectName("SpatialGlobalSearch") + self.global_search.setPlaceholderText("搜索患者、诊单…") + self.global_search.setClearButtonEnabled(True) + self.global_search.returnPressed.connect(self._run_global_search) + s_layout.addWidget(self.global_search, 1) + + self.palette_badge = QPushButton("Ctrl+K", self.search_capsule) + self.palette_badge.setObjectName("SpatialKbdBadge") + self.palette_badge.setCursor(Qt.CursorShape.PointingHandCursor) + self.palette_badge.setToolTip("打开全局临床命令中枢(Ctrl+K)") + self.palette_badge.clicked.connect(self.open_command_palette) + s_layout.addWidget(self.palette_badge) + layout.addWidget(self.search_capsule) + + self.refresh_button = QPushButton(bar) + self.refresh_button.setObjectName("SpatialCircleButton") + self.refresh_button.setIcon(icons.icon("refresh", "#2B403E", 16)) + self.refresh_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.refresh_button.setToolTip("刷新当前视图(F5)") + self.refresh_button.clicked.connect(self.refresh_current_page) + layout.addWidget(self.refresh_button) + + self.notification_button = QPushButton(bar) + self.notification_button.setObjectName("SpatialCircleButton") + self.notification_button.setIcon(icons.icon("notification", "#2B403E", 16)) + self.notification_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.notification_button.setToolTip("系统会话与问诊通知") + self.notification_button.clicked.connect(self._show_chat_notification_summary) + layout.addWidget(self.notification_button) + + # Doctor Identity Pill (Alveo 'Dr. Lena Hart · Pulmonology') + doc_name = str( + first_value(self.current_user, "name", "real_name", "account", default="主任医师") + ).strip() + dept_name = str( + first_value(self.current_user, "department_name", "dept_name", default="糖代谢专科") + ).strip() + self.user_menu_button = QPushButton(f"{doc_name} · {dept_name}", bar) + self.user_menu_button.setObjectName("SpatialDoctorCapsule") + self.user_menu_button.setIcon(icons.icon("patients", "#0E6F5C", 16)) + self.user_menu_button.setCursor(Qt.CursorShape.PointingHandCursor) + self._build_user_menu() + layout.addWidget(self.user_menu_button) + + # Crisp window controls + self.minimize_button = QPushButton("—", bar) + self.minimize_button.setObjectName("SpatialWindowControl") + self.minimize_button.setToolTip("最小化") + self.minimize_button.clicked.connect(self.showMinimized) + layout.addWidget(self.minimize_button) + + self.maximize_button = QPushButton("□", bar) + self.maximize_button.setObjectName("SpatialWindowControl") + self.maximize_button.setToolTip("最大化 / 还原") + self.maximize_button.clicked.connect(self._toggle_maximize) + layout.addWidget(self.maximize_button) + + self.close_button = QPushButton("×", bar) + self.close_button.setObjectName("SpatialWindowControl") + self.close_button.setStyleSheet( + "QPushButton { min-width: 32px; max-width: 32px; min-height: 32px; max-height: 32px;" + " border-radius: 16px; border: 0; color: #536966; font-size: 16px; background: transparent; }" + "QPushButton:hover { background-color: #E0584C; color: #FFFFFF; }" + ) + self.close_button.setToolTip("关闭工作站") + self.close_button.clicked.connect(self.close) + layout.addWidget(self.close_button) + + return bar + + def _build_user_menu(self) -> None: + menu = QMenu(self.user_menu_button) + if self._can_ai_assistant: + act_ai = menu.addAction("AI 深度问诊工作台…") + act_ai.triggered.connect(self._open_global_ai_picker) + if can_open_esign_doctor(self.repository, self.permissions): + act_esign = menu.addAction("医生电子签署身份…") + act_esign.triggered.connect(self._open_esign_dialog) + act_audio = menu.addAction("本机录音上传队列…") + act_audio.triggered.connect(self._open_audio_queue_dialog) + act_cmd = menu.addAction("全局命令面板(Ctrl+K)") + act_cmd.triggered.connect(self.open_command_palette) + act_upd = menu.addAction("检查客户端更新") + act_upd.triggered.connect(self.update_check_requested.emit) + menu.addSeparator() + act_logout = menu.addAction("退出当前账号") + act_logout.triggered.connect(self.logout_requested.emit) + self.user_menu_button.setMenu(menu) + + def _build_context_sub_hero(self) -> QWidget: + """Build the Alveo Layer-2 Editorial Sub-Hero + Active Patient Context Pill.""" + + hero = QWidget(self) + hero.setObjectName("SpatialSubHero") + hero.setFixedHeight(64) + layout = QHBoxLayout(hero) + layout.setContentsMargins(4, 0, 4, 0) + layout.setSpacing(12) + + # Left: Specialty Breadcrumb + 28px Editorial Title + title_col = QVBoxLayout() + title_col.setContentsMargins(0, 0, 0, 0) + title_col.setSpacing(2) + self.breadcrumb_label = QLabel("中医糖代谢专科 / 线上联合门诊 / 全息接诊单元", hero) + self.breadcrumb_label.setStyleSheet("color: #768C88; font-size: 11px; background: transparent;") + title_col.addWidget(self.breadcrumb_label) + + self.hero_title_label = QLabel("全息辨证接诊舱", hero) + h_font = QFont(heading_family()) + h_font.setPixelSize(28) + h_font.setWeight(QFont.Weight.DemiBold) + self.hero_title_label.setFont(h_font) + self.hero_title_label.setStyleSheet("color: #0E1D1B; background: transparent;") + title_col.addWidget(self.hero_title_label) + layout.addLayout(title_col) + + layout.addStretch(1) + + # Right: Active Patient Floating Capsule (Alveo 'Margaret Osei · 71 yrs · COPD') + self.patient_capsule = QFrame(hero) + self.patient_capsule.setObjectName("SpatialPatientCapsule") + self.patient_capsule.setFixedHeight(48) + pc_layout = QHBoxLayout(self.patient_capsule) + pc_layout.setContentsMargins(8, 4, 16, 4) + pc_layout.setSpacing(10) + + self.patient_avatar_badge = QLabel("患", self.patient_capsule) + self.patient_avatar_badge.setFixedSize(34, 34) + self.patient_avatar_badge.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.patient_avatar_badge.setStyleSheet( + "background-color: #E2F3EE; color: #0E6F5C; border: 1px solid #DFC793;" + " border-radius: 17px; font-size: 14px; font-weight: 600;" + ) + pc_layout.addWidget(self.patient_avatar_badge) + + p_meta_col = QVBoxLayout() + p_meta_col.setContentsMargins(0, 0, 0, 0) + p_meta_col.setSpacing(1) + self.context_patient_name = QLabel("等待选择接诊患者", self.patient_capsule) + self.context_patient_name.setStyleSheet( + "color: #10201E; font-size: 13px; font-weight: 600; background: transparent;" + ) + p_meta_col.addWidget(self.context_patient_name) + + self.context_patient_sub = QLabel("点击今日门诊计划自动同步全站上下文", self.patient_capsule) + self.context_patient_sub.setStyleSheet( + "color: #6E8380; font-size: 11px; background: transparent;" + ) + p_meta_col.addWidget(self.context_patient_sub) + pc_layout.addLayout(p_meta_col) + layout.addWidget(self.patient_capsule) + + # [四诊病历] Secondary White Pill (Alveo 'Share report') + self.quick_chart_button = QPushButton("四诊病历", hero) + self.quick_chart_button.setObjectName("SpatialSecondaryPill") + self.quick_chart_button.setIcon(icons.icon("consultations", "#192D2B", 15)) + self.quick_chart_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.quick_chart_button.setEnabled(False) + self.quick_chart_button.clicked.connect(self._open_active_patient_diagnosis) + layout.addWidget(self.quick_chart_button) + + # [▷ 开启视频面诊] Primary Alveo Emerald Pill (Alveo 'Start ward round') + self.quick_video_button = QPushButton("▷ 开启视频面诊", hero) + self.quick_video_button.setObjectName("SpatialPrimaryEmeraldPill") + self.quick_video_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.quick_video_button.setEnabled(False) + self.quick_video_button.clicked.connect(self._trigger_active_patient_video) + layout.addWidget(self.quick_video_button) + + return hero + + def _register_pages(self) -> None: + self.nav_group = QButtonGroup(self) + self.nav_group.setExclusive(True) + first_button: QPushButton | None = None + + for item, fallback_title in self.navigation: + page = item.page_type( + self.repository, + permissions=self.permissions, + current_user=self.current_user, + parent=self.stack, + ) + self._install_activation_refresh_gate(page) + if hasattr(page, "set_patient_context_store"): + page.set_patient_context_store(self.patient_context_store) + else: + page.patient_context_store = self.patient_context_store # type: ignore[attr-defined] + if hasattr(page, "cockpit_snapshot_updated"): + page.cockpit_snapshot_updated.connect(self._on_cockpit_snapshot_updated) + if hasattr(page, "video_requested"): + page.video_requested.connect(lambda payload: self.video_requested.emit(payload)) + + index = self.stack.addWidget(page) + self.pages[item.key] = page + pill_title = _SPATIAL_NAV_LABELS.get(item.key, fallback_title) + self.page_titles[index] = pill_title + + btn = QPushButton(pill_title, self.nav_island) + btn.setObjectName("SpatialNavPill") + btn.setCheckable(True) + btn.setCursor(Qt.CursorShape.PointingHandCursor) + btn.clicked.connect( + lambda _checked=False, page_idx=index, key=item.key: self._navigate(page_idx, key) + ) + self.nav_group.addButton(btn, index) + self.nav_layout.addWidget(btn) + self.nav_buttons[item.key] = btn + if first_button is None: + first_button = btn + + if hasattr(self, "ai_nav_button"): + self.nav_layout.addWidget(self.ai_nav_button) + + if first_button is None: + denied = EmptyState("暂无可用工作区", "当前账号没有医生工作站页面权限,请联系管理员调整授权。") + idx = self.stack.addWidget(denied) + self.stack.setCurrentIndex(idx) + self.hero_title_label.setText("权限受限") + return + + # Default to 'reception' (接诊总览) when available so doctor lands in the Digital Twin Cockpit! + target_key = "reception" if "reception" in self.nav_buttons else next(iter(self.nav_buttons)) + self.navigate(target_key) + + def _bind_shortcuts(self) -> None: + QShortcut(QKeySequence("Ctrl+K"), self, activated=self.open_command_palette) + QShortcut(QKeySequence("Ctrl+Shift+P"), self, activated=self.open_command_palette) + QShortcut(QKeySequence("F5"), self, activated=self.refresh_current_page) + QShortcut(QKeySequence("Ctrl+]"), self, activated=self.toggle_ai_bottom_sheet) + for idx, (item, _title) in enumerate(self.navigation[:6], start=1): + QShortcut( + QKeySequence(f"Alt+{idx}"), + self, + activated=lambda key=item.key: self.navigate(key), + ) + + def _install_activation_refresh_gate(self, page: QWidget) -> None: + refresh = getattr(page, "refresh", None) + if not callable(refresh): + return + + @wraps(refresh) + def activation_refresh(*args: Any, **kwargs: Any) -> Any: + if page is self._activation_page: + if self._activation_refreshed: + return None + self._activation_refreshed = True + return refresh(*args, **kwargs) + + page.refresh = activation_refresh # type: ignore[attr-defined,method-assign] + + def _ensure_activation_refresh(self, page: QWidget, generation: int) -> None: + if generation != self._activation_generation or page is not self._activation_page: + return + if not self._activation_refreshed: + refresh = getattr(page, "refresh", None) + if callable(refresh): + refresh() + + def _finish_activation(self, page: QWidget, generation: int) -> None: + if generation != self._activation_generation or page is not self._activation_page: + return + self._ensure_activation_refresh(page, generation) + self._activation_page = None + + def _navigate( + self, + index: int, + key: str, + *, + on_activate: Callable[[], None] | None = None, + ) -> None: + if index < 0 or index >= self.stack.count(): + return + page = self.stack.widget(index) + if page is None: + return + if self._active_page_key == key and self.stack.currentWidget() is page: + if on_activate is not None: + self._activation_refreshed = False + on_activate() + return + self._activation_generation += 1 + gen = self._activation_generation + self._activation_page = page + self._activation_refreshed = False + if on_activate is not None: + on_activate() + motion.switch_stack(self.stack, index) + btn = self.nav_buttons.get(key) + if btn is not None: + btn.setChecked(True) + crumb, hero_title = _SPATIAL_HERO_TITLES.get( + key, + ("中医糖代谢专科 / 临床智能工作台", self.page_titles.get(index, "临床工作站")), + ) + self.breadcrumb_label.setText(crumb) + self.hero_title_label.setText(hero_title) + self._active_page_key = key + self._ensure_activation_refresh(page, gen) + if self.isVisible(): + QTimer.singleShot(0, lambda p=page, g=gen: self._finish_activation(p, g)) + self.page_changed.emit(key) + + def navigate(self, key: str) -> bool: + btn = self.nav_buttons.get(key) + page = self.pages.get(key) + if btn is None or page is None: + return False + self._navigate(self.stack.indexOf(page), key) + return True + + def refresh_current_page(self) -> None: + page = self.stack.currentWidget() + refresh = getattr(page, "refresh", None) + if callable(refresh): + refresh() + + def toggle_ai_bottom_sheet(self) -> None: + self.ai_bottom_sheet.toggle_expanded() + + def _on_sheet_expanded_changed(self, expanded: bool) -> None: + self.patient_context_store.set_bottom_sheet_expanded(expanded) + self._sync_ai_sheet_button(expanded) + + def _sync_ai_sheet_button(self, expanded: bool) -> None: + if hasattr(self, "ai_nav_button"): + self.ai_nav_button.setProperty("activeSheet", expanded) + self.ai_nav_button.setIcon( + icons.icon("ai", "#FFFFFF" if expanded else "#0E6F5C", 15) + ) + self.ai_nav_button.style().unpolish(self.ai_nav_button) + self.ai_nav_button.style().polish(self.ai_nav_button) + if self.ai_bottom_sheet.is_expanded != expanded: + self.ai_bottom_sheet.set_expanded(expanded) + + def _on_cockpit_snapshot_updated(self, snapshot_vm: Any) -> None: + aurora = getattr(snapshot_vm, "aurora", None) + if aurora is not None: + self.ai_bottom_sheet.set_view_model(aurora) + + def _on_sheet_model_selected(self, model_key: str) -> None: + rec_page = self.pages.get("reception") + select_model = getattr(rec_page, "select_cockpit_ai_model", None) + if callable(select_model): + select_model(model_key) + + def _on_patient_context_changed(self, snapshot: PatientSnapshot) -> None: + if not snapshot or not snapshot.has_patient: + self.patient_avatar_badge.setText("患") + self.context_patient_name.setText("等待选择接诊患者") + self.context_patient_sub.setText("点击今日门诊计划自动同步全站上下文") + self.quick_chart_button.setEnabled(False) + self.quick_video_button.setEnabled(False) + return + self.patient_avatar_badge.setText(snapshot.patient_name[:1]) + self.context_patient_name.setText(f"{snapshot.patient_name} · {snapshot.status_text}") + self.context_patient_sub.setText(snapshot.subtitle_line) + self.quick_chart_button.setEnabled(snapshot.diagnosis_id > 0) + self.quick_video_button.setEnabled(snapshot.diagnosis_id > 0 or snapshot.appointment_id > 0) + + def _open_active_patient_diagnosis(self) -> None: + snap = self.patient_context_store.current_patient + if snap.diagnosis_id > 0: + self.open_diagnosis_by_id(snap.diagnosis_id, modeless=True) + + def _trigger_active_patient_video(self) -> None: + rec_page = self.pages.get("reception") + if rec_page is not None and getattr(rec_page, "_selected_appointment_id", None): + trigger = getattr(rec_page, "_request_video", None) + if callable(trigger): + trigger() + return + snap = self.patient_context_store.current_patient + if snap.diagnosis_id > 0: + self.video_requested.emit( + { + "patient_id": snap.patient_id or snap.diagnosis_id, + "diagnosis_id": snap.diagnosis_id, + "appointment_id": snap.appointment_id, + "patient_name": snap.patient_name, + "mode": "im", + "record": snap.raw_record, + } + ) + + def _open_active_patient_ai_report(self) -> None: + rec_page = self.pages.get("reception") + open_rep = getattr(rec_page, "_open_ai_analysis_dialog", None) + if callable(open_rep) and getattr(rec_page, "_selected_detail", None): + open_rep() + return + self._open_active_patient_ai_consult() + + def _open_active_patient_ai_consult(self) -> None: + snap = self.patient_context_store.current_patient + if snap.diagnosis_id > 0 and self._can_ai_assistant: + present_ai_consult( + self.repository, + diagnosis_id=snap.diagnosis_id, + patient_name=snap.patient_name, + permissions=self.permissions, + parent=self, + ) + return + self._open_global_ai_picker() + + def _open_global_ai_picker(self) -> None: + if not self._can_ai_assistant: + show_toast(self, "当前账号未开通 AI 辨证助手权限。", "warning") + return + select_and_present_ai_consult(self.repository, self.permissions, self) + + def _open_esign_dialog(self) -> None: + dlg = EsignDoctorDialog(self.repository, parent=self) + dlg.exec() + dlg.deleteLater() + + def _open_audio_queue_dialog(self) -> None: + if self._local_audio_settings_dialog is None: + self._local_audio_settings_dialog = LocalAudioQueueDialog(self.repository, self) + self._local_audio_settings_dialog.show() + self._local_audio_settings_dialog.raise_() + self._local_audio_settings_dialog.activateWindow() + + def _run_global_search(self) -> None: + query = self.global_search.text().strip() + target_key = next( + (k for k in ("consultations", "patients") if k in self.pages), + None, + ) + if target_key is None: + show_toast(self, "当前账号没有可用的患者搜索页面。", "warning") + return + page = self.pages[target_key] + search_fn = getattr(page, "search_patient", None) + if callable(search_fn): + self._navigate( + self.stack.indexOf(page), + target_key, + on_activate=lambda: search_fn(query), + ) + + def open_command_palette(self) -> None: + entries: list[CommandEntry] = [] + for idx, (item, title) in enumerate(self.navigation, start=1): + label = _SPATIAL_NAV_LABELS.get(item.key, title) + entries.append( + CommandEntry( + key=f"nav:{item.key}", + title=f"前往 · {label}", + subtitle="切换顶部胶囊空间视图", + category="空间导航", + shortcut=f"Alt+{idx}" if idx <= 6 else "", + icon_kind=item.key, + callback=lambda k=item.key: self.navigate(k), + ) + ) + entries.append( + CommandEntry( + key="act:ai_sheet", + title="展开 / 收起黑曜极光 AI 辨证舱", + subtitle="查看三联极光毛玻璃循证卡与控糖节律仪表盘", + category="临床智医", + shortcut="Ctrl+]", + icon_kind="ai", + callback=self.toggle_ai_bottom_sheet, + ) + ) + entries.append( + CommandEntry( + key="act:refresh", + title="刷新当前临床视图数据", + subtitle="同步最新号源、四诊详情与 AI 报告", + category="工作台操作", + shortcut="F5", + icon_kind="refresh", + callback=self.refresh_current_page, + ) + ) + snap = self.patient_context_store.current_patient + if snap.has_patient and snap.diagnosis_id > 0: + entries.append( + CommandEntry( + key="act:diag", + title=f"打开四诊病历 · {snap.patient_name}", + subtitle=snap.subtitle_line, + category="当前患者", + shortcut="", + icon_kind="consultations", + callback=self._open_active_patient_diagnosis, + ) + ) + dlg = CommandPaletteDialog(entries, self) + dlg.exec() + + def _toggle_maximize(self) -> None: + if self.isMaximized(): + self.showNormal() + else: + self.showMaximized() + + def _ensure_global_diagnosis_dialog(self) -> DiagnosisDialog: + dialog = self._global_diagnosis_dialog + if dialog is None: + dialog = DiagnosisDialog(self.repository, self, permissions=self.permissions) + dialog.saved.connect(self.refresh_current_page) + self._global_diagnosis_dialog = dialog + else: + dialog.refresh_permissions(self.permissions) + return dialog + + def open_diagnosis_by_id( + self, + diagnosis_id: Any, + *, + modeless: bool = False, + ) -> DiagnosisDialog | None: + try: + normalized_id = int(diagnosis_id) + except (TypeError, ValueError): + normalized_id = 0 + if normalized_id <= 0: + show_toast(self, "当前视频缺少有效诊单编号。", "warning", 3600) + return None + + if has_permission(self.permissions, "tcm.diagnosis/edit", default=False): + dialog = self._ensure_global_diagnosis_dialog() + dialog.open_for(normalized_id, editable=True, modeless=modeless) + elif has_permission(self.permissions, "tcm.diagnosis/readonlyDetail", default=False): + dialog = self._ensure_global_diagnosis_dialog() + dialog.open_view_only(normalized_id, modeless=modeless) + else: + show_toast(self, "当前账号没有查看该诊单的权限。", "danger", 4200) + return None + + dialog.raise_() + dialog.activateWindow() + return dialog + + def _open_chat_notification(self, notification: ChatNotification) -> None: + if notification.kind == CONSULTATION_COMPLETE and notification.diagnosis_id > 0: + self.open_diagnosis_by_id(notification.diagnosis_id, modeless=True) + return + if notification.kind == PATIENT_OPENED_CHAT and self.navigate("reception"): + return + show_toast(self, notification.description, "info", 4200) + + def _show_chat_notification_summary(self) -> None: + pending = self.chat_notifications.pending + if not pending: + show_toast(self, "当前没有新的系统通知。", "info") + return + latest = pending[0] + show_toast( + self, + f"待处理通知 {len(pending)} 条,最新:{latest.title} · {latest.description}", + "info", + 4200, + ) + + def set_connection_state(self, online: bool, message: str = "") -> None: + self._online = online + tip = message or ("云端同步正常" if online else "云端连接中断") + self.refresh_button.setToolTip(f"刷新当前视图(F5) · {tip}") + + def showEvent(self, event: Any) -> None: # noqa: N802 + super().showEvent(event) + self.chat_notifications.start() + page = self.stack.currentWidget() + if page is not None and page is self._activation_page: + gen = self._activation_generation + QTimer.singleShot(0, lambda p=page, g=gen: self._finish_activation(p, g)) + + def closeEvent(self, event: Any) -> None: # noqa: N802 + self.chat_notifications.stop() + super().closeEvent(event) + if event.isAccepted(): + self.close_requested.emit() + + +__all__ = ["SpatialShellWindow"] diff --git a/app/src/doctor_workstation/ui/state/__init__.py b/app/src/doctor_workstation/ui/state/__init__.py new file mode 100644 index 000000000..c7f200a50 --- /dev/null +++ b/app/src/doctor_workstation/ui/state/__init__.py @@ -0,0 +1,5 @@ +"""Cross-page reactive state stores for Clinical OS 3.0.""" + +from .patient_context_store import PatientContextStore, PatientSnapshot + +__all__ = ["PatientContextStore", "PatientSnapshot"] diff --git a/app/src/doctor_workstation/ui/state/patient_context_store.py b/app/src/doctor_workstation/ui/state/patient_context_store.py new file mode 100644 index 000000000..a4e43bec4 --- /dev/null +++ b/app/src/doctor_workstation/ui/state/patient_context_store.py @@ -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) diff --git a/app/src/doctor_workstation/ui/viewmodels/__init__.py b/app/src/doctor_workstation/ui/viewmodels/__init__.py new file mode 100644 index 000000000..70c27d8b4 --- /dev/null +++ b/app/src/doctor_workstation/ui/viewmodels/__init__.py @@ -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", +] diff --git a/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py b/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py new file mode 100644 index 000000000..04ea25aad --- /dev/null +++ b/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py @@ -0,0 +1,1350 @@ +"""100% real-data clinical view-model derivation for Zhenyangtang Clinical OS 3.0. + +Strict Clinical Integrity Policy: +- NEVER invent, hash-seed, or fabricate glucose values, percentages, TIR, heart rates, + day numbers, or AI confidence scores. +- Every number, bar, anatomical callout, 21-day check-in cell, and AI card is derived + strictly from authoritative backend payloads (`appointment`, `patient`, `diagnosis`, + `daily_window`, `tracking_notes`, `doctor_notes`, `prescriptions`, `ai_payload`). +- Missing or unrecorded clinical fields are honestly represented as `未记录` / `待选择患者`. +""" + +from __future__ import annotations + +import math +import re +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import date, timedelta +from typing import Any + +from ..widgets import display_text, first_value + +_EXACT_FLOAT_RE = re.compile(r"^\s*([+]?\d+(?:\.\d+)?)\s*(?:mmol/l|mmhg|%|kg|cm)?\s*$", re.IGNORECASE) +MODEL_LABELS = {"qwen": "千问", "openai": "OpenAI", "doubao": "豆包"} + + +def _parse_positive_float(value: Any) -> float | None: + """Parse an exact numeric clinical measurement; return None for 0, empty, or free-text ranges.""" + + if value in (None, "", "—", "-", 0, "0", "0.0", "0.00"): + return None + if isinstance(value, bool): + return None + if isinstance(value, (int, float)): + num = float(value) + return num if math.isfinite(num) and num > 0 else None + text = str(value).strip() + if any(sep in text for sep in ("至", "~", "~", "到", "/")): + return None + match = _EXACT_FLOAT_RE.match(text) + if not match: + return None + try: + num = float(match.group(1)) + except ValueError: + return None + return num if math.isfinite(num) and num > 0 else None + + +def _clean_text(raw: Any) -> str: + if raw in (None, "", [], {}, ()): + return "" + if isinstance(raw, (list, tuple, set)): + parts = [_clean_text(item) for item in raw] + joined = "、".join(p for p in parts if p) + return "" if joined in {"—", "-"} else joined + text = display_text(raw, "").strip() + return "" if text in {"—", "-", "None", "null"} else text + + +def _clip(text: str, limit: int = 32) -> str: + clean = " ".join(text.split()) + if len(clean) <= limit: + return clean + return f"{clean[: limit - 1]}…" + + +def _is_normal_or_negated(text: str) -> bool: + if not text: + return True + norm = text.strip().lower() + if norm in {"正常", "无", "否", "未见异常", "无异常", "平", "尚可", "良好", "规律", "无特殊", "none", "no"}: + return True + return norm.startswith(("无", "否认", "未见", "未发现")) + + +@dataclass(frozen=True) +class ProgressionPoint: + label: str + ratio: float + recorded: bool = False + highlight: bool = False + alert: bool = False + value_hint: str = "" + + +@dataclass(frozen=True) +class GlycemicProgressionVM: + title: str + subtitle_badge: str + primary_value: str + unit: str + delta_badge: str + delta_tone: str # "emerald" | "coral" | "neutral" + delta_caption: str + target_label: str + target_ratio: float + bars: tuple[ProgressionPoint, ...] + left_foot: str + right_foot: str + + +@dataclass(frozen=True) +class DiurnalSlot: + time_label: str + height_ratio: float + state: str # "empty" | "normal" | "mint" | "alert" + tooltip: str = "" + + +@dataclass(frozen=True) +class VitalMiniBrick: + icon_kind: str + label: str + value: str + unit: str + tooltip: str = "" + alert: bool = False + + +@dataclass(frozen=True) +class DiurnalStabilityVM: + title: str + mode_badge: str + primary_value: str + unit: str + caption: str + has_marker: bool + range_marker_ratio: float + range_min_text: str + range_target_text: str + range_max_text: str + overnight_title: str + overnight_peak_hint: str + slots: tuple[DiurnalSlot, ...] + vitals: tuple[VitalMiniBrick, ...] + + +@dataclass(frozen=True) +class TwinCalloutNode: + locus_id: str + side: str # "left" | "right" + anchor_x: float + anchor_y: float + card_y: float + status_text: str + status_tone: str # "emerald" | "coral" | "gold" | "neutral" + title: str + detail: str + full_tooltip: str = "" + + +@dataclass(frozen=True) +class SyndromeTwinVM: + has_patient: bool + mode_key: str # "sanjiao" | "organ" | "tcm" + scan_badge: str + empty_title: str + empty_subtitle: str + nodes: tuple[TwinCalloutNode, ...] + bottom_capsule_title: str + bottom_capsule_text: str + recorded_Zone_flags: tuple[float, float, float, float] # head, chest_oral, abdomen, kidney_limb + + +@dataclass(frozen=True) +class JourneyDayCell: + day_num: int + date_iso: str + label_text: str + state: str # "completed" | "alert" | "stage" | "today" | "planned" + tooltip: str + has_dot: bool = False + + +@dataclass(frozen=True) +class JourneyPhaseSpan: + code: str + title: str + date_span: str + start_day: int + end_day: int + active: bool + + +@dataclass(frozen=True) +class CareJourneyVM: + title: str + plan_subtitle: str + primary_metric_text: str + total_unit_text: str + status_pill: str + status_tone: str # "emerald" | "coral" | "neutral" + end_capsule_text: str + phases: tuple[JourneyPhaseSpan, ...] + days: tuple[JourneyDayCell, ...] + milestones: tuple[tuple[int, str], ...] + + +@dataclass(frozen=True) +class AuroraCardVM: + kind: str # "diagnosis" | "treatment" | "risks" + tint: str # "cyan" | "olive" | "amber" + title: str + subtitle: str + badge_text: str + body_text: str + risk_items: tuple[tuple[str, str], ...] # (level, label) + foot_left: str + foot_right: str + + +@dataclass(frozen=True) +class ObsidianAuroraVM: + has_patient: bool + program_title: str + ai_summary_line: str + active_model_key: str + active_model_label: str + params: tuple[tuple[str, str], ...] + cards: tuple[AuroraCardVM, ...] + gauge_value: str + gauge_unit: str + gauge_caption: str + gauge_ratio: float + gauge_tooltip: str + + +@dataclass(frozen=True) +class CockpitSnapshotVM: + has_patient: bool + patient_name: str + progression: GlycemicProgressionVM + diurnal: DiurnalStabilityVM + twin_sanjiao: SyndromeTwinVM + twin_organ: SyndromeTwinVM + twin_tcm: SyndromeTwinVM + journey: CareJourneyVM + aurora: ObsidianAuroraVM + + def twin_for_mode(self, mode_key: str) -> SyndromeTwinVM: + if mode_key == "organ": + return self.twin_organ + if mode_key == "tcm": + return self.twin_tcm + return self.twin_sanjiao + + +def _build_empty_snapshot(active_ai_model: str = "qwen") -> CockpitSnapshotVM: + """Return an honest, zero-fake-metric empty state when no patient is selected.""" + + model_label = MODEL_LABELS.get(active_ai_model, "千问") + today = date.today() + start_21 = today - timedelta(days=20) + empty_bars = tuple( + ProgressionPoint(label=f"#{i + 1}", ratio=0.18, recorded=False, value_hint="尚未选择患者") + for i in range(12) + ) + empty_slots = tuple( + DiurnalSlot( + time_label=(today - timedelta(days=13 - i)).strftime("%m-%d"), + height_ratio=0.18, + state="empty", + tooltip="尚未选择患者", + ) + for i in range(14) + ) + empty_days = tuple( + JourneyDayCell( + day_num=i + 1, + date_iso=(start_21 + timedelta(days=i)).isoformat(), + label_text=str((start_21 + timedelta(days=i)).day), + state="today" if i == 20 else "planned", + tooltip=f"{(start_21 + timedelta(days=i)).isoformat()} · 请先选择患者", + has_dot=False, + ) + for i in range(21) + ) + empty_twin = SyndromeTwinVM( + has_patient=False, + mode_key="sanjiao", + scan_badge="等待选择患者", + empty_title="尚未选择接诊患者", + empty_subtitle="请从右侧「门诊接诊队列」选择患者,或切换「近期挂号 / 在管诊单」载入真实病历、血糖打卡与处方数据", + nodes=(), + bottom_capsule_title="当前状态", + bottom_capsule_text="未加载患者诊单 · 右侧点击任意患者即可同步全站临床资料", + recorded_Zone_flags=(0.0, 0.0, 0.0, 0.0), + ) + return CockpitSnapshotVM( + has_patient=False, + patient_name="未选择患者", + progression=GlycemicProgressionVM( + title="空腹血糖记录", + subtitle_badge="控制参考 < 7.0", + primary_value="—", + unit="mmol/L", + delta_badge="待选患者", + delta_tone="neutral", + delta_caption="实测空腹血糖序列", + target_label="控制阈值 7.0 mmol/L", + target_ratio=7.0 / 16.0, + bars=empty_bars, + left_foot="最早记录", + right_foot="最近一次", + ), + diurnal=DiurnalStabilityVM( + title="餐后2h血糖与体征", + mode_badge="控制参考 < 11.1", + primary_value="—", + unit="mmol/L", + caption="选择患者后展示实测餐后血糖与血压", + has_marker=False, + range_marker_ratio=0.0, + range_min_text="4.4", + range_target_text="7.8 餐后参考", + range_max_text="11.1", + overnight_title="近 14 天日常健康打卡记录", + overnight_peak_hint="暂无患者数据", + slots=empty_slots, + vitals=( + VitalMiniBrick("activity", "血压 (高压/低压)", "—", "mmHg"), + VitalMiniBrick("patients", "身高体重 / BMI", "—", ""), + VitalMiniBrick("prescriptions", "现用西药 / 胰岛素", "—", ""), + ), + ), + twin_sanjiao=empty_twin, + twin_organ=SyndromeTwinVM(**{**empty_twin.__dict__, "mode_key": "organ"}), + twin_tcm=SyndromeTwinVM(**{**empty_twin.__dict__, "mode_key": "tcm"}), + journey=CareJourneyVM( + title="近 21 天健康打卡与复诊", + plan_subtitle="关联小程序自录血糖、饮食、运动与复诊药尽提醒", + primary_metric_text="—", + total_unit_text="/ 21 天有记录", + status_pill="待选患者", + status_tone="neutral", + end_capsule_text="复诊待查", + phases=( + JourneyPhaseSpan("W1", "前第 3 周", f"{start_21.strftime('%m-%d')}起", 1, 7, False), + JourneyPhaseSpan("W2", "前第 2 周", f"{(start_21 + timedelta(days=7)).strftime('%m-%d')}起", 8, 14, False), + JourneyPhaseSpan("W3", "最近 7 天", f"{(start_21 + timedelta(days=14)).strftime('%m-%d')}–今日", 15, 21, True), + ), + days=empty_days, + milestones=((1, start_21.strftime("%m-%d")), (11, (start_21 + timedelta(days=10)).strftime("%m-%d")), (21, "今日")), + ), + aurora=ObsidianAuroraVM( + has_patient=False, + program_title="AI 病历循证分析舱", + ai_summary_line="请先选择接诊患者,系统将自动读取该患者已保存的千问 / OpenAI / 豆包病历分析报告", + active_model_key=active_ai_model, + active_model_label=model_label, + params=( + ("当前模型", model_label), + ("报告状态", "待选患者"), + ("实采维度", "0 / 6 项"), + ), + cards=( + AuroraCardVM( + kind="diagnosis", + tint="cyan", + title="AI 辨证与病情分析", + subtitle=f"{model_label} · 依据实采病历生成", + badge_text="待加载", + body_text="选择患者后,此处直接显示服务端返回的「诊断建议(diagnosis_advice)」原文,绝不展示虚构评分。", + risk_items=(), + foot_left="数据来源:tcm.diagnosis/patientAiReports", + foot_right="实采循证", + ), + AuroraCardVM( + kind="treatment", + tint="olive", + title="AI 治法与用药复核", + subtitle=f"{model_label} · 治疗与随访建议", + badge_text="待加载", + body_text="选择患者后,此处直接显示服务端返回的「治疗建议(treatment_advice)」原文及中西药核对要点。", + risk_items=(), + foot_left="仅供临床辅助参考", + foot_right="医师审定", + ), + AuroraCardVM( + kind="risks", + tint="amber", + title="AI 临床风险分层", + subtitle=f"{model_label} · 风险与信息缺口提示", + badge_text="0 项", + body_text="选择患者后,此处逐条列出服务端识别的高/中/低风险提示(risk_assessment)。", + risk_items=(), + foot_left="风险提示列表", + foot_right="待加载", + ), + ), + gauge_value="0/6", + gauge_unit="维", + gauge_caption="病历实采完备度", + gauge_ratio=0.05, + gauge_tooltip="选择患者后统计:基础体征、血糖记录、全身问诊、既往用药、四诊备注、处方记录 6 大实采维度", + ), + ) + + +def derive_cockpit_snapshot( + appointment: Any = None, + patient: Any = None, + diagnosis: Any = None, + *, + daily_window: Any = None, + daily_records: Sequence[Any] = (), + tracking_notes: Sequence[Any] = (), + doctor_notes: Sequence[Any] = (), + prescriptions: Sequence[Any] = (), + ai_payload: Mapping[str, Any] | None = None, + ai_state: str = "empty", + ai_message: str = "", + active_ai_model: str = "qwen", +) -> CockpitSnapshotVM: + """Derive 100% real-data visual models from backend reception & diagnosis payloads.""" + + appt = appointment or {} + pat = patient or {} + diag = diagnosis or {} + + raw_name = _clean_text( + first_value( + appt, + "patient_name", + "name", + default=first_value( + diag, + "patient_name", + "name", + default=first_value(pat, "patient_name", "name", default=""), + ), + ) + ) + diag_id_val = first_value( + diag, "id", "diagnosis_id", default=first_value(appt, "diagnosis_id", "patient_id", default=0) + ) + appt_id_val = first_value(appt, "id", "appointment_id", default=0) + has_patient = bool(raw_name or diag_id_val or appt_id_val) + if not has_patient: + return _build_empty_snapshot(active_ai_model) + + patient_name = raw_name or "未命名患者" + model_label = MODEL_LABELS.get(active_ai_model, "千问") + + # ── Extract real daily records from `trackingWindow` ───────────────── + blood_rows: list[Any] = [] + diet_rows: list[Any] = [] + exercise_rows: list[Any] = [] + if isinstance(daily_window, Mapping): + blood_rows = list(daily_window.get("blood_records") or []) + diet_rows = list(daily_window.get("diet_records") or []) + exercise_rows = list(daily_window.get("exercise_records") or []) + if not blood_rows and daily_records: + blood_rows = list(daily_records) + + # Sort blood records chronologically (oldest -> newest) + def _rec_sort_key(row: Any) -> tuple[str, str]: + d_str = str(first_value(row, "record_date", "date", default="") or "")[:10] + t_str = str(first_value(row, "record_time", "time", default="") or "")[:8] + return (d_str, t_str) + + sorted_blood = sorted(blood_rows, key=_rec_sort_key) + + # ── 1. Left Top Card: REAL Fasting Blood Glucose (mmol/L) ──────────── + fasting_points: list[tuple[str, float, str]] = [] + diag_fasting_raw = first_value(diag, "fasting_blood_sugar", "fasting_glucose", default=None) + diag_fasting_num = _parse_positive_float(diag_fasting_raw) + diag_fasting_text = _clean_text(diag_fasting_raw) + diag_date_str = _clean_text( + first_value(diag, "diagnosis_date", default=first_value(appt, "appointment_date", default="")) + )[:10] + + for row in sorted_blood: + f_num = _parse_positive_float(first_value(row, "fasting_blood_sugar", "fasting_glucose", default=None)) + if f_num is not None: + r_date = str(first_value(row, "record_date", "date", default="") or "")[:10] + r_time = str(first_value(row, "record_time", default="") or "")[:5] + src_tag = "患者自录" if str(first_value(row, "source", default="0")) == "1" else "随访录入" + label_short = r_date[5:] if len(r_date) >= 10 else "记录" + tip = f"{r_date} {r_time} · 空腹血糖 {f_num:g} mmol/L({src_tag})".strip() + fasting_points.append((label_short, f_num, tip)) + + if not fasting_points and diag_fasting_num is not None: + lbl = diag_date_str[5:] if len(diag_date_str) >= 10 else "建档" + fasting_points.append((lbl, diag_fasting_num, f"病历建档空腹血糖:{diag_fasting_num:g} mmol/L")) + + # Build 12-slot chart: ONLY real points are filled; unrecorded slots stay empty! + recent_fasting = fasting_points[-12:] + scale_max = max([14.0, *(pt[1] * 1.12 for pt in recent_fasting)]) + bars: list[ProgressionPoint] = [] + pad_empty = 12 - len(recent_fasting) + for idx in range(pad_empty): + bars.append( + ProgressionPoint( + label="", + ratio=0.14, + recorded=False, + highlight=False, + alert=False, + value_hint="无更早空腹血糖打卡记录", + ) + ) + for idx, (lbl, val, tip) in enumerate(recent_fasting): + is_latest = idx == len(recent_fasting) - 1 + bars.append( + ProgressionPoint( + label=lbl, + ratio=max(0.18, min(0.96, val / scale_max)), + recorded=True, + highlight=is_latest, + alert=(val >= 7.0), + value_hint=tip, + ) + ) + + if recent_fasting: + latest_f = recent_fasting[-1][1] + f_primary = f"{latest_f:g}" + f_unit = "mmol/L" + is_high_f = latest_f >= 7.0 + f_badge = "偏高 ↑" if is_high_f else "达标" + f_tone = "coral" if is_high_f else "emerald" + if len(recent_fasting) >= 2: + first_f = recent_fasting[0][1] + diff = latest_f - first_f + sign = "+" if diff > 0 else "" + f_caption = f"共 {len(fasting_points)} 次 · 较首测 {sign}{diff:.1f}" + else: + f_caption = "病历实测基线值" + left_foot = recent_fasting[0][0] or "首测" + right_foot = f"最新 ({recent_fasting[-1][0]})" + elif diag_fasting_text: + f_primary = "有描述" + f_unit = "" + f_badge = "文本记录" + f_tone = "neutral" + f_caption = _clip(diag_fasting_text, 14) + left_foot = "无数值打卡" + right_foot = "见病历描述" + else: + f_primary = "未记录" + f_unit = "" + f_badge = "待补录" + f_tone = "neutral" + f_caption = "暂无空腹血糖数值" + left_foot = "近21天无记录" + right_foot = "可在日常记录新增" + + hba1c_num = _parse_positive_float(first_value(diag, "hba1c", "glycosylated_hemoglobin", default=None)) + top_sub_badge = f"糖化 {hba1c_num:g}%" if hba1c_num is not None else "参考 < 7.0 mmol/L" + + progression_vm = GlycemicProgressionVM( + title="空腹血糖监测", + subtitle_badge=top_sub_badge, + primary_value=f_primary, + unit=f_unit, + delta_badge=f_badge, + delta_tone=f_tone, + delta_caption=f_caption, + target_label="7.0 mmol/L 控制线", + target_ratio=min(0.88, 7.0 / scale_max), + bars=tuple(bars), + left_foot=left_foot, + right_foot=right_foot, + ) + + # ── 2. Left Bottom Card: REAL Postprandial 2h Glucose & Vitals ─────── + post_points: list[tuple[str, float, str]] = [] + other_points: list[tuple[str, float, str]] = [] + latest_bp_from_blood = "" + latest_west_med = "" + latest_insulin = "" + + for row in sorted_blood: + r_date = str(first_value(row, "record_date", "date", default="") or "")[:10] + p_num = _parse_positive_float(first_value(row, "postprandial_blood_sugar", "postprandial_glucose", default=None)) + if p_num is not None: + post_points.append((r_date, p_num, f"{r_date} · 餐后2h血糖 {p_num:g} mmol/L")) + o_num = _parse_positive_float(first_value(row, "other_blood_sugar", default=None)) + if o_num is not None: + other_points.append((r_date, o_num, f"{r_date} · 随机/其他血糖 {o_num:g} mmol/L")) + sp = _parse_positive_float(first_value(row, "systolic_pressure", default=None)) + dp = _parse_positive_float(first_value(row, "diastolic_pressure", default=None)) + if sp is not None and dp is not None: + latest_bp_from_blood = f"{int(sp)}/{int(dp)}" + wm = _clean_text(first_value(row, "western_medicine", default="")) + if wm: + latest_west_med = wm + ins = _clean_text(first_value(row, "insulin", default="")) + if ins: + latest_insulin = ins + + diag_post_num = _parse_positive_float(first_value(diag, "postprandial_blood_sugar", default=None)) + if not post_points and diag_post_num is not None: + post_points.append((diag_date_str, diag_post_num, f"病历建档餐后血糖 {diag_post_num:g} mmol/L")) + + if post_points: + latest_p = post_points[-1][1] + p_primary = f"{latest_p:g}" + p_unit = "mmol/L" + p_high = latest_p >= 11.1 + p_badge = "餐后偏高 ↑" if p_high else "餐后达标" + p_caption = f"最近实测 ({post_points[-1][0][5:] or '建档'}) · 共 {len(post_points)} 次" + has_p_marker = True + p_marker_ratio = max(0.06, min(0.95, (latest_p - 4.4) / (13.0 - 4.4))) + elif other_points: + latest_o = other_points[-1][1] + p_primary = f"{latest_o:g}" + p_unit = "mmol/L" + p_badge = "其他时段血糖" + p_caption = f"最近随机血糖 ({other_points[-1][0][5:]}) · 未测餐后2h" + has_p_marker = True + p_marker_ratio = max(0.06, min(0.95, (latest_o - 4.4) / (13.0 - 4.4))) + else: + p_primary = "未记录" + p_unit = "" + p_badge = "参考 < 11.1" + p_caption = "暂无餐后2h血糖记录" + has_p_marker = False + p_marker_ratio = 0.0 + + # Build Real 14-Day Daily Check-in Strip (blood / diet / exercise / tracking) + today = date.today() + blood_by_date: dict[str, list[Any]] = {} + for r in sorted_blood: + k = str(first_value(r, "record_date", "date", default="") or "")[:10] + if k: + blood_by_date.setdefault(k, []).append(r) + diet_dates = { + str(first_value(r, "record_date", "date", default="") or "")[:10] + for r in diet_rows + if any(_clean_text(first_value(r, m, f"{m}_foods", default="")) for m in ("breakfast", "lunch", "dinner")) + } + exercise_by_date: dict[str, str] = {} + for r in exercise_rows: + k = str(first_value(r, "record_date", "date", default="") or "")[:10] + ex_t = _clean_text(first_value(r, "exercise_type", default="")) + dur = first_value(r, "duration", default=None) + if k and (ex_t or dur): + exercise_by_date[k] = f"{ex_t} {dur}分钟".strip() if dur else (ex_t or "已运动") + note_by_date: dict[str, str] = {} + for n in tracking_notes or (): + k = str(first_value(n, "note_date", "record_date", "create_time", default="") or "")[:10] + c = _clean_text(first_value(n, "content", "tracking_content", default="")) + if k and c: + note_by_date[k] = c + + slots_14: list[DiurnalSlot] = [] + high_days_14 = 0 + recorded_days_14 = 0 + for i in range(14): + d_obj = today - timedelta(days=13 - i) + d_iso = d_obj.isoformat() + b_list = blood_by_date.get(d_iso, []) + f_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "fasting_blood_sugar", default=None))) is not None] + p_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "postprandial_blood_sugar", default=None))) is not None] + has_diet = d_iso in diet_dates + ex_txt = exercise_by_date.get(d_iso, "") + tr_txt = note_by_date.get(d_iso, "") + + tip_parts = [d_iso] + if f_vals: + tip_parts.append(f"空腹 {f_vals[-1]:g}") + if p_vals: + tip_parts.append(f"餐后 {p_vals[-1]:g}") + if has_diet: + tip_parts.append("已记饮食") + if ex_txt: + tip_parts.append(ex_txt) + if tr_txt: + tip_parts.append(_clip(tr_txt, 16)) + + max_f = max(f_vals, default=0.0) + max_p = max(p_vals, default=0.0) + if max_f >= 7.0 or max_p >= 11.1: + high_days_14 += 1 + recorded_days_14 += 1 + peak_ratio = max(max_f / 14.0, max_p / 18.0) + slots_14.append( + DiurnalSlot(d_iso[5:], max(0.55, min(1.0, peak_ratio)), "alert", " · ".join(tip_parts)) + ) + elif f_vals or p_vals: + recorded_days_14 += 1 + norm_ratio = max(max_f / 14.0, max_p / 18.0, 0.48) + slots_14.append( + DiurnalSlot(d_iso[5:], min(0.85, norm_ratio), "mint", " · ".join(tip_parts)) + ) + elif has_diet or ex_txt or tr_txt: + recorded_days_14 += 1 + slots_14.append(DiurnalSlot(d_iso[5:], 0.42, "normal", " · ".join(tip_parts))) + else: + slots_14.append(DiurnalSlot(d_iso[5:], 0.16, "empty", f"{d_iso} · 当日无打卡记录")) + + # Real Vitals (BP, Height/Weight/BMI, Current Meds) + sys_num = _parse_positive_float( + first_value(diag, "systolic_pressure", "systolic", "high_pressure", default=first_value(pat, "systolic_pressure", default=None)) + ) + dia_num = _parse_positive_float( + first_value(diag, "diastolic_pressure", "diastolic", "low_pressure", default=first_value(pat, "diastolic_pressure", default=None)) + ) + if sys_num is not None and dia_num is not None: + bp_val = f"{int(sys_num)}/{int(dia_num)}" + bp_unit = "mmHg" + bp_alert = sys_num >= 140 or dia_num >= 90 + elif latest_bp_from_blood: + bp_val = latest_bp_from_blood + bp_unit = "mmHg" + bp_alert = False + else: + raw_bp = _clean_text(first_value(diag, "blood_pressure", default="")) + bp_val = raw_bp if raw_bp else "—" + bp_unit = "mmHg" if raw_bp and "mmhg" not in raw_bp.lower() else "" + bp_alert = False + + h_num = _parse_positive_float(first_value(diag, "height", default=first_value(pat, "height", default=None))) + w_num = _parse_positive_float(first_value(diag, "weight", default=first_value(pat, "weight", default=None))) + if h_num and h_num > 40 and w_num: + bmi = w_num / ((h_num / 100.0) ** 2) + hw_val = f"{bmi:.1f}" + hw_unit = f"BMI ({int(w_num)}kg)" + hw_tip = f"身高 {h_num:g} cm · 体重 {w_num:g} kg · BMI {bmi:.1f}" + hw_alert = bmi >= 24.0 or bmi < 18.5 + elif w_num: + hw_val = f"{w_num:g}" + hw_unit = "kg" + hw_tip = f"体重 {w_num:g} kg(身高未填)" + hw_alert = False + else: + hw_val = "—" + hw_unit = "" + hw_tip = "病历暂未录入身高体重" + hw_alert = False + + meds_full = _clean_text( + first_value( + diag, + "current_medications", + "current_medicine", + "current_medication", + default=latest_insulin or latest_west_med, + ) + ) + meds_short = _clip(meds_full, 7) if meds_full else "—" + + diurnal_vm = DiurnalStabilityVM( + title="餐后2h血糖与体征", + mode_badge=p_badge, + primary_value=p_primary, + unit=p_unit, + caption=p_caption, + has_marker=has_p_marker, + range_marker_ratio=p_marker_ratio, + range_min_text="4.4", + range_target_text="7.8 餐后参考", + range_max_text="11.1", + overnight_title="近 14 天日常打卡轨迹", + overnight_peak_hint=( + f"偏高 {high_days_14} 天 / 已记 {recorded_days_14} 天" + if recorded_days_14 > 0 + else "近 14 天暂无打卡记录" + ), + slots=tuple(slots_14), + vitals=( + VitalMiniBrick("activity", "血压 (高压/低压)", bp_val, bp_unit, f"实测血压:{bp_val} {bp_unit}".strip(), bp_alert), + VitalMiniBrick("patients", "体质量 BMI", hw_val, hw_unit, hw_tip, hw_alert), + VitalMiniBrick("prescriptions", "在用降糖药", meds_short, "", meds_full or "暂未录入在用药物", False), + ), + ) + + # ── 3. Center Stage: 100% Real Body Symptom & Clinical Case Map ────── + # Extract real symptom fields from `tcm_diagnosis` + head_txt = _clean_text(first_value(diag, "head_feeling_text", "head_feeling_desc", "head_feeling")) + eye_txt = _clean_text(first_value(diag, "eye_condition_text", "eye_condition_desc", "eye_condition")) + sleep_txt = _clean_text(first_value(diag, "sleep_condition_text", "sleep_condition_desc", "sleep_condition")) + + chief_txt = _clean_text(first_value(diag, "chief_complaint", "complaint", "symptoms")) + oral_txt = _clean_text(first_value(diag, "appetite_text", "appetite_desc", "appetite")) + water_txt = _clean_text(first_value(diag, "water_intake_text", "water_intake_desc", "water_intake")) + + diet_c_txt = _clean_text(first_value(diag, "diet_condition_text", "diet_condition_desc", "diet_condition")) + weight_c_txt = _clean_text(first_value(diag, "weight_change_text", "weight_change_desc", "weight_change")) + fatty_txt = _clean_text(first_value(diag, "fatty_liver_degree_text", "fatty_liver_degree_desc", "fatty_liver_degree")) + stool_txt = _clean_text(first_value(diag, "stool_condition_text", "stool_condition_desc", "stool_condition")) + + kidney_txt = _clean_text(first_value(diag, "kidney_condition_text", "kidney_condition_desc", "kidney_condition")) + urine_txt = _clean_text(first_value(diag, "urine_condition_text", "urine_condition_desc", "urine_condition")) + limb_txt = _clean_text(first_value(diag, "body_feeling_text", "body_feeling_desc", "body_feeling")) + sweat_skin_txt = ";".join( + p + for p in ( + _clean_text(first_value(diag, "sweat_condition_text", "sweat_condition")), + _clean_text(first_value(diag, "skin_condition_text", "skin_condition")), + ) + if p + ) + + def _zone_summary(items: Sequence[tuple[str, str]]) -> tuple[str, str, str, float]: + """Return (badge, tone, summary_line, heat_intensity) strictly from real fields.""" + present = [(lbl, val) for lbl, val in items if val] + if not present: + return ("未采集", "neutral", "病历暂未填写该部位问诊项", 0.0) + abnormal = [(lbl, val) for lbl, val in present if not _is_normal_or_negated(val)] + full = ";".join(f"{lbl}:{val}" for lbl, val in present) + if abnormal: + ab_line = " · ".join(f"{lbl}:{val}" for lbl, val in abnormal) + return ("阳性体征", "coral", ab_line, 0.85) + norm_line = " · ".join(f"{lbl}:{val}" for lbl, val in present) + return ("未见异常", "emerald", norm_line, 0.22) + + z_head_badge, z_head_tone, z_head_line, z_head_heat = _zone_summary( + (("头部", head_txt), ("眼睛", eye_txt), ("睡眠", sleep_txt)) + ) + z_oral_badge, z_oral_tone, z_oral_line, z_oral_heat = _zone_summary( + (("主诉", chief_txt), ("口干食欲", oral_txt), ("饮水", water_txt)) + ) + z_abd_badge, z_abd_tone, z_abd_line, z_abd_heat = _zone_summary( + (("脂肪肝", fatty_txt), ("体重变化", weight_c_txt), ("饮食", diet_c_txt), ("大便", stool_txt)) + ) + z_low_badge, z_low_tone, z_low_line, z_low_heat = _zone_summary( + (("肢体末梢", limb_txt), ("小便", urine_txt), ("腰肾", kidney_txt), ("汗肤", sweat_skin_txt)) + ) + + # Also boost middle abdomen heat if fasting >= 7.0 or postprandial >= 11.1 + if (recent_fasting and recent_fasting[-1][1] >= 7.0) or (post_points and post_points[-1][1] >= 11.1): + z_abd_heat = max(z_abd_heat, 0.80) + if z_abd_tone == "neutral": + z_abd_badge = "血糖偏高" + z_abd_tone = "coral" + z_abd_line = f"实测血糖高于参考线(空腹 {f_primary})" + + # Prescriptions & Notes real summaries + rx_list = [ + rx for rx in (prescriptions or ()) + if str(first_value(rx, "void_status", default=0) or 0) in {"0", "False", "false"} + ] + has_rx = bool(rx_list) or bool( + first_value(appt, "has_prescription", default=first_value(diag, "has_prescription", default=False)) + ) + notes_list = list(doctor_notes or ()) + tongue_img_count = sum(len(first_value(n, "tongue_images", default=[]) or []) for n in notes_list) + report_file_count = sum(len(first_value(n, "report_files", default=[]) or []) for n in notes_list) + + course_real = _clean_text( + first_value( + diag, + "disease_course_text", + "diabetes_discovery_year_text", + "diabetes_discovery_year", + "diabetes_history_text", + ) + ) + diag_title_real = _clean_text( + first_value(diag, "clinical_diagnosis", "diagnosis_type_text", "local_hospital_diagnosis") + ) + rx_status_str = f"已开处方 {len(rx_list)} 张" if rx_list else ("已开方" if has_rx else "当前未开方") + bottom_bar_text = " · ".join( + p + for p in ( + f"诊单 #{diag_id_val}" if diag_id_val else "", + diag_title_real or "诊断待完善", + f"病史 {course_real}" if course_real else "", + rx_status_str, + f"医嘱备注 {len(notes_list)} 条", + ) + if p + ) + scan_badge = f"诊断日期 · {diag_date_str}" if diag_date_str else f"诊单 #{diag_id_val or '—'}" + + # Tab 1: 全身问诊症候实采 + twin_sanjiao = SyndromeTwinVM( + has_patient=True, + mode_key="sanjiao", + scan_badge=scan_badge, + empty_title="", + empty_subtitle="", + nodes=( + TwinCalloutNode( + locus_id="head_eye_sleep", + side="left", + anchor_x=0.50, + anchor_y=0.22, + card_y=0.25, + status_text=z_head_badge, + status_tone=z_head_tone, + title="头面 · 眼底与睡眠", + detail=_clip(z_head_line, 20), + full_tooltip=z_head_line, + ), + TwinCalloutNode( + locus_id="oral_thirst", + side="right", + anchor_x=0.52, + anchor_y=0.36, + card_y=0.27, + status_text=z_oral_badge, + status_tone=z_oral_tone, + title="上焦 · 主诉与口渴饮水", + detail=_clip(z_oral_line, 20), + full_tooltip=z_oral_line, + ), + TwinCalloutNode( + locus_id="liver_pancreas_spleen", + side="left", + anchor_x=0.47, + anchor_y=0.53, + card_y=0.62, + status_text=z_abd_badge, + status_tone=z_abd_tone, + title="中焦 · 肝脂脾胃与体重", + detail=_clip(z_abd_line, 20), + full_tooltip=z_abd_line, + ), + TwinCalloutNode( + locus_id="kidney_limbs", + side="right", + anchor_x=0.53, + anchor_y=0.70, + card_y=0.66, + status_text=z_low_badge, + status_tone=z_low_tone, + title="下焦 · 腰肾二便与四肢", + detail=_clip(z_low_line, 20), + full_tooltip=z_low_line, + ), + ), + bottom_capsule_title="病历实采总览", + bottom_capsule_text=bottom_bar_text, + recorded_Zone_flags=(z_head_heat, z_oral_heat, z_abd_heat, z_low_heat), + ) + + # Tab 2: 病史、当地诊断与现用药 + past_txt = _clean_text(first_value(diag, "past_history_text", "past_history_desc", "past_history")) + allergy_txt = _clean_text(first_value(diag, "allergy_history_text", "allergy_history_desc", "allergy_history")) + family_txt = _clean_text(first_value(diag, "family_history_text", "family_history_desc", "family_history")) + local_hosp = " · ".join( + p + for p in ( + _clean_text(first_value(diag, "local_hospital_name", "local_hospital")), + _clean_text(first_value(diag, "local_hospital_diagnosis", "local_diagnosis")), + ) + if p + ) + allergy_alert = bool(allergy_txt and not _is_normal_or_negated(allergy_txt)) + + twin_organ = SyndromeTwinVM( + has_patient=True, + mode_key="organ", + scan_badge="病史与现用药核查", + empty_title="", + empty_subtitle="", + nodes=( + TwinCalloutNode( + locus_id="local_diagnosis", + side="left", + anchor_x=0.50, + anchor_y=0.33, + card_y=0.27, + status_text=course_real or "病史核查", + status_tone="emerald" if (diag_title_real or local_hosp) else "neutral", + title="确诊病种与外院诊断", + detail=_clip(local_hosp or diag_title_real or "未录入当地医院诊断", 20), + full_tooltip=local_hosp or diag_title_real or "未录入当地医院诊断", + ), + TwinCalloutNode( + locus_id="current_meds", + side="right", + anchor_x=0.48, + anchor_y=0.52, + card_y=0.29, + status_text="在用方案" if meds_full else "未填用药", + status_tone="gold" if meds_full else "neutral", + title="当前在用降糖药 / 胰岛素", + detail=_clip(meds_full or "暂未录入在用药物", 20), + full_tooltip=meds_full or "暂未录入在用药物", + ), + TwinCalloutNode( + locus_id="past_history", + side="left", + anchor_x=0.47, + anchor_y=0.64, + card_y=0.64, + status_text="既往病史" if past_txt else "未采集", + status_tone="coral" if (past_txt and not _is_normal_or_negated(past_txt)) else "neutral", + title="既往史与合并症", + detail=_clip(past_txt or "未记录既往病史", 20), + full_tooltip=past_txt or "未记录既往病史", + ), + TwinCalloutNode( + locus_id="allergy_family", + side="right", + anchor_x=0.53, + anchor_y=0.68, + card_y=0.66, + status_text="过敏预警" if allergy_alert else ("已核实" if (allergy_txt or family_txt) else "未采集"), + status_tone="coral" if allergy_alert else "emerald" if (allergy_txt or family_txt) else "neutral", + title="药物过敏史与家族史", + detail=_clip( + f"过敏:{allergy_txt or '未填'} · 家族:{family_txt or '未填'}", + 20, + ), + full_tooltip=f"过敏史:{allergy_txt or '未记录'}\n家族史:{family_txt or '未记录'}", + ), + ), + bottom_capsule_title="用药与病史状态", + bottom_capsule_text=bottom_bar_text, + recorded_Zone_flags=(z_head_heat, z_oral_heat, z_abd_heat, z_low_heat), + ) + + # Tab 3: 四诊舌脉、医生备注附件与已开处方 + tongue_real = _clean_text(first_value(diag, "tongue", "tongue_coating")) + pulse_real = _clean_text(first_value(diag, "pulse", "pulse_condition")) + principle_real = _clean_text(first_value(diag, "treatment_principle", "prescription_opinion")) + latest_note_txt = _clean_text(first_value(notes_list[0], "content", "remark")) if notes_list else "" + + if rx_list: + latest_rx = rx_list[0] + herbs = first_value(latest_rx, "herbs", default=[]) or [] + herb_names = [ + f"{_clean_text(first_value(h, 'name', 'medicine_name'))}{_clean_text(first_value(h, 'dosage', 'amount'))}g" + for h in herbs[:5] + if _clean_text(first_value(h, "name", "medicine_name")) + ] + rx_herbs_summary = "、".join(herb_names) if herb_names else f"共 {len(herbs)} 味中药" + med_days = first_value(latest_rx, "medication_days", "usage_days", "dose_count", default="") + rx_badge = f"已开 {med_days}天" if med_days else f"共 {len(rx_list)} 张处方" + rx_tone = "emerald" + elif has_rx: + rx_herbs_summary = "已关联有效电子处方(可在已开处方查看明细)" + rx_badge = "已开具处方" + rx_tone = "emerald" + else: + rx_herbs_summary = "本次诊单尚未开具中药处方" + rx_badge = "未开方" + rx_tone = "gold" + + twin_tcm = SyndromeTwinVM( + has_patient=True, + mode_key="tcm", + scan_badge="四诊·备注·处方实录", + empty_title="", + empty_subtitle="", + nodes=( + TwinCalloutNode( + locus_id="tongue_pulse", + side="left", + anchor_x=0.50, + anchor_y=0.31, + card_y=0.28, + status_text="已录舌脉" if (tongue_real or pulse_real) else "待录舌脉", + status_tone="emerald" if (tongue_real or pulse_real) else "neutral", + title="望舌与切脉记录", + detail=_clip( + f"舌:{tongue_real or '未填'} · 脉:{pulse_real or '未填'}", + 20, + ), + full_tooltip=f"舌象:{tongue_real or '未记录'}\n脉象:{pulse_real or '未记录'}\n治则:{principle_real or '未记录'}", + ), + TwinCalloutNode( + locus_id="notes_media", + side="right", + anchor_x=0.53, + anchor_y=0.45, + card_y=0.30, + status_text=f"舌图{tongue_img_count} · 报告{report_file_count}", + status_tone="emerald" if (notes_list or tongue_img_count or report_file_count) else "neutral", + title="医生备注与影像附件", + detail=_clip(latest_note_txt or f"共 {len(notes_list)} 条医生备注", 20), + full_tooltip=latest_note_txt or "点击打开结构化病历查看或上传舌苔图与检查报告", + ), + TwinCalloutNode( + locus_id="rx_summary", + side="left", + anchor_x=0.48, + anchor_y=0.62, + card_y=0.64, + status_text=rx_badge, + status_tone=rx_tone, + title="本诊单电子处方记录", + detail=_clip(rx_herbs_summary, 20), + full_tooltip=rx_herbs_summary, + ), + TwinCalloutNode( + locus_id="rx_principle", + side="right", + anchor_x=0.52, + anchor_y=0.68, + card_y=0.66, + status_text="治则方义" if principle_real else "待拟治则", + status_tone="emerald" if principle_real else "neutral", + title="辨证治则与处方意见", + detail=_clip(principle_real or "暂未录入治则与处方意见", 20), + full_tooltip=principle_real or "暂未录入治则与处方意见", + ), + ), + bottom_capsule_title="四诊与处方核验", + bottom_capsule_text=bottom_bar_text, + recorded_Zone_flags=(z_head_heat, z_oral_heat, z_abd_heat, z_low_heat), + ) + + # ── 4. Bottom 21-Day Real Check-in & Revisit Due Track ─────────────── + start_21 = today - timedelta(days=20) + days_21: list[JourneyDayCell] = [] + checked_in_days = 0 + for idx in range(21): + d_obj = start_21 + timedelta(days=idx) + d_iso = d_obj.isoformat() + b_list = blood_by_date.get(d_iso, []) + f_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "fasting_blood_sugar", default=None))) is not None] + p_vals = [v for r in b_list if (v := _parse_positive_float(first_value(r, "postprandial_blood_sugar", default=None))) is not None] + has_diet = d_iso in diet_dates + ex_txt = exercise_by_date.get(d_iso, "") + tr_txt = note_by_date.get(d_iso, "") + + has_any = bool(f_vals or p_vals or has_diet or ex_txt or tr_txt) + if has_any: + checked_in_days += 1 + + tip_lines = [f"{d_iso}({'今日' if d_obj == today else '历史记录'})"] + if f_vals: + tip_lines.append(f"空腹血糖:{f_vals[-1]:g} mmol/L") + if p_vals: + tip_lines.append(f"餐后2h血糖:{p_vals[-1]:g} mmol/L") + if has_diet: + tip_lines.append("饮食记录:已上传") + if ex_txt: + tip_lines.append(f"运动记录:{ex_txt}") + if tr_txt: + tip_lines.append(f"跟踪备注:{_clip(tr_txt, 28)}") + if not has_any: + tip_lines.append("当日无血糖/饮食/运动打卡") + + is_high_day = max(f_vals, default=0.0) >= 7.0 or max(p_vals, default=0.0) >= 11.1 + if d_obj == today: + cell_state = "today" + elif is_high_day: + cell_state = "alert" + elif f_vals or p_vals: + cell_state = "completed" + elif has_any: + cell_state = "stage" + else: + cell_state = "planned" + + days_21.append( + JourneyDayCell( + day_num=idx + 1, + date_iso=d_iso, + label_text=str(d_obj.day), + state=cell_state, + tooltip="\n".join(tip_lines), + has_dot=is_high_day, + ) + ) + + # Parse `revisit_due` (Contract C from `RevisitNodeCell.vue`) if present + revisit_due = first_value(diag, "revisit_due", default=first_value(appt, "revisit_due", default=None)) + if isinstance(revisit_due, Mapping) and str(revisit_due.get("state") or "none") not in {"none", ""}: + slot_n = int(revisit_due.get("current_slot") or 0) + med_d = int(revisit_due.get("medication_days") or 0) + due_dt = _clean_text(revisit_due.get("due_date")) + st_txt = _clean_text(revisit_due.get("state_text")) or "复诊跟踪中" + st_code = str(revisit_due.get("state") or "") + j_sub = " · ".join( + p for p in (f"第 {slot_n} 诊" if slot_n > 0 else "", f"开药 {med_d} 天" if med_d > 0 else "", f"药尽 {due_dt[5:]}" if len(due_dt) >= 10 else "") if p + ) or "复诊用药周期跟踪" + j_pill = st_txt + j_tone = "coral" if st_code in {"overdue", "missed", "warning", "no_days"} else "emerald" + end_cap = f"药尽 {due_dt[5:]}" if len(due_dt) >= 10 else st_txt[:4] + else: + j_sub = f"{start_21.strftime('%m-%d')} 至 {today.strftime('%m-%d')} 血糖·饮食·运动实录" + j_pill = rx_status_str + j_tone = "emerald" if has_rx else "neutral" + end_cap = "已开方" if has_rx else "待开方" + + journey_vm = CareJourneyVM( + title="近 21 天健康打卡与复诊", + plan_subtitle=j_sub, + primary_metric_text=f"{checked_in_days}", + total_unit_text="/ 21 天有打卡", + status_pill=j_pill, + status_tone=j_tone, + end_capsule_text=end_cap, + phases=( + JourneyPhaseSpan( + "第1周", + "早期基线周", + f"{start_21.strftime('%m-%d')}–{(start_21 + timedelta(days=6)).strftime('%m-%d')}", + 1, + 7, + False, + ), + JourneyPhaseSpan( + "第2周", + "中期观察周", + f"{(start_21 + timedelta(days=7)).strftime('%m-%d')}–{(start_21 + timedelta(days=13)).strftime('%m-%d')}", + 8, + 14, + False, + ), + JourneyPhaseSpan( + "近7天", + "本周实测窗口", + f"{(start_21 + timedelta(days=14)).strftime('%m-%d')}–{today.strftime('%m-%d')}", + 15, + 21, + True, + ), + ), + days=tuple(days_21), + milestones=( + (1, start_21.strftime("%m-%d")), + (8, (start_21 + timedelta(days=7)).strftime("%m-%d")), + (15, (start_21 + timedelta(days=14)).strftime("%m-%d")), + (21, "今日"), + ), + ) + + # ── 5. Bottom Obsidian Aurora-Glass AI Sheet: 100% Real AI Reports ─── + # Compute 100% objective 6-dimension Clinical Record Completeness + completeness_dims = [ + ("基础体征(身高/体重/血压)", bool(bp_val != "—" or hw_val != "—")), + ("血糖实测(空腹/餐后)", bool(recent_fasting or post_points or other_points or diag_fasting_text)), + ("主诉与全身问诊", bool(chief_txt or oral_txt or head_txt or diet_c_txt or limb_txt)), + ("既往史与在用药", bool(meds_full or past_txt or allergy_txt or local_hosp)), + ("舌脉与医生备注", bool(tongue_real or pulse_real or principle_real or notes_list)), + ("电子处方开具", bool(has_rx)), + ] + filled_count = sum(1 for _, ok in completeness_dims if ok) + missing_names = [name for name, ok in completeness_dims if not ok] + gauge_tip = ( + "病历 6 大维度已全部实采完备" + if not missing_names + else "待补采维度:" + "、".join(missing_names) + ) + + diag_advice = _clean_text(first_value(ai_payload or {}, "diagnosis_advice", "summary")) + treat_advice = _clean_text(first_value(ai_payload or {}, "treatment_advice")) + raw_risks = first_value(ai_payload or {}, "risk_assessment", default=[]) + parsed_risks: list[tuple[str, str]] = [] + if isinstance(raw_risks, Sequence) and not isinstance(raw_risks, (str, bytes)): + for item in raw_risks: + if isinstance(item, Mapping): + lvl = str(item.get("level") or "medium").lower() + lbl = _clean_text(item.get("label") or item.get("text")) + if lbl: + parsed_risks.append((lvl, lbl)) + elif isinstance(item, str) and item.strip(): + parsed_risks.append(("medium", item.strip())) + + snap_time = _clean_text(first_value(ai_payload or {}, "generated_at", "created_at"))[:16] + if ai_payload and (diag_advice or treat_advice or parsed_risks): + ai_status_txt = "已生成" + summary_banner = _clip(diag_advice or treat_advice, 62) + c1_body = diag_advice or "该模型未返回诊断建议正文。" + c2_body = treat_advice or "该模型未返回治疗与用药复核正文。" + c3_body = ( + "\n".join( + f"• [{'高危' if lv == 'high' else ('中危' if lv == 'medium' else '关注')}] {lb}" + for lv, lb in parsed_risks[:4] + ) + if parsed_risks + else "当前模型未标记特殊高危风险项,请结合实测血糖与过敏史常规复核。" + ) + c1_badge = "已生成" + c2_badge = "已生成" + c3_badge = f"{len(parsed_risks)} 项风险" + elif ai_state == "loading": + ai_status_txt = "正在分析…" + summary_banner = ai_message or f"正在请求 {model_label} 分析 {patient_name} 的实采病历…" + c1_body = f"正在根据 {patient_name} 的已录入病历生成 {model_label} 诊断建议,请稍候…" + c2_body = f"正在同步 {model_label} 治法方向与现用药物复核要点…" + c3_body = "正在筛查潜在血糖波动与并发症风险…" + c1_badge = c2_badge = c3_badge = "分析中…" + else: + ai_status_txt = "暂未生成" + summary_banner = ( + ai_message + or f"{patient_name} 当前尚无已保存的 {model_label} 快照 · 点击右侧「完整循证报告」或「AI 深度对话」发起实采分析" + ) + c1_body = f"服务端暂无 {patient_name} 的 {model_label} 诊断分析快照。点击「完整循证报告」可触发生成或查看历史快照。" + c2_body = "未生成治疗建议快照。我们不在界面编造任何配伍评分或虚构建议。" + c3_body = "未生成风险分层快照。" + c1_badge = c2_badge = "未生成" + c3_badge = "待分析" + + aurora_vm = ObsidianAuroraVM( + has_patient=True, + program_title="AI 病历循证分析舱", + ai_summary_line=summary_banner, + active_model_key=active_ai_model, + active_model_label=model_label, + params=( + ("当前模型", model_label), + ("报告状态", ai_status_txt), + ("快照时间", snap_time or "—"), + ), + cards=( + AuroraCardVM( + kind="diagnosis", + tint="cyan", + title="AI 辨证与病情分析", + subtitle=f"{model_label} · 实采病历循证梳理", + badge_text=c1_badge, + body_text=c1_body, + risk_items=(), + foot_left=f"患者:{patient_name}", + foot_right="点击查看全文 ↗", + ), + AuroraCardVM( + kind="treatment", + tint="olive", + title="AI 治法与用药复核", + subtitle=f"{model_label} · 中西药与随访核实建议", + badge_text=c2_badge, + body_text=c2_body, + risk_items=(), + foot_left="仅供临床辅助参考", + foot_right="点击查看全文 ↗", + ), + AuroraCardVM( + kind="risks", + tint="amber", + title="AI 临床风险分层", + subtitle=f"{model_label} · 风险识别与待补采提示", + badge_text=c3_badge, + body_text=c3_body, + risk_items=tuple(parsed_risks[:4]), + foot_left=f"共 {len(parsed_risks)} 项提示", + foot_right="点击查看全文 ↗", + ), + ), + gauge_value=f"{filled_count}/6", + gauge_unit="项", + gauge_caption="病历实采完备度", + gauge_ratio=max(0.08, min(1.0, filled_count / 6.0)), + gauge_tooltip=gauge_tip, + ) + + return CockpitSnapshotVM( + has_patient=True, + patient_name=patient_name, + progression=progression_vm, + diurnal=diurnal_vm, + twin_sanjiao=twin_sanjiao, + twin_organ=twin_organ, + twin_tcm=twin_tcm, + journey=journey_vm, + aurora=aurora_vm, + ) diff --git a/app/src/doctor_workstation/ui/visuals/__init__.py b/app/src/doctor_workstation/ui/visuals/__init__.py new file mode 100644 index 000000000..1e6dc94da --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/__init__.py @@ -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", +] diff --git a/app/src/doctor_workstation/ui/visuals/aurora_sheet.py b/app/src/doctor_workstation/ui/visuals/aurora_sheet.py new file mode 100644 index 000000000..ef17c2dfa --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/aurora_sheet.py @@ -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)) diff --git a/app/src/doctor_workstation/ui/visuals/context_bridge_bar.py b/app/src/doctor_workstation/ui/visuals/context_bridge_bar.py new file mode 100644 index 000000000..810b24268 --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/context_bridge_bar.py @@ -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("") diff --git a/app/src/doctor_workstation/ui/visuals/diurnal_strip.py b/app/src/doctor_workstation/ui/visuals/diurnal_strip.py new file mode 100644 index 000000000..1ce5bb856 --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/diurnal_strip.py @@ -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, + ) diff --git a/app/src/doctor_workstation/ui/visuals/journey_track.py b/app/src/doctor_workstation/ui/visuals/journey_track.py new file mode 100644 index 000000000..3915a71b9 --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/journey_track.py @@ -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) diff --git a/app/src/doctor_workstation/ui/visuals/pill_chart.py b/app/src/doctor_workstation/ui/visuals/pill_chart.py new file mode 100644 index 000000000..bdfe58461 --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/pill_chart.py @@ -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, + ) diff --git a/app/src/doctor_workstation/ui/visuals/reception_cockpit.py b/app/src/doctor_workstation/ui/visuals/reception_cockpit.py new file mode 100644 index 000000000..04e461c9f --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/reception_cockpit.py @@ -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) diff --git a/app/src/doctor_workstation/ui/visuals/twin_stage.py b/app/src/doctor_workstation/ui/visuals/twin_stage.py new file mode 100644 index 000000000..546d6bbaa --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/twin_stage.py @@ -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, + ) diff --git a/app/src/doctor_workstation/ui/visuals/week_strip.py b/app/src/doctor_workstation/ui/visuals/week_strip.py new file mode 100644 index 000000000..950f8acda --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/week_strip.py @@ -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()], + ) diff --git a/app/tests/test_spatial_cockpit_v3.py b/app/tests/test_spatial_cockpit_v3.py new file mode 100644 index 000000000..4837993d7 --- /dev/null +++ b/app/tests/test_spatial_cockpit_v3.py @@ -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()