diff --git a/app/src/doctor_workstation/ui/diagnosis_drawer.py b/app/src/doctor_workstation/ui/diagnosis_drawer.py index 62cff2207..f4831be99 100755 --- a/app/src/doctor_workstation/ui/diagnosis_drawer.py +++ b/app/src/doctor_workstation/ui/diagnosis_drawer.py @@ -17,6 +17,7 @@ from PySide6.QtCore import ( QDate, QEvent, QPointF, + QPropertyAnimation, QRect, QRectF, QSize, @@ -63,6 +64,7 @@ from PySide6.QtWidgets import ( QWidget, ) +from . import motion from .chat_items import ChatItem, parse_chat_item from .design_system import PALETTE, clinical_stylesheet from .diagnosis_editors import FlowLayout @@ -1265,7 +1267,7 @@ class SaveStateButton(QPushButton): class DiagnosisTabWidget(QTabWidget): - """Scrollable diagnosis tabs without boxed previous/next arrow controls.""" + """Pan the native tab bar in pixels independently of the selected page.""" def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) @@ -1275,45 +1277,100 @@ class DiagnosisTabWidget(QTabWidget): self.tab_scrollbar = QScrollBar(Qt.Orientation.Horizontal, self) self.tab_scrollbar.setObjectName("DiagnosisTabOverflow") self.tab_scrollbar.setFixedHeight(4) - self.tab_scrollbar.setSingleStep(1) - self.tab_scrollbar.valueChanged.connect(self._scroll_to_tab) - self.currentChanged.connect(self._sync_scroll_value) + self.tab_scrollbar.setSingleStep(24) + self.tab_scrollbar.valueChanged.connect(self._pan_to) + self._wheel_animation = QPropertyAnimation(self.tab_scrollbar, b"value", self) + self._wheel_animation.setDuration(motion.SCROLL_MS) + self._wheel_animation.setEasingCurve(motion.EASE_ENTER) + self.tab_scrollbar.sliderPressed.connect(self._wheel_animation.stop) + self.tab_scrollbar.actionTriggered.connect(self._wheel_animation.stop) + self.tabBar().installEventFilter(self) + self.tab_scrollbar.installEventFilter(self) + self.tabBar().currentChanged.connect(lambda _: self._sync_overflow(reveal=True)) self.tab_scrollbar.hide() - self._overflow_sync = QTimer(self) - self._overflow_sync.setSingleShot(True) - self._overflow_sync.setInterval(0) - self._overflow_sync.timeout.connect(self._sync_overflow) + self._strip_size = (0, 0) - def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt API - super().resizeEvent(event) - self._overflow_sync.start() + def event(self, event: QEvent) -> bool: + handled = super().event(event) + if event.type() in ( + QEvent.Type.Resize, QEvent.Type.Show, QEvent.Type.LayoutRequest, + QEvent.Type.StyleChange, QEvent.Type.FontChange, + ) and hasattr(self, "_strip_size"): + self._sync_overflow(reveal=event.type() == QEvent.Type.Show) + return handled - def tabInserted(self, index: int) -> None: # noqa: N802 - Qt API - super().tabInserted(index) - self._overflow_sync.start() + def _sync_overflow(self, *, reveal: bool = False) -> None: + bar = self.tabBar() + width = self.width() + content = max(0, bar.sizeHint().width()) + rail = self.tab_scrollbar + previous_width, _ = self._strip_size + selected = bar.tabRect(bar.currentIndex()) + was_in_view = selected.left() >= rail.value() and selected.right() < rail.value() + previous_width + # Let the parent clip the full-width bar. Qt then keeps native tab hit + # testing and keyboard navigation without a second, tab-sized offset. + if bar.minimumWidth() != content or bar.maximumWidth() != content: + bar.setFixedWidth(content) + rail.setGeometry(0, bar.y() + bar.height(), width, rail.height()) + rail.setPageStep(width) + rail.setRange(0, max(0, content - width)) + rail.setVisible(content > width) + if self._strip_size != (width, content): + self._strip_size = (width, content) + self._wheel_animation.stop() + reveal = reveal or not previous_width or was_in_view + if reveal: + self._reveal_tab(bar.currentIndex()) + # QTabWidget lays its tab bar back at the origin on layout requests. + self._pan_to(rail.value()) - def tabRemoved(self, index: int) -> None: # noqa: N802 - Qt API - super().tabRemoved(index) - self._overflow_sync.start() + def _pan_to(self, offset: int) -> None: + bar = self.tabBar() + bar.move(-offset, bar.y()) - def _sync_overflow(self) -> None: - bar_height = self.tabBar().height() - # Keep overflow navigation below the selected-tab underline. - self.tab_scrollbar.setGeometry(0, bar_height, self.width(), 4) - overflow = self.tabBar().sizeHint().width() > self.width() - self.tab_scrollbar.setRange(0, max(0, self.count() - 1)) - self.tab_scrollbar.setPageStep(max(1, self.width() // 92)) - self.tab_scrollbar.setVisible(overflow and self.count() > 1) - self.tab_scrollbar.raise_() + def _reveal_tab(self, index: int) -> None: + self._wheel_animation.stop() + if index < 0: + return + tab = self.tabBar().tabRect(index) + rail = self.tab_scrollbar + if tab.left() < rail.value(): + rail.setValue(tab.left()) + elif tab.right() >= rail.value() + self.width(): + rail.setValue(tab.right() + 1 - self.width()) - def _scroll_to_tab(self, index: int) -> None: - if 0 <= index < self.count() and index != self.currentIndex(): - self.setCurrentIndex(index) - - def _sync_scroll_value(self, index: int) -> None: - self.tab_scrollbar.blockSignals(True) - self.tab_scrollbar.setValue(max(0, index)) - self.tab_scrollbar.blockSignals(False) + def eventFilter(self, watched, event: QEvent) -> bool: # noqa: N802 - Qt API + if event.type() != QEvent.Type.Wheel or watched not in (self.tabBar(), self.tab_scrollbar): + return super().eventFilter(watched, event) + rail = self.tab_scrollbar + pixels = event.pixelDelta() + angle = event.angleDelta() + if pixels.isNull(): + step = -round((angle.x() or angle.y()) * motion.SCROLL_STEP / 120) + else: + step = -(pixels.x() or pixels.y()) + if not step or not rail.maximum() or event.modifiers() & ( + Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier + ): + event.ignore() + return True + animation = self._wheel_animation + current = rail.value() + continuous = not pixels.isNull() or event.phase() != Qt.ScrollPhase.NoScrollPhase + if continuous or motion.reduced_motion(): + animation.stop() + rail.setValue(current + step) + else: + pending = animation.endValue() if animation.state() == QPropertyAnimation.State.Running else current + origin = current if (pending - current) * step < 0 else pending + target = max(0, min(rail.maximum(), origin + step)) + if target != pending: + animation.stop() + animation.setStartValue(current) + animation.setEndValue(target) + animation.start() + event.accept() + return True class DiagnosisLineEdit(QLineEdit): diff --git a/app/src/doctor_workstation/ui/dialogs/ai_consult.py b/app/src/doctor_workstation/ui/dialogs/ai_consult.py index 2a56ec2c9..3ab15fc23 100755 --- a/app/src/doctor_workstation/ui/dialogs/ai_consult.py +++ b/app/src/doctor_workstation/ui/dialogs/ai_consult.py @@ -3491,7 +3491,7 @@ class _ChatBubble(QWidget): self._role_name = role_name meta.addWidget(role_name) meta.addStretch(1) - self.stamp = QLabel(time_text) + self.stamp = QLabel(time_text, bubble) self.stamp.setObjectName("AiConsultTime") self.stamp.setVisible(bool(time_text)) meta.addWidget(self.stamp) @@ -7794,6 +7794,7 @@ def present_ai_consult( patient_id: int = 0, seed: Any = None, source_title: str = "问诊列表", + prescription_patient_name: str = "", ) -> None: if not can_open_ai_consult(permissions): if parent is not None: @@ -7804,6 +7805,8 @@ def present_ai_consult( show_toast(parent, "缺少诊单编号,无法打开 AI 对话。", "warning") return dialog = AiConsultDialog(repository, permissions, parent=parent) + if prescription_patient_name: + dialog.setProperty("prescriptionSheetPatient", prescription_patient_name) dialog.open_for( diagnosis_id=diagnosis_id, patient_id=patient_id, diff --git a/app/src/doctor_workstation/ui/dialogs/diagnosis.py b/app/src/doctor_workstation/ui/dialogs/diagnosis.py index a5dac8bdc..396ed0ebb 100755 --- a/app/src/doctor_workstation/ui/dialogs/diagnosis.py +++ b/app/src/doctor_workstation/ui/dialogs/diagnosis.py @@ -915,6 +915,7 @@ class DiagnosisDialog(QDialog): self._loading_tabs: set[str] = set() self._daily_todo_status: int | None = None self._pending_focus_target: tuple[str, str, int | None] | None = None + self._last_focus_target: tuple[str, str, int | None] | None = None self._highlighted_target: QWidget | None = None self._highlight_timer = QTimer(self) self._highlight_timer.setSingleShot(True) @@ -2301,6 +2302,7 @@ class DiagnosisDialog(QDialog): self._diagnosis_id = int(diagnosis_id) self._patient_id = 0 self._pending_focus_target = None + self._last_focus_target = None self._clear_field_highlight() self._editable = bool( editable and has_permission(self.permissions, "tcm.diagnosis/edit", default=True) @@ -2569,6 +2571,7 @@ class DiagnosisDialog(QDialog): ) -> None: """Switch to `tab_key` and scroll/highlight `field_key` or `section_index`.""" + self._last_focus_target = (tab_key, field_key, section_index) if not self._authoritative_detail_loaded: self._pending_focus_target = (tab_key, field_key, section_index) self._apply_clinical_target(tab_key, field_key=field_key, section_index=section_index) @@ -2613,9 +2616,12 @@ class DiagnosisDialog(QDialog): def _do_scroll() -> None: with suppress(RuntimeError): - if scroll.widget() is None or not target.isVisibleTo(scroll.widget()): - if scroll.widget() is not None and scroll.widget().layout() is not None: - scroll.widget().layout().activate() + if ( + scroll.widget() is not None + and scroll.widget().layout() is not None + and not target.isVisibleTo(scroll.widget()) + ): + scroll.widget().layout().activate() if self.form_host.layout() is not None: self.form_host.layout().activate() y_pos = target.mapTo(scroll.widget(), target.rect().topLeft()).y() @@ -2689,6 +2695,10 @@ class DiagnosisDialog(QDialog): editor._sync_flow_height() if hasattr(self, "form_host"): self.form_host.updateGeometry() + if self._highlight_timer.isActive() and self._last_focus_target is not None: + t_key, f_key, s_idx = self._last_focus_target + if t_key == "basic": + self._apply_clinical_target(t_key, field_key=f_key, section_index=s_idx) def _show_authoritative_content(self, visible: bool) -> None: self.readonly_patient_card.setVisible(visible) diff --git a/app/src/doctor_workstation/ui/dialogs/esign_doctor.py b/app/src/doctor_workstation/ui/dialogs/esign_doctor.py index 1adce2a43..6759b3288 100644 --- a/app/src/doctor_workstation/ui/dialogs/esign_doctor.py +++ b/app/src/doctor_workstation/ui/dialogs/esign_doctor.py @@ -18,7 +18,7 @@ from PySide6.QtWidgets import ( ) from shiboken6 import isValid -from ...core.errors import ApiBusinessError, AuthenticationExpiredError +from ...core.errors import ApiBusinessError, ApiTimeoutError, AuthenticationExpiredError from ...core.esign import ( certificate_identity_number, esign_doctor_mobile, @@ -61,6 +61,7 @@ class EsignDoctorDialog(QDialog): self.state: dict[str, Any] = {} self._busy = False self._closed = False + self._status_read_pending = True self._generation = 0 self._retry_mobile = False self._manual_check = False @@ -156,8 +157,16 @@ class EsignDoctorDialog(QDialog): close.rejected.connect(self.reject) footer.addWidget(close) layout.addLayout(footer) - self.banner.show_message("正在查询医生签署身份…", "info") - self.refresh() + self._sync_actions() + + def _read_status_when_visible(self) -> None: + if (self._status_read_pending and self.isVisible() and not self.isMinimized() + and not self._busy and not self._closed): + self.refresh() + + def showEvent(self, event: Any) -> None: + super().showEvent(event) + self._read_status_when_visible() def _sync_actions(self) -> None: active = not self._busy and not self._closed and not self._native_hide_pending @@ -261,7 +270,10 @@ class EsignDoctorDialog(QDialog): self._stop_view() if method == "get_esign_doctor_status": self.state = {} - self.banner.show_message("医生签署身份状态待确认,请检查认证状态后继续。", "warning") + message = ("查询医生签署身份超时,请点击「检查认证状态」重试。" + if isinstance(error, ApiTimeoutError) + else "医生签署身份状态待确认,请检查认证状态后继续。") + self.banner.show_message(message, "warning") else: # 发起或绑定被拒绝时保留当前步骤,医生可直接修正后重试。 reason = str(error) if isinstance(error, (ApiBusinessError, AuthenticationExpiredError)) else "" @@ -273,6 +285,10 @@ class EsignDoctorDialog(QDialog): self._busy = False if self._closed: return + # Docking can hide and show the panel before the old request finishes. + if self._status_read_pending: + self._read_status_when_visible() + return self._sync_actions() if (succeeded and current() and method == "start_esign_doctor" and self.isVisible() and self.state.get("auth_url")): @@ -290,6 +306,9 @@ class EsignDoctorDialog(QDialog): def refresh(self) -> None: if self._busy or self._closed: return + self._status_read_pending = False + if not self.state: + self.banner.show_message("正在查询医生签署身份…", "info") self.mobile_input.setText("") self.identity_input.setText("") self._request("get_esign_doctor_status") @@ -400,6 +419,8 @@ class EsignDoctorDialog(QDialog): def _suspend(self) -> None: self._generation += 1 + self._status_read_pending = True + self._manual_check = False self.signer_input.setText("") self.mobile_input.setText("") self.identity_input.setText("") diff --git a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py index 40aa747f5..fc8d75af6 100755 --- a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py +++ b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai.py @@ -2,7 +2,7 @@ from __future__ import annotations -from collections.abc import Mapping +from collections.abc import Callable, Mapping from copy import deepcopy from html import escape from math import isfinite @@ -339,13 +339,17 @@ def batch_running(batch: Any) -> bool: def agreement_text(batch: Any) -> str: data = mapping(batch) + if not current_batch(data): + return "" models = mapping(data.get("models")) - stale = not current_batch(data) parts = [] for key, name in MODELS.items(): model = mapping(models.get(key)) - value = "—" if stale or model.get("comparison_status") == "not_comparable" else percentage(model.get("score")) - parts.append(f"{name} {value}") + if model.get("comparison_status") == "not_comparable": + continue + value = percentage(model.get("score")) + if value != "—": + parts.append(f"{name} {value}") return "\n".join(parts) @@ -364,7 +368,8 @@ def state_text(batch: Any) -> str: if mapping(data.get("progress")).get("stage") in {"preparing", "waiting_sources", "retry_wait"}: state = progress_view(data).headline else: - if any(mapping(model).get("progress") for model in models.values()): + if any(mapping(model).get("progress") or mapping(model).get("status") == "retry_wait" + for model in models.values()): parts = [] for key, name in MODELS.items(): model = mapping(models.get(key)) @@ -1244,6 +1249,7 @@ class IssuedPrescriptionAiDialog(QDialog): self._timer.stop() self._freeze_progress() # A manual history refresh supersedes any pending detail response. + self._sync_actions() self._generation += 1 self._detail_pending = False self._history_generation += 1 @@ -1399,6 +1405,8 @@ class IssuedPrescriptionAiDialog(QDialog): self._clear_report() else: self._freeze_progress() + if self._batch: + self.live_status.setText("同步已暂停") suffix = " · 当前显示上次读取的数据,进度已暂停更新。点击刷新重连。" if self._batch else "" self.message.setText(prefix + _error_text(error) + suffix) self._sync_actions() @@ -1437,7 +1445,7 @@ class IssuedPrescriptionAiDialog(QDialog): if (first_load or recovered) and self._feature_enabled: self.message.setText("已读取最新保存的报告;处理进度每 5 秒同步。" if batch_running(batch) else "已读取最新保存的报告。") compact_state = state_text(batch).replace("\n", " · ") - self.live_status.setText("分析中 · 自动同步" if batch_running(batch) else "已读取报告") + self.live_status.setText("每 5 秒同步进度" if batch_running(batch) else "已读取报告") self.identity.setText(f"处方 {batch.get('prescription_id')} · 诊单 {batch.get('diagnosis_id')} · 版本 {batch.get('prescription_revision', '—')}") self._set_chips([ (label(batch.get("validity")), "info" if current_batch(batch) else "warn"), @@ -1608,21 +1616,33 @@ class IssuedPrescriptionAiDialog(QDialog): """Show why a model stopped and whether a retry is still available.""" data = mapping(batch) - retry_allowed = has_permission(self.permissions, "tcm.prescriptionAi/retry", default=False) for key, name in MODELS.items(): model = mapping(mapping(data.get("models")).get(key)) if model.get("status") != "failed": self.agreement.set_failure(key, "", False) continue reason = _reason(model.get("error_message") or model.get("error_code")) or "模型未能完成本次生成" - retryable = bool(retry_allowed and current_batch(data) and not self._progress_stale and self._feature_enabled) - exhausted = int(mapping(model.get("progress")).get("manual_retries") or model.get("manual_retries") or 0) >= 2 - if exhausted: + if model.get("error_code") == "ACCESS_REVOKED": + self.agreement.set_failure( + key, f"{name} 失败:{reason}。请核对资料访问权限,再使用“重新分析”建立新批次。", False) + elif self._retries_exhausted(model): self.agreement.set_failure( key, f"{name} 失败:{reason}。手动重试次数已用完,请使用“重新分析”生成新批次。", False) else: self.agreement.set_failure( - key, f"{name} 失败:{reason}。可仅重试本模型,使用原资料快照。", retryable) + key, f"{name} 失败:{reason}。可仅重试本模型,使用原资料快照。", self._can_retry(model)) + + @staticmethod + def _retries_exhausted(model: dict[str, Any]) -> bool: + retries = model.get("manual_retries", mapping(model.get("progress")).get("manual_retries", 0)) + limit = model.get("max_manual_retries", 2) + return type(retries) is int and type(limit) is int and retries >= limit + + def _can_retry(self, model: dict[str, Any]) -> bool: + return (model.get("status") == "failed" and model.get("error_code") != "ACCESS_REVOKED" + and not self._retries_exhausted(model) and current_batch(self._batch) + and not self._busy and not self._progress_stale and self._feature_enabled + and has_permission(self.permissions, "tcm.prescriptionAi/retry", default=False)) def _set_chip(self, chip: QLabel, text: str, tone: str) -> None: background, colour = CHIP_TONES.get(tone, CHIP_TONES["neutral"]) @@ -1684,9 +1704,9 @@ class IssuedPrescriptionAiDialog(QDialog): bar.setValue(0) bar.hide() views["progress_title"].setVisible(progress.busy or bool(progress.detail)) - if "stage" in views: - views["stage"].setText(progress.headline) - views["stage"].setVisible(progress.busy or bool(progress.headline) and live) + stage = views["stage"] + stage.setText(model_prefix + (progress.retry_summary or progress.headline)) + stage.setVisible(bool(model) and model.get("status") in ACTIVE_STATES and (live or bool(model_prefix))) views["progress_detail"].setVisible(bool(progress.detail)) bar.setAccessibleName(progress.headline) bar.setToolTip("仅显示本阶段已完成的资料组数,不代表整体完成比例。" if progress.total is not None else progress.headline) @@ -1714,7 +1734,7 @@ class IssuedPrescriptionAiDialog(QDialog): self.refresh_button.setEnabled(active) for key, views in self.model_views.items(): model = mapping(mapping(self._batch.get("models")).get(key)) - views["retry"].setEnabled(active and not self._progress_stale and self._feature_enabled and model.get("status") == "failed" and current_batch(self._batch)) + views["retry"].setEnabled(self._can_retry(model)) reviewable = valid_batch and (bool(model.get("report_id")) or bool(model.get("report"))) views["save"].setEnabled(active and not self._progress_stale and reviewable) views["review_state"].setEnabled(active and reviewable) @@ -1722,12 +1742,14 @@ class IssuedPrescriptionAiDialog(QDialog): selected = self.review_model.currentData() self.save_review_button.setToolTip(f"保存 {MODELS[selected]} 的复核意见") - def _mutate(self, operation: Any, success: str) -> None: + def _mutate(self, operation: Any, success: str | Callable[[Any], str]) -> None: if self._busy: return self._busy = True self._timer.stop() self._freeze_progress() + self._generation += 1 + self._detail_pending = False generation = self._generation self._sync_actions() completed = False @@ -1736,7 +1758,7 @@ class IssuedPrescriptionAiDialog(QDialog): nonlocal completed completed = True if generation == self._generation: - self.message.setText(success) + self.message.setText(success(_result) if callable(success) else success) new_batch_id = mapping(_result).get("batch_id") if new_batch_id: self._preferred_batch_id = int(new_batch_id) @@ -1744,7 +1766,7 @@ class IssuedPrescriptionAiDialog(QDialog): def failed(error: Exception) -> None: if generation == self._generation: - self.message.setText(_error_text(error)) + self.message.setText(_error_text(error) + "。请刷新核对最新状态。") def finished() -> None: self._busy = False @@ -1770,7 +1792,15 @@ class IssuedPrescriptionAiDialog(QDialog): if not self.model_views[model_key]["retry"].isEnabled() or not has_permission(self.permissions, "tcm.prescriptionAi/retry", default=False): return batch_id = int(self._batch["id"]) - self._mutate(lambda: self.repository.retry_prescription_ai(batch_id, model_key), "已提交单模型重试。") + + def retry_feedback(result: Any) -> str: + response = mapping(result) + if not response.get("status"): + return f"已提交 {MODELS[model_key]} 重试,正在读取状态。" + view = progress_view(response) + return f"{MODELS[model_key]}:{view.headline}" + (f" · {view.retry_summary}" if view.retry_summary else "") + + self._mutate(lambda: self.repository.retry_prescription_ai(batch_id, model_key), retry_feedback) def _review(self, model_key: str) -> None: if not self.model_views[model_key]["save"].isEnabled() or not has_permission(self.permissions, "tcm.prescriptionAi/review", default=False): diff --git a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_console.py b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_console.py index bc343cb7a..74c92dd39 100755 --- a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_console.py +++ b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_console.py @@ -290,6 +290,7 @@ class AgreementBar(QFrame): stage.setTextFormat(Qt.TextFormat.PlainText) stage.setWordWrap(True) stage.setStyleSheet(f"color: {MODEL_TEXT[key]}; font-size: 12px;") + column.addWidget(stage) stage.hide() # The plain bar stays as a value carrier for callers and accessibility tools; the painted # track above is the visual, so it is never added to the layout. diff --git a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_progress.py b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_progress.py index 3afc92238..60ee51bcc 100755 --- a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_progress.py +++ b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_progress.py @@ -4,8 +4,11 @@ from __future__ import annotations from collections.abc import Mapping from dataclasses import dataclass +from datetime import datetime from typing import Any +from .issued_prescription_ai_labels import FIELD_LABELS, STATE_LABELS, system_text + ACTIVE_STATES = {"pending", "preparing", "queued", "waiting", "waiting_sources", "waiting_transcript", "waiting_transcription", "running", "processing", "retrying", "retry_wait"} SUCCESS_STATES = {"succeeded", "completed", "success"} TERMINAL_STATES = SUCCESS_STATES | {"partial", "failed", "cancelled", "canceled", "blocked", "stale", "superseded", "invalid", "revoked", "deleted", "voided"} @@ -50,6 +53,36 @@ class ProgressView: completed: int | None = None total: int | None = None busy: bool = False + retry_summary: str = "" + + +def _retry_summary(data: dict[str, Any], progress: dict[str, Any], advance: int) -> str: + parts = [] + reason = data.get("error_message") or data.get("error_code") + if reason: + parts.append(system_text(reason, STATE_LABELS, FIELD_LABELS)) + previous = data.get("last_error_message") or data.get("last_error_code") + if previous and previous != reason: + parts.append("上次失败:" + system_text(previous, STATE_LABELS, FIELD_LABELS)) + + server_time = _integer(progress.get("server_time")) + deadline = _integer(progress.get("next_run_at")) + remaining = _integer(progress.get("wait_remaining_seconds")) + if deadline and server_time: + remaining = max(0, deadline - server_time) + elif remaining and server_time and not deadline: + # Older servers round an overdue wait to zero, losing the original deadline. + deadline = server_time + remaining + if deadline and deadline <= 4_294_967_295: + parts.append("最早可执行时间 " + datetime.fromtimestamp(deadline).strftime("%Y-%m-%d %H:%M:%S")) + if remaining is None: + if not deadline: + parts.append("等待服务端更新重试时间") + elif remaining > advance: + parts.append("距下次重试 " + duration(remaining - advance)) + else: + parts.append("已到可执行时间,等待后台领取") + return " · ".join(parts) def progress_view(owner: Any, *, fallback_status: str = "", seconds: int = 0, live: bool = True) -> ProgressView: @@ -60,7 +93,7 @@ def progress_view(owner: Any, *, fallback_status: str = "", seconds: int = 0, li if stage not in STAGES: stage = "unknown" terminal = status in TERMINAL_STATES - if terminal: + if terminal or status in {"queued", "pending", "retry_wait", "retrying"}: stage = STATUS_STAGE.get(status, status) if stage not in STAGES: stage = "unknown" @@ -91,11 +124,12 @@ def progress_view(owner: Any, *, fallback_status: str = "", seconds: int = 0, li if stage_elapsed is not None and active and stage != "retry_wait": details.append("本阶段 " + duration(stage_elapsed + advance)) remaining = _integer(progress.get("wait_remaining_seconds")) - if stage in {"preparing", "waiting_sources", "retry_wait"} and remaining is not None and active: + retry_summary = _retry_summary(data, progress, advance) if stage == "retry_wait" else "" + if retry_summary: + details.append(retry_summary) + if stage in {"preparing", "waiting_sources"} and remaining is not None and active: remaining = max(0, remaining - advance) details.append("资料等待窗口剩余 " + duration(remaining) if remaining else "等待窗口已到,等待服务端确认") - if stage == "retry_wait": - details[-1] = "距下次重试 " + duration(remaining) if remaining else "重试时间已到,等待服务端确认" server_time = _integer(progress.get("server_time")) updated_at = _integer(progress.get("updated_at")) if active and server_time is not None and updated_at is not None and updated_at > 0: @@ -104,11 +138,13 @@ def progress_view(owner: Any, *, fallback_status: str = "", seconds: int = 0, li details.append("服务端暂未提供分阶段进度") notice = progress.get("notice") terminal_notice = stage in {"failed", "cancelled"} and progress.get("stage") == stage and progress.get("phase") == "failed" - if isinstance(notice, str) and notice.strip() and (not terminal or terminal_notice): + current_notice = stage not in {"queued", "retry_wait"} or progress.get("stage") in (None, "", stage) + if isinstance(notice, str) and notice.strip() and current_notice and (not terminal or terminal_notice): details.append(notice.strip()) elif stage in {"final", "text", "files", "reduce"} and active: details.append("等待模型响应;耗时取决于资料量与模型服务") - return ProgressView(stage, headline, " · ".join(details), completed, total, live and active) + busy = live and active and stage not in {"retry_wait", "queued"} + return ProgressView(stage, headline, " · ".join(details), completed, total, busy, retry_summary) def flow_text(batch: Any) -> str: @@ -130,6 +166,13 @@ def flow_text(batch: Any) -> str: prepared = "已完成" if any(models) else "待确认" comparisons = sum(model.get("status") in SUCCESS_STATES and bool(model.get("comparison")) for model in models) compare_state = f"{comparisons}/2 已处理" if comparisons else "进行中" if "comparing" in stages else "待处理" - analysis = f"{complete}/2 完成" + (f",{failed} 个失败" if failed else ",进行中" if status not in TERMINAL_STATES else "") + analysis = f"{complete}/2 完成" + if failed: + analysis += f",{failed} 个失败" + waiting = stages.count("retry_wait") + if waiting: + analysis += f",{waiting} 个等待重试" + elif not failed and status not in TERMINAL_STATES: + analysis += ",进行中" end = "已完成" if complete == 2 else "部分完成" if status == "partial" else "待处理" return f"准备资料:{prepared} → 双模型分析:{analysis} → 用药对照:{compare_state} → 完成:{end}" diff --git a/app/src/doctor_workstation/ui/pages/prescriptions.py b/app/src/doctor_workstation/ui/pages/prescriptions.py index 4ed0929ef..88c5011eb 100755 --- a/app/src/doctor_workstation/ui/pages/prescriptions.py +++ b/app/src/doctor_workstation/ui/pages/prescriptions.py @@ -18,6 +18,7 @@ from PySide6.QtCore import ( QSize, Qt, QTimer, + Signal, ) from PySide6.QtGui import ( QColor, @@ -56,6 +57,7 @@ from PySide6.QtWidgets import ( QStyledItemDelegate, QStyleOptionButton, QStyleOptionViewItem, + QTableWidgetItem, QTextEdit, QToolTip, QVBoxLayout, @@ -961,7 +963,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 len(lines) > 1: primary, secondary = lines[0], " · ".join(lines[1:]) if column == 5 else lines[1] if column == 5: @@ -1059,6 +1061,12 @@ class _PrescriptionCopyText(QTextEdit): self.table._hide_copy_text() self.table.setFocus() event.accept() + elif event.modifiers() == Qt.KeyboardModifier.NoModifier and event.key() in ( + Qt.Key.Key_Up, Qt.Key.Key_Down, + ): + self.table._hide_copy_text() + self.table.setFocus() + QApplication.sendEvent(self.table, event) else: super().keyPressEvent(event) @@ -1083,6 +1091,11 @@ class _PrescriptionBlueTable(SortableTable): self.model().dataChanged.connect(self._copy_data_changed) self.selectionModel().currentChanged.connect(self._copy_current_changed) + def current_data(self) -> Any: + # Qt keeps a current index even after the highlighted row is cleared. + rows = self.selectionModel().selectedRows(0) + return rows[0].data(Qt.ItemDataRole.UserRole) if rows else None + @staticmethod def _copyable(index: QModelIndex) -> bool: return index.isValid() and index.column() in (1, 3, 4, 5, 6, 7, 8, 9, 10) @@ -1156,6 +1169,9 @@ class _PrescriptionBlueTable(SortableTable): def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 index = self.indexAt(event.position().toPoint()) self._hide_copy_text() + if event.button() == Qt.MouseButton.LeftButton and index.column() == 0: + # The native checkbox consumes its press before the view selects the row. + self.setCurrentIndex(index) super().mousePressEvent(event) if event.button() == Qt.MouseButton.LeftButton and self._copyable(index): self._show_copy_text(index) @@ -1217,6 +1233,8 @@ class _PrescriptionBlueTable(SortableTable): class PrescriptionsPage(QWidget): """Complete issued-prescription route: list, workflow actions, print, and orders.""" + selected_prescription_changed = Signal(object) + def __init__( self, repository: Any, @@ -1231,6 +1249,7 @@ class PrescriptionsPage(QWidget): self.repository = repository self.permissions = permissions self.current_user = current_user + self._published_prescription: dict[str, Any] = {} self._page = 1 self._page_size = 15 self._generation = 0 @@ -1513,19 +1532,19 @@ class PrescriptionsPage(QWidget): table_layout.setSpacing(0) self.table = _PrescriptionBlueTable( [ - TableColumn("__selected__", "", 46, lambda _value, _row: ""), - TableColumn("sn", "处方编号", 260, _sn_cell), - TableColumn("__actions__", "操作", 150, lambda _value, _row: ""), - TableColumn("prescription_type", "处方类型", 96), - TableColumn("is_system_auto", "来源", 88, _source_cell), - TableColumn("patient_name", "患者信息", 190, _patient_cell), - TableColumn("audit_status", "审核状态", 110, _audit_cell), - 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("__selected__", "", 36, lambda _value, _row: ""), + TableColumn("sn", "处方编号", 136, _sn_cell), + TableColumn("__actions__", "操作", 144, lambda _value, _row: ""), + TableColumn("prescription_type", "处方类型", 78), + TableColumn("is_system_auto", "来源", 80, _source_cell), + TableColumn("patient_name", "患者信息", 98, _patient_cell), + TableColumn("audit_status", "审核状态", 80, _audit_cell), + TableColumn("void_status", "作废", 52, _void_cell), + TableColumn("doctor_name", "医生信息", 122, _doctor_cell), + TableColumn("assistant_name", "医助", 68), + TableColumn("create_time", "创建时间", 102, _create_time_cell), + TableColumn("__ai_status__", "AI 分析", 90, lambda _value, _row: ""), + TableColumn("__ai_agreement__", "与 AI 一致度", 116, lambda _value, _row: ""), ] ) self.table.setObjectName("PrescriptionTable") @@ -1533,16 +1552,14 @@ class PrescriptionsPage(QWidget): self.table.setAlternatingRowColors(False) self.table.verticalHeader().setMinimumSectionSize(80) self.table.verticalHeader().setDefaultSectionSize(80) - self.table.horizontalHeader().setFixedHeight(42) - self.table.horizontalHeader().setMinimumSectionSize(36) - 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) + header = self.table.horizontalHeader() + header.setFixedHeight(42) + header.setMinimumSectionSize(36) + header.setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) + header.setSectionResizeMode(QHeaderView.ResizeMode.Interactive) + # 仅调整显示顺序,行操作与 AI 点击事件仍使用原有逻辑列号。 + header.moveSection(header.visualIndex(2), header.count() - 1) # 操作跟在两列 AI 信息后 + header.moveSection(header.visualIndex(5), 1) # 勾选框后首先显示患者信息 self.table.horizontalHeaderItem(12).setToolTip("分别显示千问、OpenAI 的药味与剂量一致度;点击查看逐味贡献。") self.table.horizontalHeader().viewport().installEventFilter(self) self.table.verticalScrollBar().valueChanged.connect(lambda _value: self._schedule_ai_statuses()) @@ -1558,8 +1575,9 @@ class PrescriptionsPage(QWidget): 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.itemSelectionChanged.connect(self._publish_selected_prescription) 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.itemClicked.connect(self._ai_cell_clicked) self.table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.table.customContextMenuRequested.connect(self._open_ai_context_menu) table_layout.addWidget(self.table, 1) @@ -1746,6 +1764,7 @@ class PrescriptionsPage(QWidget): if generation != self._generation: return rows = page_items(result) + was_empty = self.table.rowCount() == 0 self.table.set_rows(rows) self._decorate_rows() self._render_ai_statuses() @@ -1768,7 +1787,7 @@ class PrescriptionsPage(QWidget): doctor_rows.extend(extend_doctors) self.doctor_filter.update_options(doctor_rows) self.banner.clear() - if rows and self.table.currentRow() < 0: + if rows and was_empty: self.table.selectRow(0) self._selection_changed() self._load_ai_statuses() @@ -1786,7 +1805,7 @@ class PrescriptionsPage(QWidget): 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 = self.table.columns[2].width for row_index in range(self.table.rowCount()): selector = self.table.item(row_index, 0) if selector is None: @@ -1857,7 +1876,7 @@ class PrescriptionsPage(QWidget): actions_host, ) ) - if self._ai_enabled and can_open_issued_ai(self.permissions) and not _is_blank_prescription(row): + if self._ai_enabled and self._can_view_ai_report(row): actions.addWidget( _row_action_button( "eye", "AI 报告", @@ -1958,14 +1977,15 @@ class PrescriptionsPage(QWidget): self.ai_status_notice.setVisible(not only_blank) if only_blank: self._ai_timer.stop() - self._set_ai_columns(False) + self._set_ai_enabled(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._set_ai_enabled(False) self.ai_status_notice.setText("AI 分析:当前账号没有查看分析状态的权限,请联系管理员授权。") return if not callable(method): + self._set_ai_enabled(False) self.ai_status_notice.setText("AI 分析:当前数据模式暂不支持此功能。") return if self._ai_pending: @@ -1991,35 +2011,23 @@ class PrescriptionsPage(QWidget): if token == self._ai_request_token: self._ai_pending = False - def _set_ai_columns(self, enabled: bool) -> None: + def _set_ai_enabled(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 not enabled: + self._ai_statuses.clear() + self._render_ai_statuses() 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, "") + self._render_ai_statuses() def _load_ai_capabilities(self) -> None: self._ai_capability_token += 1 @@ -2054,7 +2062,7 @@ class PrescriptionsPage(QWidget): 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) + self._set_ai_enabled(data.get("enabled") is True) if not self._ai_enabled: self._ai_timer.stop() notice = "AI 分析未启用:暂不生成报告或一致度,请联系管理员启用。" @@ -2090,17 +2098,19 @@ class PrescriptionsPage(QWidget): 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) + state = agreement = tooltip = "" + if self._ai_enabled and self._agreement_visible and batch and not _is_blank_prescription(row): + if batch.get("status") not in (None, "", "blank", "not_generated"): + state = state_text(batch) + agreement = agreement_text(batch) + if state or agreement: + tooltip = status_tooltip(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.setToolTip(tooltip if text else "") item.setData(Qt.ItemDataRole.AccessibleTextRole, text) if changed: self.table.resizeRowsToContents() @@ -2111,14 +2121,22 @@ class PrescriptionsPage(QWidget): 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._set_ai_enabled(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 _ai_cell_clicked(self, item: QTableWidgetItem) -> None: + if item.column() in (11, 12) and item.text(): + self._open_ai_report() + + def _can_view_ai_report(self, row: Any) -> bool: + return (not _is_blank_prescription(row) and can_open_issued_ai(self.permissions) + and callable(getattr(self.repository, "list_prescription_ai_reports", None))) + def _open_ai_report(self) -> None: row = self._selected() - if _is_blank_prescription(row): + if not self._can_view_ai_report(row): return value = _int(first_value(row, "id", "prescription_id"), 0) if value > 0: @@ -2139,12 +2157,10 @@ class PrescriptionsPage(QWidget): 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)) + menu.addSeparator() + action = menu.addAction("AI 分析") + action.setEnabled(self._can_view_ai_report(row)) + 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)) @@ -2189,11 +2205,7 @@ class PrescriptionsPage(QWidget): 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)) - ) + ai_available = self._can_view_ai_report(row) self.ai_report_button.setVisible(ai_available) self.ai_report_button.setEnabled(ai_available) self.patch_button.setEnabled(active and can_patch_patient(row)) @@ -2250,6 +2262,17 @@ class PrescriptionsPage(QWidget): def _selected(self) -> Any: return self.table.current_data() + def selected_prescription(self) -> dict[str, Any]: + """Return the highlighted source record, including raw API fields such as patient_id.""" + return _row_mapping(self._selected()) + + def _publish_selected_prescription(self) -> None: + # InfiniteList emits once after restoring the selection by record ID. + record = self.selected_prescription() + if record != self._published_prescription: + self._published_prescription = record + self.selected_prescription_changed.emit(dict(record)) + def _get_prescription(self, prescription_id: int) -> Any: method = self.repository.get_prescription return method(prescription_id) diff --git a/app/src/doctor_workstation/ui/pages/reception.py b/app/src/doctor_workstation/ui/pages/reception.py index 2098c22dc..f1dd79b81 100755 --- a/app/src/doctor_workstation/ui/pages/reception.py +++ b/app/src/doctor_workstation/ui/pages/reception.py @@ -4349,6 +4349,9 @@ class ReceptionPage(QWidget): 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.cockpit_view.ai_model_selected.connect(self.select_cockpit_ai_model) + self.cockpit_view.open_ai_report_requested.connect(self._open_ai_analysis_dialog) + self.cockpit_view.open_ai_consult_requested.connect(self._open_ai_consult) self.view_mode_stack.addWidget(self.cockpit_view) root.addWidget(self.view_mode_stack, 1) diff --git a/app/src/doctor_workstation/ui/prescription_patient_sheet.py b/app/src/doctor_workstation/ui/prescription_patient_sheet.py new file mode 100644 index 000000000..bb833b8ba --- /dev/null +++ b/app/src/doctor_workstation/ui/prescription_patient_sheet.py @@ -0,0 +1,186 @@ +"""Read saved clinical reports for the patient highlighted in the prescription table.""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, replace +from typing import Any + +from PySide6.QtCore import QObject, Signal + +from .dialogs.prescription_ai import can_open_diagnosis_ai_report +from .pages.reception import AI_ANALYSIS_MODELS, _normalize_patient_report, _patient_report_rows +from .viewmodels.cockpit_vm import ObsidianAuroraVM, derive_cockpit_snapshot +from .widgets import friendly_error, has_permission, run_async + + +def _id(value: Any) -> int: + try: + return max(0, int(value or 0)) + except (TypeError, ValueError): + return 0 + + +@dataclass(frozen=True) +class _ReportOwner: + patient_id: int + diagnosis_id: int + name: str + + +def _read_reports( + repository: Any, permissions: Any, owner: _ReportOwner +) -> tuple[_ReportOwner, list[dict], str, str]: + patient_read = has_permission(permissions, "tcm.diagnosis/patientAiReports") + visit_read = can_open_diagnosis_ai_report(permissions) + visit_id = owner.diagnosis_id + if ( + not owner.patient_id + and visit_id + and patient_read + and has_permission(permissions, "tcm.diagnosis/readonlyDetail") + ): + detail = repository.get_diagnosis_detail(visit_id, readonly=True) + visit = detail.get("diagnosis", detail) + if not isinstance(visit, Mapping) or _id(visit.get("id")) != visit_id: + raise ValueError("返回的诊单与所选处方不匹配。") + owner = replace( + owner, + patient_id=_id(visit.get("patient_id")), + name=owner.name or str(visit.get("patient_name") or ""), + ) + + if owner.patient_id and patient_read: + payload = repository.list_patient_ai_reports(owner.patient_id) + reports = _patient_report_rows(payload, expected_patient_id=owner.patient_id) + if reports is None: + raise ValueError("返回的报告无法核实患者归属或内容。") + if reports or not (visit_id and visit_read): + return owner, reports, "missing", "" + + if visit_id and visit_read: + payload = repository.list_diagnosis_ai_reports(visit_id) + if _id(payload.get("diagnosis_id")) != visit_id or ( + owner.patient_id + and payload.get("patient_id") + and _id(payload["patient_id"]) != owner.patient_id + ): + raise ValueError("返回的报告与所选诊单不匹配。") + reports = [] + for row in payload["reports"]: + if ( + not isinstance(row, Mapping) + or ("diagnosis_id" in row and _id(row["diagnosis_id"]) != visit_id) + or ( + owner.patient_id + and row.get("patient_id") + and _id(row["patient_id"]) != owner.patient_id + ) + ): + raise ValueError("无法核实诊单报告的归属。") + structured = row.get("report") + if isinstance(structured, Mapping): + # Visit reports call these sections 主治方向 and 用药与复核提醒. + row = dict(row) + if structured.get("main_indications"): + row.setdefault("treatment_advice", structured["main_indications"]) + if structured.get("cautions"): + row.setdefault("risk_assessment", structured["cautions"]) + normalized = _normalize_patient_report(row) + if normalized is None: + raise ValueError("诊单报告内容不完整。") + reports.append(normalized) + owner = replace(owner, name=owner.name or str(payload.get("patient_name") or "")) + return owner, reports, "missing", "" + return owner, [], "permission", "当前账号无法读取这张处方关联的病历报告。" + + +class PrescriptionPatientSheet(QObject): + changed = Signal() + + def __init__(self, repository: Any, permissions: Any, parent: QObject) -> None: + super().__init__(parent) + self.repository = repository + self.permissions = permissions + self.model = "qwen" + self.selection: tuple[int, _ReportOwner] | None = None + self.owner = _ReportOwner(0, 0, "") + self.histories: dict[str, list[dict]] = {} + self.state = "missing" + self.message = "" + self._generation = 0 + + def select(self, row: Mapping[str, Any], *, force: bool = False) -> None: + owner = _ReportOwner( + _id(row.get("patient_id")), + _id(row.get("diagnosis_id")), + str(row.get("patient_name") or "").strip(), + ) + selection = (_id(row.get("id")), owner) if row else None + if self.selection == selection and not force: + return + self._generation += 1 + generation = self._generation + self.selection = selection + self.owner = owner + self.histories = {} + self.state = "reading" if owner.patient_id or owner.diagnosis_id else "missing" + self.message = "正在读取已保存的病历报告。" + if self.state == "missing": + self.message = "这张处方没有关联患者档案或诊单。" if row else "请先选择一条处方。" + self.changed.emit() + if self.state != "reading": + return + + def loaded(result: tuple[_ReportOwner, list[dict], str, str]) -> None: + if generation != self._generation: + return + self.owner, rows, self.state, self.message = result + for report in rows: + self.histories.setdefault(report["model_key"], []).append(report) + self.changed.emit() + + def failed(error: Exception) -> None: + if generation == self._generation: + self.state = "error" + self.message = friendly_error(error) + self.changed.emit() + + run_async( + _read_reports, + self.repository, + self.permissions, + owner, + on_success=loaded, + on_error=failed, + ) + + def select_model(self, model: str) -> None: + if model in AI_ANALYSIS_MODELS and self.model != model: + self.model = model + self.changed.emit() + + def model_states(self) -> dict[str, str]: + return { + key: "success" if self.histories.get(key) else self.state for key in AI_ANALYSIS_MODELS + } + + def view_model(self) -> ObsidianAuroraVM: + owner = self.owner + reports = self.histories.get(self.model) + aurora = derive_cockpit_snapshot( + patient={"id": owner.patient_id, "patient_name": owner.name}, + diagnosis={"id": owner.diagnosis_id}, + ai_payload=reports[0] if reports else None, + ai_state=self.model_states()[self.model], + ai_message=self.message, + active_ai_model=self.model, + ).aurora + # The table supplies identity and reports, not the six clinical intake dimensions. + return replace( + aurora, + gauge_value="—", + gauge_unit="", + gauge_ratio=0, + gauge_tooltip="处方列表未载入完整病历,无法统计病历实采完备度。", + ) diff --git a/app/src/doctor_workstation/ui/shell_spatial.py b/app/src/doctor_workstation/ui/shell_spatial.py index 6a0323ad5..5df5533c0 100644 --- a/app/src/doctor_workstation/ui/shell_spatial.py +++ b/app/src/doctor_workstation/ui/shell_spatial.py @@ -5,8 +5,9 @@ from __future__ import annotations from collections.abc import Callable from functools import wraps from typing import Any +from urllib.parse import quote -from PySide6.QtCore import QPointF, QRectF, QSize, Qt, QTimer, Signal +from PySide6.QtCore import QPointF, QRectF, QSettings, QSize, Qt, QTimer, Signal from PySide6.QtGui import ( QColor, QFont, @@ -42,22 +43,26 @@ from .chat_notifications import ( ChatNotificationCenter, ) from .command_palette import CommandEntry, CommandPaletteDialog -from .dialogs.ai_consult import can_open_ai_consult, present_ai_consult +from .dialogs.ai_consult import AiConsultDialog, 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 .prescription_patient_sheet import PrescriptionPatientSheet from .reception_style import heading_family from .shell import ( _SHELL_MINIMUM_SIZE, _bounded_initial_window_size, _resolve_navigation, ) +from .sortable_navigation import SortableNavigationBar from .spatial_wings import SpatialWingManager from .state import PatientContextStore, PatientSnapshot from .viewmodels import derive_cockpit_snapshot +from .visuals.ai_report_wing import ClinicalAiReportWingPanel from .visuals.aurora_sheet import CollapsibleObsidianSheet +from .visuals.cockpit_layout import COCKPIT_PRESET_SUITES from .widgets import EmptyState, first_value, get_value, has_permission, show_toast _SPATIAL_NAV_LABELS = { @@ -139,6 +144,11 @@ QPushButton#SpatialAiNavPill[activeSheet="true"] { border-color: #0E6F5C; color: #FFFFFF; } +QPushButton#SpatialNavPill:pressed, QPushButton#SpatialAiNavPill:pressed { + background-color: #D9EEE5; + color: #104F40; + border: 1px solid #6FA894; +} QFrame#SpatialSearchCapsule { background-color: #FFFFFF; border: 1px solid #E1ECE8; @@ -411,11 +421,16 @@ class SpatialShellWindow(QMainWindow): 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.patient_context_store.cockpit_mode_changed.connect(self._sync_reception_header) 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._rx_sheet = PrescriptionPatientSheet(repository, self.permissions, self) + self._rx_sheet.changed.connect(self._render_prescription_sheet) + self._rx_report_panel: ClinicalAiReportWingPanel | None = None + self._reception_aurora = derive_cockpit_snapshot().aurora self._activation_page: QWidget | None = None self._activation_generation = 0 self._activation_refreshed = False @@ -477,7 +492,7 @@ class SpatialShellWindow(QMainWindow): 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) + self.ai_bottom_sheet.set_view_model(self._reception_aurora) stage_layout.addWidget(self.ai_bottom_sheet) self.right_wing_dock = QWidget(self.wing_splitter) @@ -507,6 +522,7 @@ class SpatialShellWindow(QMainWindow): # Auto-collapse the bottom obsidian sheet when a docked wing opens so the cockpit stays airy if visible and self.wing_manager.mode == "docked" and self.ai_bottom_sheet.is_expanded: self.set_ai_bottom_sheet_expanded(False) + self._sync_suite_island_visibility() def _prewarm_wing_surfaces(self) -> None: """Warm up heavy wing panels on idle after startup so the first click opens in < 15ms.""" @@ -555,13 +571,17 @@ class SpatialShellWindow(QMainWindow): layout.addStretch(1) # Center Floating Pill Navigation Island (Zero-sidebar centerpiece, never compressed!) - self.nav_island = QFrame(bar) + user_id = first_value(self.current_user, "id", "user_id") + account = first_value(self.current_user, "account", "username", default="") + profile = f"id-{user_id}" if user_id else f"account-{account}" + settings_key = f"navigation/{quote(profile, safe='')}/order" + self.nav_island = SortableNavigationBar( + QSettings("ZhenYangTang", "DoctorWorkstation"), settings_key, bar + ) self.nav_island.setObjectName("SpatialPillNavIsland") self.nav_island.setFixedHeight(44) self.nav_island.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) - self.nav_layout = QHBoxLayout(self.nav_island) - self.nav_layout.setContentsMargins(5, 3, 5, 3) - self.nav_layout.setSpacing(3) + self.nav_layout = self.nav_island.row layout.addWidget(self.nav_island) # Separate AI Syndrome Assistant Pill inside island with guaranteed room @@ -707,8 +727,12 @@ class SpatialShellWindow(QMainWindow): title_col.setContentsMargins(0, 0, 0, 0) title_col.setSpacing(2) self.breadcrumb_label = QLabel("中医糖代谢专科 / 线上联合门诊 / 全息接诊单元", hero) + self.breadcrumb_label.setMinimumWidth(1) self.breadcrumb_label.setStyleSheet("color: #768C88; font-size: 11px; background: transparent;") - title_col.addWidget(self.breadcrumb_label) + breadcrumb_row = QHBoxLayout() + breadcrumb_row.setSpacing(8) + breadcrumb_row.addWidget(self.breadcrumb_label) + title_col.addLayout(breadcrumb_row) self.hero_title_label = QLabel("全息辨证接诊舱", hero) h_font = QFont(heading_family()) @@ -716,7 +740,78 @@ class SpatialShellWindow(QMainWindow): 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) + title_row = QHBoxLayout() + title_row.setContentsMargins(0, 0, 0, 0) + title_row.setSpacing(10) + title_row.addWidget(self.hero_title_label) + + self.classic_reception_button = QPushButton("原版接诊台", hero) + self.classic_reception_button.setToolTip("进入接诊队列和患者详情") + self.classic_reception_button.clicked.connect(self._open_classic_reception) + + # Quick 1-Click 4-Suite Switcher Island right beside the Cockpit Hero Title + self.cockpit_suite_island = QFrame(hero) + self.cockpit_suite_island.setObjectName("SubHeroSuiteIsland") + self.cockpit_suite_island.setStyleSheet( + "QFrame#SubHeroSuiteIsland {" + " background-color: #FFFFFF; border: 1px solid #D7E5E0; border-radius: 14px; }" + "QPushButton#SubHeroSuitePill {" + " min-height: 24px; max-height: 24px; padding: 0 9px; border-radius: 12px;" + " border: 0; background: transparent; color: #4A6460; font-size: 11px; font-weight: 600; }" + "QPushButton#SubHeroSuitePill:hover { color: #0E6F5C; background: #EAF5F1; }" + "QPushButton#SubHeroSuitePill:checked { background-color: #111918; color: #FFFFFF; }" + ) + si_row = QHBoxLayout(self.cockpit_suite_island) + si_row.setContentsMargins(3, 2, 3, 2) + si_row.setSpacing(2) + self._subhero_suite_buttons: dict[str, QPushButton] = {} + for s_spec in COCKPIT_PRESET_SUITES: + s_btn = QPushButton(s_spec.short_title, self.cockpit_suite_island) + s_btn.setObjectName("SubHeroSuitePill") + s_btn.setCheckable(True) + s_btn.setCursor(Qt.CursorShape.PointingHandCursor) + s_btn.setToolTip(f"切换卡片套系 · {s_spec.title}:{s_spec.description}") + s_btn.clicked.connect(lambda _c=False, sk=s_spec.key: self._apply_cockpit_suite(sk)) + si_row.addWidget(s_btn) + self._subhero_suite_buttons[s_spec.key] = s_btn + + self._subhero_custom_suite_btn = QPushButton("我的方案", self.cockpit_suite_island) + self._subhero_custom_suite_btn.setObjectName("SubHeroSuitePill") + self._subhero_custom_suite_btn.setCheckable(True) + self._subhero_custom_suite_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self._subhero_custom_suite_btn.setToolTip("切换到您保存的自定义卡片组合方案") + self._subhero_custom_suite_btn.clicked.connect(lambda: self._apply_cockpit_suite("custom")) + self._subhero_custom_suite_btn.hide() + si_row.addWidget(self._subhero_custom_suite_btn) + self._subhero_suite_buttons["custom"] = self._subhero_custom_suite_btn + self.cockpit_suite_island.hide() + + self.cockpit_layout_button = QPushButton("布局编排", hero) + self.cockpit_layout_button.setCheckable(True) + self.cockpit_layout_button.setIcon(icons.icon("layers", "#0E6F5C", 14)) + self.cockpit_layout_button.setIconSize(QSize(14, 14)) + self.cockpit_layout_button.setToolTip( + "打开 14 卡临床组件库、切换 4 套工作台套系、自由增删换卡或拖拽排序" + ) + action_style = ( + "QPushButton {" + " min-height: 28px; max-height: 28px; padding: 0 12px; border-radius: 14px;" + " background-color: #FFFFFF; border: 1px solid #D5E4DF;" + " color: #19312E; font-size: 11.5px; font-weight: 600; }" + "QPushButton:hover { background-color: #E7F4F0; border-color: #8FCBB9; color: #0E6F5C; }" + "QPushButton:checked { background-color: #0E6F5C; border-color: #0E6F5C; color: #FFFFFF; }" + ) + self.cockpit_layout_button.clicked.connect(self._toggle_cockpit_layout_studio) + for button in (self.classic_reception_button, self.cockpit_layout_button): + button.setStyleSheet(action_style) + button.setCursor(Qt.CursorShape.PointingHandCursor) + button.hide() + self.classic_reception_button.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) + breadcrumb_row.addWidget(self.classic_reception_button, 0, Qt.AlignmentFlag.AlignVCenter) + title_row.addWidget(self.cockpit_suite_island, 0, Qt.AlignmentFlag.AlignVCenter) + title_row.addWidget(self.cockpit_layout_button, 0, Qt.AlignmentFlag.AlignVCenter) + + title_col.addLayout(title_row) layout.addLayout(title_col) layout.addStretch(1) @@ -796,6 +891,14 @@ class SpatialShellWindow(QMainWindow): 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 item.key == "prescriptions": + page.selected_prescription_changed.connect(self._on_prescription_selected) + cockpit_v = getattr(page, "cockpit_view", None) + if cockpit_v is not None and hasattr(cockpit_v, "layout_state_changed"): + cockpit_v.layout_state_changed.connect(self._on_cockpit_layout_state_changed) + self._on_cockpit_layout_state_changed( + cockpit_v.layout_state, cockpit_v.is_layout_edit_mode + ) if hasattr(page, "video_requested"): page.video_requested.connect(lambda payload: self.video_requested.emit(payload)) @@ -813,13 +916,14 @@ class SpatialShellWindow(QMainWindow): 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) + buttons = self.nav_buttons.copy() + if self._can_ai_assistant: + buttons["ai_assistant"] = self.ai_nav_button + self.nav_island.set_buttons(buttons) if first_button is None: denied = EmptyState("暂无可用工作区", "当前账号没有医生工作站页面权限,请联系管理员调整授权。") @@ -837,11 +941,11 @@ class SpatialShellWindow(QMainWindow): 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): + for index in range(self.nav_layout.count()): QShortcut( - QKeySequence(f"Alt+{idx}"), + QKeySequence(f"Alt+{index + 1}"), self, - activated=lambda key=item.key: self.navigate(key), + activated=lambda i=index: self.nav_layout.itemAt(i).widget().click(), ) def _install_activation_refresh_gate(self, page: QWidget) -> None: @@ -906,7 +1010,20 @@ class SpatialShellWindow(QMainWindow): ) self.breadcrumb_label.setText(crumb) self.hero_title_label.setText(hero_title) + leaving_prescriptions = self._active_page_key == "prescriptions" self._active_page_key = key + if key == "prescriptions": + if isinstance(self.wing_manager.active_widget, (ClinicalAiReportWingPanel, AiConsultDialog)): + self.wing_manager.close_wing() + self._rx_sheet.select(page.selected_prescription(), force=True) + elif leaving_prescriptions: + if self._prescription_wing_is_open(): + self.wing_manager.close_wing() + self._rx_sheet.select({}) + self.ai_bottom_sheet.set_view_model(self._reception_aurora) + self.ai_bottom_sheet.consult_button.setEnabled(True) + self.ai_bottom_sheet.report_button.setEnabled(True) + self._sync_reception_header(self.patient_context_store.cockpit_mode) self._ensure_activation_refresh(page, gen) if self.isVisible(): QTimer.singleShot(0, lambda p=page, g=gen: self._finish_activation(p, g)) @@ -922,6 +1039,8 @@ class SpatialShellWindow(QMainWindow): def refresh_current_page(self) -> None: page = self.stack.currentWidget() + if self._active_page_key == "prescriptions": + self._rx_sheet.select(page.selected_prescription(), force=True) refresh = getattr(page, "refresh", None) if callable(refresh): refresh() @@ -929,6 +1048,77 @@ class SpatialShellWindow(QMainWindow): def toggle_ai_bottom_sheet(self) -> None: self.ai_bottom_sheet.toggle_expanded() + def _open_classic_reception(self) -> None: + page = self.pages.get("reception") + if page is not None: + page.set_workspace_mode("chart") + + def _sync_suite_island_visibility(self) -> None: + if not hasattr(self, "cockpit_suite_island"): + return + show_cockpit = ( + self._active_page_key == "reception" + and self.patient_context_store.cockpit_mode == "cockpit" + ) + docked_wing_open = bool( + hasattr(self, "wing_manager") + and self.wing_manager.is_open + and self.wing_manager.mode == "docked" + ) + wide_enough = (self.width() >= 1180 or not self.isVisible()) and ( + not docked_wing_open or self.width() >= 1760 + ) + self.cockpit_suite_island.setVisible(show_cockpit and wide_enough) + + def _apply_cockpit_suite(self, suite_key: str) -> None: + rec_page = self.pages.get("reception") + cockpit_v = getattr(rec_page, "cockpit_view", None) + if cockpit_v is not None and hasattr(cockpit_v, "apply_suite"): + cockpit_v.apply_suite(suite_key) + + def _sync_reception_header(self, mode: str) -> None: + is_reception = self._active_page_key == "reception" + show_actions = is_reception and mode == "cockpit" + self.classic_reception_button.setVisible(show_actions) + self.cockpit_layout_button.setVisible(show_actions) + self._sync_suite_island_visibility() + if is_reception: + self.hero_title_label.setText( + _SPATIAL_HERO_TITLES["reception"][1] if show_actions else "原版接诊台" + ) + + def _toggle_cockpit_layout_studio(self) -> None: + rec_page = self.pages.get("reception") + cockpit_v = getattr(rec_page, "cockpit_view", None) + if cockpit_v is not None and hasattr(cockpit_v, "toggle_layout_edit_mode"): + cockpit_v.toggle_layout_edit_mode() + + def _on_cockpit_layout_state_changed(self, state: Any, edit_mode: bool) -> None: + if hasattr(self, "_subhero_suite_buttons"): + active_suite = str(getattr(state, "active_suite", "holistic") or "holistic") + has_custom = bool(getattr(state, "has_custom_suite", False)) + if hasattr(self, "_subhero_custom_suite_btn"): + self._subhero_custom_suite_btn.setVisible(has_custom or active_suite == "custom") + for sk, sb in self._subhero_suite_buttons.items(): + sb.blockSignals(True) + sb.setChecked(sk == active_suite) + sb.blockSignals(False) + if not hasattr(self, "cockpit_layout_button"): + return + removed_count = len(getattr(state, "removed_cards", ()) or ()) + self.cockpit_layout_button.blockSignals(True) + self.cockpit_layout_button.setChecked(bool(edit_mode)) + self.cockpit_layout_button.blockSignals(False) + self.cockpit_layout_button.setIcon( + icons.icon("check" if edit_mode else "layers", "#FFFFFF" if edit_mode else "#0E6F5C", 14) + ) + if edit_mode: + self.cockpit_layout_button.setText("完成布局") + elif removed_count > 0: + self.cockpit_layout_button.setText(f"布局编排 · 已隐{removed_count}") + else: + self.cockpit_layout_button.setText("布局编排") + def set_ai_bottom_sheet_expanded(self, expanded: bool) -> None: self.ai_bottom_sheet.set_expanded(bool(expanded)) @@ -950,9 +1140,57 @@ class SpatialShellWindow(QMainWindow): 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) + self._reception_aurora = aurora + if self._active_page_key != "prescriptions": + self.ai_bottom_sheet.set_view_model(aurora) + + def _on_prescription_selected(self, row: dict) -> None: + if self._active_page_key == "prescriptions": + self._rx_sheet.select(row) + + def _prescription_wing_is_open(self) -> bool: + widget = self.wing_manager.active_widget + return widget is not None and ( + widget is self._rx_report_panel or bool(widget.property("prescriptionSheetPatient")) + ) + + def _render_prescription_sheet(self) -> None: + if self._active_page_key != "prescriptions": + return + sheet = self._rx_sheet + owner = sheet.owner + can_chat = owner.diagnosis_id > 0 and self._can_ai_assistant + self.ai_bottom_sheet.set_view_model(sheet.view_model()) + self.ai_bottom_sheet.report_button.setEnabled(bool(owner.patient_id or owner.diagnosis_id)) + self.ai_bottom_sheet.consult_button.setEnabled(can_chat) + if not self._prescription_wing_is_open(): + return + active = self.wing_manager.active_widget + if active is not self._rx_report_panel: + if active.diagnosis_id != owner.diagnosis_id or ( + active.patient_id and owner.patient_id and active.patient_id != owner.patient_id + ) or active.property("prescriptionSheetPatient") != (owner.name or "姓名未记录"): + self.wing_manager.close_wing() + return + if not sheet.selection: + self.wing_manager.close_wing() + return + self.wing_manager.update_header(subtitle=owner.name or "姓名未记录") + states = sheet.model_states() + self._rx_report_panel.set_report_context( + histories=sheet.histories, + model_states=states, + model_messages=dict.fromkeys(states, sheet.message or "当前患者暂无该模型的已保存报告。"), + active_model=sheet.model, + patient_name=owner.name, + can_regenerate=False, + ) + self._rx_report_panel.consult_btn.setEnabled(can_chat) def _on_sheet_model_selected(self, model_key: str) -> None: + if self._active_page_key == "prescriptions": + self._rx_sheet.select_model(model_key) + return rec_page = self.pages.get("reception") select_model = getattr(rec_page, "select_cockpit_ai_model", None) if callable(select_model): @@ -990,6 +1228,8 @@ class SpatialShellWindow(QMainWindow): def _sync_open_wing_with_patient(self, snapshot: PatientSnapshot) -> None: """Keep any open Right/Left Wing or Sidecar synchronized when switching patients.""" + if self._prescription_wing_is_open(): + return self.wing_manager.update_header(subtitle=snapshot.patient_name) active_w = self.wing_manager.active_widget if active_w is None: @@ -1110,6 +1350,21 @@ class SpatialShellWindow(QMainWindow): ) def _open_active_patient_ai_report(self) -> None: + if self._active_page_key == "prescriptions": + owner = self._rx_sheet.owner + if not (owner.patient_id or owner.diagnosis_id): + return + if self._rx_report_panel is None: + panel = ClinicalAiReportWingPanel(self) + panel.model_selected.connect(self._rx_sheet.select_model) + panel.open_ai_consult_requested.connect(self._open_active_patient_ai_consult) + self._rx_report_panel = panel + self.wing_manager.present_widget( + self._rx_report_panel, title="AI 循证诊断报告", subtitle=owner.name or "姓名未记录", + icon_kind="ai", preferred_width=540, + ) + self._render_prescription_sheet() + return rec_page = self.pages.get("reception") open_wing = getattr(rec_page, "open_ai_report_wing", None) if ( @@ -1121,6 +1376,15 @@ class SpatialShellWindow(QMainWindow): self._open_active_patient_ai_consult() def _open_active_patient_ai_consult(self) -> None: + if self._active_page_key == "prescriptions": + owner = self._rx_sheet.owner + if owner.diagnosis_id and self._can_ai_assistant: + present_ai_consult( + self.repository, self.permissions, self, diagnosis_id=owner.diagnosis_id, + patient_id=owner.patient_id, seed={"patient_name": owner.name}, + source_title="已开处方", prescription_patient_name=owner.name or "姓名未记录", + ) + return snap = self.patient_context_store.current_patient if snap.diagnosis_id > 0 and self._can_ai_assistant: present_ai_consult( @@ -1173,17 +1437,44 @@ class SpatialShellWindow(QMainWindow): 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) + sheet_shortcut = "Ctrl+]" + for idx, key in enumerate(self.nav_island.order, start=1): + if key == "ai_assistant": + sheet_shortcut = f"Alt+{idx} / Ctrl+]" + continue + label = self.page_titles[self.stack.indexOf(self.pages[key])] entries.append( CommandEntry( - key=f"nav:{item.key}", + key=f"nav:{key}", title=f"前往 · {label}", subtitle="切换顶部胶囊空间视图", category="空间导航", - shortcut=f"Alt+{idx}" if idx <= 6 else "", - icon_kind=item.key, - action=lambda k=item.key: self.navigate(k), + shortcut=f"Alt+{idx}", + icon_kind=key, + action=lambda k=key: self.navigate(k), + ) + ) + entries.append( + CommandEntry( + key="act:cockpit_layout", + title="打开 14 卡临床组件库与自由布局工作台", + subtitle="支持 4 套工作台方案、14 张卡片自由增删换卡、拖拽排序与跨度调节", + category="空间导航", + shortcut="", + icon_kind="layers", + action=lambda: (self.navigate("reception"), self._toggle_cockpit_layout_studio()), + ) + ) + for s_spec in COCKPIT_PRESET_SUITES: + entries.append( + CommandEntry( + key=f"act:suite:{s_spec.key}", + title=f"切换接诊总览卡片方案 · {s_spec.title}", + subtitle=s_spec.description, + category="卡片套系", + shortcut="", + icon_kind="reception", + action=lambda sk=s_spec.key: (self.navigate("reception"), self._apply_cockpit_suite(sk)), ) ) entries.append( @@ -1192,7 +1483,7 @@ class SpatialShellWindow(QMainWindow): title="展开 / 收起黑曜极光 AI 分析舱", subtitle="查看三模型循证结论与病历完备度", category="临床智医", - shortcut="Ctrl+]", + shortcut=sheet_shortcut, icon_kind="ai", action=self.toggle_ai_bottom_sheet, ) @@ -1352,9 +1643,11 @@ class SpatialShellWindow(QMainWindow): self.user_menu_button.setText( self._short_user_label if compact_top else self._full_user_label ) + self._sync_suite_island_visibility() def showEvent(self, event: Any) -> None: # noqa: N802 super().showEvent(event) + self._sync_suite_island_visibility() self.chat_notifications.start() page = self.stack.currentWidget() if page is not None and page is self._activation_page: @@ -1364,6 +1657,7 @@ class SpatialShellWindow(QMainWindow): def closeEvent(self, event: Any) -> None: # noqa: N802 self.chat_notifications.stop() self.wing_manager.close_all() + self._rx_sheet.select({}) super().closeEvent(event) if event.isAccepted(): self.close_requested.emit() diff --git a/app/src/doctor_workstation/ui/sortable_navigation.py b/app/src/doctor_workstation/ui/sortable_navigation.py new file mode 100644 index 000000000..c22251e61 --- /dev/null +++ b/app/src/doctor_workstation/ui/sortable_navigation.py @@ -0,0 +1,262 @@ +"""Reorderable row of existing workstation navigation buttons.""" + +from __future__ import annotations + +from PySide6.QtCore import QEvent, QObject, QPoint, QSettings, Qt, QTimer +from PySide6.QtGui import QColor, QKeyEvent, QMouseEvent, QPainter, QPaintEvent, QPolygon +from PySide6.QtWidgets import ( + QApplication, + QFrame, + QGraphicsDropShadowEffect, + QHBoxLayout, + QMenu, + QPushButton, + QWidget, +) + +from . import motion + + +class _InsertionMarker(QWidget): + def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor("#0E6F5C")) + x = self.width() // 2 + bottom = self.height() - 1 + painter.drawRoundedRect(x - 1, 3, 2, bottom - 5, 1, 1) + painter.drawPolygon(QPolygon([QPoint(0, 0), QPoint(2 * x, 0), QPoint(x, 5)])) + painter.drawPolygon( + QPolygon([QPoint(0, bottom), QPoint(2 * x, bottom), QPoint(x, bottom - 5)]) + ) + + +class SortableNavigationBar(QFrame): + def __init__(self, settings: QSettings, settings_key: str, parent: QWidget) -> None: + super().__init__(parent) + self._settings = settings + self._settings_key = settings_key + self.row = QHBoxLayout(self) + self.row.setContentsMargins(5, 3, 5, 3) + self.row.setSpacing(3) + self.buttons: dict[str, QPushButton] = {} + self._source: QPushButton | None = None + self._press_pos = QPoint() + self._dragging = False + self._cancelled_press: QPushButton | None = None + self._hold = QTimer(self) + self._hold.setSingleShot(True) + self._hold.setInterval(160) + self._hold.timeout.connect(self._lift) + + self._origin = QFrame(self) + self._origin.setObjectName("NavDragOrigin") + self._origin.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents) + self._origin.setStyleSheet( + "background: #EAF3EF; border: 1px dashed #75AA9B; border-radius: 17px;" + ) + self._origin.hide() + + self._preview = QPushButton(self) + self._preview.setObjectName("NavDragPreview") + self._preview.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents) + self._preview.setFocusPolicy(Qt.FocusPolicy.NoFocus) + self._preview.setStyleSheet( + "QPushButton#NavDragPreview { background: #E2F4EC; color: #104F40;" + " border: 1px solid #21846A; border-radius: 17px; padding: 0; font-weight: 600; }" + ) + self._shadow = QGraphicsDropShadowEffect(self._preview) + self._shadow.setColor(QColor(14, 66, 52, 100)) + self._shadow.setOffset(0, 2) + self._preview.setGraphicsEffect(self._shadow) + self._preview.hide() + + self._marker = _InsertionMarker(self) + self._marker.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents) + self._marker.hide() + self.window().installEventFilter(self) + + @property + def order(self) -> list[str]: + return [self.row.itemAt(i).widget().property("navKey") for i in range(self.row.count())] + + def _saved_order(self) -> list[str]: + value = self._settings.value(self._settings_key, []) + if not isinstance(value, list): + return [] + return list(dict.fromkeys(key for key in value if isinstance(key, str))) + + def set_buttons(self, buttons: dict[str, QPushButton]) -> None: + self.buttons = buttons + for key, button in buttons.items(): + button.setProperty("navKey", key) + button.setCursor( + Qt.CursorShape.OpenHandCursor + if len(buttons) > 1 + else Qt.CursorShape.PointingHandCursor + ) + button.installEventFilter(self) + button.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + button.customContextMenuRequested.connect(lambda pos, k=key: self._show_menu(k, pos)) + if len(buttons) > 1: + hint = "按住并左右拖动调整导航顺序,右键查看更多操作" + button.setToolTip("\n".join(filter(None, (button.toolTip(), hint)))) + saved = [key for key in self._saved_order() if key in buttons] + self._arrange(list(dict.fromkeys([*saved, *buttons]))) + + def _arrange(self, keys: list[str]) -> None: + for index, key in enumerate(keys): + self.row.insertWidget(index, self.buttons[key]) + for left, right in zip(keys, keys[1:], strict=False): + QWidget.setTabOrder(self.buttons[left], self.buttons[right]) + + def move_button(self, key: str, index: int) -> None: + order = self.order + if key not in order or not 0 <= index < len(order) or order[index] == key: + return + order.remove(key) + order.insert(index, key) + self._arrange(order) + # Keep slots for temporarily unavailable pages when permissions change. + visible = iter(order) + saved = [next(visible) if k in self.buttons else k for k in self._saved_order()] + self._settings.setValue(self._settings_key, [*saved, *visible]) + + def reset_order(self) -> None: + self._settings.remove(self._settings_key) + self._arrange(list(self.buttons)) + + def _show_menu(self, key: str, pos: QPoint) -> None: + button = self.buttons[key] + index = self.row.indexOf(button) + menu = QMenu(button) + menu.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) + left = menu.addAction("向左移动", lambda: self.move_button(key, index - 1)) + right = menu.addAction("向右移动", lambda: self.move_button(key, index + 1)) + left.setEnabled(index > 0) + right.setEnabled(index < self.row.count() - 1) + menu.addSeparator() + reset = menu.addAction("恢复默认顺序", self.reset_order) + reset.setEnabled(self.order != list(self.buttons)) + menu.popup(button.mapToGlobal(pos)) + + def _drop_slot(self, x: int) -> int: + for i in range(self.row.count()): + if x < self.row.itemAt(i).widget().geometry().center().x(): + return i + return self.row.count() + + def _lift(self) -> None: + source = self._source + if source is None: + return + self._hold.stop() + self._origin.setGeometry(source.geometry()) + self._preview.setText(source.text()) + self._preview.setFont(source.font()) + self._preview.setIcon(source.icon()) + self._preview.setIconSize(source.iconSize()) + self._preview.setGeometry(source.geometry().translated(0, -3)) + self._origin.raise_() + self._origin.show() + self._preview.raise_() + self._preview.show() + self._marker.stackUnder(self._preview) + motion.animate(self._shadow, b"blurRadius", 1.0, 7.0, duration=motion.FAST) + + def _preview_drop(self, pos: QPoint) -> None: + inside = self.rect().contains(pos) + self._preview.setVisible(inside) + self._origin.setVisible(inside) + self._marker.setVisible(inside) + if not inside: + return + # Follow the original grab point, even when dragging a wide pill by its edge. + x = self._origin.x() + pos.x() - self._press_pos.x() + self._preview.move(max(0, min(x, self.width() - self._preview.width())), self._preview.y()) + slot = self._drop_slot(pos.x()) + if slot < self.row.count(): + x = self.row.itemAt(slot).widget().geometry().left() - 2 + else: + x = self.row.itemAt(slot - 1).widget().geometry().right() + 1 + self._marker.setGeometry(x - 4, 1, 9, self.height() - 2) + + def _finish_press(self, *, cancel: bool = False) -> None: + source = self._source + if source is None: + return + self._hold.stop() + if self._dragging or cancel: + source.setDown(False) + self._cancelled_press = source if cancel else None + source.setCursor(Qt.CursorShape.OpenHandCursor) + self._origin.hide() + self._preview.hide() + self._marker.hide() + self._source = None + self._dragging = False + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 + if self._source is not None: + if isinstance(event, QKeyEvent) and event.key() == Qt.Key.Key_Escape: + if event.type() == QEvent.Type.ShortcutOverride: + event.accept() + return True + if event.type() == QEvent.Type.KeyPress: + self._finish_press(cancel=True) + return True + if event.type() == QEvent.Type.WindowDeactivate or ( + watched is self._source + and event.type() in (QEvent.Type.Hide, QEvent.Type.UngrabMouse) + ): + self._finish_press(cancel=True) + if not isinstance(watched, QPushButton) or not isinstance(event, QMouseEvent): + return super().eventFilter(watched, event) + pos = self.mapFromGlobal(event.globalPosition().toPoint()) + if ( + event.type() == QEvent.Type.MouseButtonPress + and event.button() == Qt.MouseButton.LeftButton + ): + if self.row.count() < 2: + return False + self._cancelled_press = None + self._source = watched + self._press_pos = pos + watched.setCursor(Qt.CursorShape.ClosedHandCursor) + self._hold.start() + elif watched is self._cancelled_press: + if event.type() == QEvent.Type.MouseButtonRelease: + self._cancelled_press = None + return True + if ( + event.type() == QEvent.Type.MouseMove + and event.buttons() & Qt.MouseButton.LeftButton + ): + return True + elif watched is self._source and event.type() == QEvent.Type.MouseMove: + if event.buttons() & Qt.MouseButton.LeftButton and ( + self._dragging + or (pos - self._press_pos).manhattanLength() >= QApplication.startDragDistance() + ): + if not self._dragging: + self._dragging = True + watched.setDown(False) + if not self._preview.isVisible(): + self._lift() + self._preview_drop(pos) + return True + elif ( + watched is self._source + and event.type() == QEvent.Type.MouseButtonRelease + and event.button() == Qt.MouseButton.LeftButton + ): + dragged = self._dragging + self._finish_press() + if dragged: + if self.rect().contains(pos): + slot = self._drop_slot(pos.x()) + index = slot - 1 if slot > self.row.indexOf(watched) else slot + self.move_button(watched.property("navKey"), index) + return True + return super().eventFilter(watched, event) diff --git a/app/src/doctor_workstation/ui/spatial_wings.py b/app/src/doctor_workstation/ui/spatial_wings.py index a24077874..c585160aa 100644 --- a/app/src/doctor_workstation/ui/spatial_wings.py +++ b/app/src/doctor_workstation/ui/spatial_wings.py @@ -825,6 +825,7 @@ class SpatialWingManager(QObject): self._strip_dialog_chrome_once(dialog, preferred_width=preferred_width) resolved_title = title or dialog.windowTitle().split(" - ")[0].strip() or "临床工作视窗" + subtitle = subtitle or str(dialog.property("prescriptionSheetPatient") or "") if not subtitle: store = getattr(self.shell, "patient_context_store", None) snap = getattr(store, "current_patient", None) diff --git a/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py b/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py index 76eda76e9..5026a915a 100644 --- a/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py +++ b/app/src/doctor_workstation/ui/viewmodels/cockpit_vm.py @@ -14,7 +14,7 @@ from __future__ import annotations import math import re from collections.abc import Mapping, Sequence -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import date, datetime, timedelta from typing import Any @@ -22,6 +22,12 @@ 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": "豆包"} +_SAVED_REPORT_STATES = { + "reading": ("正在读取", "正在读取{section}…"), + "error": ("读取失败", "{section}读取失败。"), + "permission": ("无查看权限", "当前账号无权查看{section}。"), + "missing": ("暂无报告", "暂无已保存的{section}。"), +} def _parse_positive_float(value: Any) -> float | None: @@ -264,6 +270,7 @@ class AuroraCardVM: @dataclass(frozen=True) class ObsidianAuroraVM: has_patient: bool + patient_name: str program_title: str ai_summary_line: str active_model_key: str @@ -277,6 +284,128 @@ class ObsidianAuroraVM: gauge_tooltip: str +@dataclass(frozen=True) +class MetabolicGaugeItem: + label: str + value_text: str + unit: str + target_text: str + ratio: float + tone: str # "emerald" | "coral" | "neutral" + status_badge: str + date_label: str + locus_id: str + + +@dataclass(frozen=True) +class MetabolicPanelVM: + has_patient: bool = False + completeness_value: str = "0/6" + completeness_ratio: float = 0.0 + completeness_caption: str = "待选患者" + missing_dims: tuple[str, ...] = () + metrics: tuple[MetabolicGaugeItem, ...] = () + + +@dataclass(frozen=True) +class FourDiagCellVM: + code: str + title: str + status_text: str + tone: str # "emerald" | "coral" | "gold" | "neutral" + primary_line: str + secondary_line: str + locus_id: str + + +@dataclass(frozen=True) +class TcmFourDiagVM: + has_patient: bool = False + badge_text: str = "待选患者" + syndrome_summary: str = "选择患者后汇总望、闻、问、切实采信息" + cells: tuple[FourDiagCellVM, ...] = () + + +@dataclass(frozen=True) +class SyndromeTagItem: + label: str + value: str + locus_id: str + + +@dataclass(frozen=True) +class SyndromeTagsVM: + has_patient: bool = False + positive_items: tuple[SyndromeTagItem, ...] = () + normal_items: tuple[SyndromeTagItem, ...] = () + missing_items: tuple[SyndromeTagItem, ...] = () + + +@dataclass(frozen=True) +class HerbChipVM: + name: str + dosage_text: str + + +@dataclass(frozen=True) +class PrescriptionCardVM: + has_patient: bool = False + has_rx: bool = False + rx_count: int = 0 + formula_title: str = "等待选择患者" + dose_badge: str = "待选患者" + usage_line: str = "选择患者后展示本诊单电子处方药味组成与煎服医嘱" + principle_text: str = "" + herbs: tuple[HerbChipVM, ...] = () + western_meds_text: str = "" + + +@dataclass(frozen=True) +class SafetyHistoryVM: + has_patient: bool = False + allergy_state: str = "unknown" # "alert" | "safe" | "unknown" + allergy_title: str = "过敏史待加载" + allergy_detail: str = "选择患者后核对药物过敏、合并症与现用降糖药" + diagnosis_course: str = "" + comorbidities: tuple[str, ...] = () + family_history: str = "" + current_meds: str = "" + + +@dataclass(frozen=True) +class LifestyleEntryVM: + date_label: str + category: str # "饮食" | "运动" | "随访" + tone: str # "emerald" | "gold" | "cyan" + summary_text: str + + +@dataclass(frozen=True) +class LifestyleLogVM: + has_patient: bool = False + diet_count: int = 0 + exercise_count: int = 0 + note_count: int = 0 + entries: tuple[LifestyleEntryVM, ...] = () + + +@dataclass(frozen=True) +class NoteEntryVM: + date_label: str + author: str + content: str + media_badge: str = "" + + +@dataclass(frozen=True) +class NotesMediaVM: + has_patient: bool = False + note_count: int = 0 + tongue_count: int = 0 + report_count: int = 0 + entries: tuple[NoteEntryVM, ...] = () + + @dataclass(frozen=True) class CockpitSnapshotVM: has_patient: bool @@ -288,6 +417,13 @@ class CockpitSnapshotVM: twin_tcm: SyndromeTwinVM journey: CareJourneyVM aurora: ObsidianAuroraVM + metabolic_panel: MetabolicPanelVM = field(default_factory=MetabolicPanelVM) + tcm_four_diag: TcmFourDiagVM = field(default_factory=TcmFourDiagVM) + syndrome_tags: SyndromeTagsVM = field(default_factory=SyndromeTagsVM) + rx_card: PrescriptionCardVM = field(default_factory=PrescriptionCardVM) + safety_history: SafetyHistoryVM = field(default_factory=SafetyHistoryVM) + lifestyle_log: LifestyleLogVM = field(default_factory=LifestyleLogVM) + notes_media: NotesMediaVM = field(default_factory=NotesMediaVM) def twin_for_mode(self, mode_key: str) -> SyndromeTwinVM: if mode_key == "organ": @@ -383,6 +519,7 @@ def _build_empty_snapshot(active_ai_model: str = "qwen") -> CockpitSnapshotVM: ), aurora=ObsidianAuroraVM( has_patient=False, + patient_name="", program_title="AI 病历循证分析舱", ai_summary_line="请先选择接诊患者,系统将自动读取该患者已保存的千问 / OpenAI / 豆包病历分析报告", active_model_key=active_ai_model, @@ -457,24 +594,25 @@ def derive_cockpit_snapshot( 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=""), - ), - ) + names = ( + _clean_text(first_value(source, key)) + for source in (appt, diag, pat) + for key in ("patient_name", "name") + ) + raw_name = next( + (name for name in names if name and name not in {"患者", "未命名患者", "未选择患者"}), + "", ) diag_id_val = first_value( - diag, "id", "diagnosis_id", default=first_value(appt, "diagnosis_id", "patient_id", default=0) + diag, "id", "diagnosis_id", default=first_value(appt, "diagnosis_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) + pat_id_val = first_value( + pat, "id", "patient_id", default=first_value(diag, "patient_id", default=first_value(appt, "patient_id")) + ) + has_patient = bool(raw_name) or any( + value not in (None, "", 0, "0") for value in (diag_id_val, appt_id_val, pat_id_val) + ) if not has_patient: return _build_empty_snapshot(active_ai_model) @@ -540,13 +678,18 @@ def derive_cockpit_snapshot( tip = f"{r_date or base_date_short} {r_time} · 空腹血糖 {f_num:g} mmol/L({src_tag})".strip() fasting_points.append((label_short, f_num, tip)) + first_blood_iso = ( + _clean_date_iso(first_value(sorted_blood[0], "record_date", "date", "create_time")) + if sorted_blood + else "" + ) if diag_fasting_num is not None: lbl = base_date_short tip_base = f"{diag_date_str or '建档'} · 病历建档空腹血糖:{diag_fasting_num:g} mmol/L" if not fasting_points: fasting_points.append((lbl, diag_fasting_num, tip_base)) - elif fasting_points[0][0] != lbl and abs(fasting_points[0][1] - diag_fasting_num) > 0.05: - fasting_points.insert(0, (f"{lbl}建档" if len(lbl) <= 5 else lbl, diag_fasting_num, tip_base)) + elif diag_date_str and first_blood_iso and diag_date_str < first_blood_iso: + fasting_points.insert(0, (lbl, diag_fasting_num, tip_base)) # ONLY real recorded measurements — ZERO empty gray placeholder bars! recent_fasting = fasting_points[-8:] @@ -1428,6 +1571,9 @@ def derive_cockpit_snapshot( else "待补采维度:" + "、".join(missing_names) ) + saved_report_state = _SAVED_REPORT_STATES.get(ai_state) + if saved_report_state: + ai_payload = None 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=[]) @@ -1443,7 +1589,16 @@ def derive_cockpit_snapshot( 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): + has_report = bool(ai_payload and (diag_advice or treat_advice or parsed_risks)) + if saved_report_state: + ai_status_txt, message_template = saved_report_state + summary_banner = ai_message or f"{patient_name} · {model_label} · {message_template.format(section='病历分析报告')}" + c1_body, c2_body, c3_body = ( + ai_message or message_template.format(section=section) + for section in ("诊断建议", "治疗建议", "风险评估") + ) + c1_badge = c2_badge = c3_badge = ai_status_txt + elif has_report: ai_status_txt = "已生成" summary_banner = _clip(diag_advice or treat_advice, 62) c1_body = diag_advice or "该模型未返回诊断建议正文。" @@ -1480,6 +1635,7 @@ def derive_cockpit_snapshot( aurora_vm = ObsidianAuroraVM( has_patient=True, + patient_name=raw_name, program_title="AI 病历循证分析舱", ai_summary_line=summary_banner, active_model_key=active_ai_model, @@ -1499,7 +1655,7 @@ def derive_cockpit_snapshot( body_text=c1_body, risk_items=(), foot_left=f"患者:{patient_name}", - foot_right="点击查看全文 ↗", + foot_right="点击查看全文 ↗" if has_report else "", ), AuroraCardVM( kind="treatment", @@ -1510,7 +1666,7 @@ def derive_cockpit_snapshot( body_text=c2_body, risk_items=(), foot_left="仅供临床辅助参考", - foot_right="点击查看全文 ↗", + foot_right="点击查看全文 ↗" if has_report else "", ), AuroraCardVM( kind="risks", @@ -1520,8 +1676,8 @@ def derive_cockpit_snapshot( badge_text=c3_badge, body_text=c3_body, risk_items=tuple(parsed_risks[:4]), - foot_left=f"共 {len(parsed_risks)} 项提示", - foot_right="点击查看全文 ↗", + foot_left=f"共 {len(parsed_risks)} 项提示" if has_report else "风险评估", + foot_right="点击查看全文 ↗" if has_report else "", ), ), gauge_value=f"{filled_count}/6", @@ -1531,6 +1687,350 @@ def derive_cockpit_snapshot( gauge_tooltip=gauge_tip, ) + # ── 6. Extra Specialist Card ViewModels (100% Real Data) ────────────── + # 6A. Metabolic 6-Dimension Target Panel + f_metric = ( + MetabolicGaugeItem( + "空腹血糖", + f"{recent_fasting[-1][1]:g}", + "mmol/L", + "< 7.0", + min(0.96, max(0.18, recent_fasting[-1][1] / 14.0)), + "coral" if recent_fasting[-1][1] >= 7.0 else "emerald", + "偏高" if recent_fasting[-1][1] >= 7.0 else "达标", + recent_fasting[-1][0], + "daily_glucose", + ) + if recent_fasting + else MetabolicGaugeItem("空腹血糖", "未测", "", "< 7.0", 0.0, "neutral", "待补录", "—", "daily_glucose") + ) + p_metric = ( + MetabolicGaugeItem( + "餐后2h血糖", + f"{post_points[-1][1]:g}", + "mmol/L", + "< 11.1", + min(0.96, max(0.18, post_points[-1][1] / 18.0)), + "coral" if post_points[-1][1] >= 11.1 else "emerald", + "偏高" if post_points[-1][1] >= 11.1 else "达标", + post_points[-1][0], + "daily_glucose", + ) + if post_points + else MetabolicGaugeItem("餐后2h血糖", "未测", "", "< 11.1", 0.0, "neutral", "待补录", "—", "daily_glucose") + ) + hb_metric = ( + MetabolicGaugeItem( + "糖化 HbA1c", + f"{hba1c_num:g}", + "%", + "< 7.0%", + min(0.96, max(0.18, hba1c_num / 12.0)), + "coral" if hba1c_num >= 7.0 else "emerald", + "偏高" if hba1c_num >= 7.0 else "达标", + base_date_short, + "vital:hba1c", + ) + if hba1c_num is not None + else MetabolicGaugeItem("糖化 HbA1c", "未测", "", "< 7.0%", 0.0, "neutral", "待补录", "—", "vital:hba1c") + ) + bp_metric = ( + MetabolicGaugeItem( + "动脉血压", + bp_val, + bp_unit, + "< 140/90", + 0.82 if bp_alert else 0.56, + "coral" if bp_alert else "emerald", + "偏高" if bp_alert else "正常", + bp_date.split()[0] if bp_date else base_date_short, + "vital:systolic_pressure", + ) + if bp_val != "—" + else MetabolicGaugeItem( + "动脉血压", "未测", "", "< 140/90", 0.0, "neutral", "待补录", "—", "vital:systolic_pressure" + ) + ) + bmi_metric = ( + MetabolicGaugeItem( + "体质量 BMI", + hw_val, + "kg/m²" if "BMI" in hw_unit else hw_unit, + "18.5–23.9", + 0.80 if hw_alert else 0.54, + "coral" if hw_alert else "emerald", + "超限" if hw_alert else "适中", + base_date_short, + "vital:weight", + ) + if hw_val != "—" + else MetabolicGaugeItem("体质量 BMI", "未测", "", "18.5–23.9", 0.0, "neutral", "待补录", "—", "vital:weight") + ) + metabolic_panel_vm = MetabolicPanelVM( + has_patient=True, + completeness_value=f"{filled_count}/6", + completeness_ratio=max(0.08, min(1.0, filled_count / 6.0)), + completeness_caption="全部实采完备" if not missing_names else f"待补 {len(missing_names)} 维", + missing_dims=tuple(missing_names), + metrics=(f_metric, p_metric, hb_metric, bp_metric, bmi_metric), + ) + + # 6B. TCM Four-Diagnostics 2x2 Matrix (望 / 闻问 / 问 / 切) + wang_present = bool(tongue_real or tongue_img_count or hw_val != "—" or fatty_txt) + wang_p1 = f"舌象:{tongue_real}" if tongue_real else (f"舌苔图:已传 {tongue_img_count} 张" if tongue_img_count else "舌质舌苔尚未录入") + wang_p2 = " · ".join( + p for p in (f"形体 BMI {hw_val}" if hw_val != "—" else "", f"肝脂:{fatty_txt}" if fatty_txt else "", f"舌图 {tongue_img_count} 张" if tongue_img_count and tongue_real else "") if p + ) or "点击进入医生备注上传舌像" + + wen1_present = bool(chief_txt or oral_txt or water_txt or sweat_skin_txt) + wen1_p1 = f"主诉:{_clip(chief_txt, 26)}" if chief_txt else "主诉与现病史暂未填写" + wen1_p2 = " · ".join( + p for p in (f"口干:{oral_txt}" if oral_txt else "", f"饮水:{water_txt}" if water_txt else "", f"汗肤:{sweat_skin_txt}" if sweat_skin_txt else "") if p + ) or "点击补充口渴饮水与汗出问诊" + + wen2_present = bool(diet_c_txt or stool_txt or urine_txt or limb_txt or sleep_txt) + wen2_p1 = " · ".join( + p for p in (f"二便:{stool_txt or '—'}/{urine_txt or '—'}" if (stool_txt or urine_txt) else "", f"饮食:{diet_c_txt}" if diet_c_txt else "") if p + ) or "脾胃饮食与二便尚未采集" + wen2_p2 = " · ".join( + p for p in (f"肢末:{limb_txt}" if limb_txt else "", f"睡眠:{sleep_txt}" if sleep_txt else "", f"眼底:{eye_txt}" if eye_txt else "") if p + ) or "点击补充睡眠、眼底与肢末麻木" + + qie_present = bool(pulse_real or principle_real or diag_title_real) + qie_p1 = f"脉象:{pulse_real}" if pulse_real else (f"临床诊断:{diag_title_real}" if diag_title_real else "切诊脉象尚未录入") + qie_p2 = f"治则:{_clip(principle_real, 26)}" if principle_real else "点击拟定辨证治则与处方意见" + + diag_filled_n = sum(1 for flag in (wang_present, wen1_present, wen2_present, qie_present) if flag) + tcm_four_diag_vm = TcmFourDiagVM( + has_patient=True, + badge_text=f"四诊已采 {diag_filled_n}/4", + syndrome_summary=diag_title_real or principle_real or "点击任意四诊象限直达对应病历字段修订", + cells=( + FourDiagCellVM( + "望", + "望诊 · 舌象与形体", + "已采" if wang_present else "待采", + "emerald" if wang_present else "neutral", + _clip(wang_p1, 28), + _clip(wang_p2, 28), + "tongue_pulse", + ), + FourDiagCellVM( + "闻问", + "主诉 · 口渴与寒热汗出", + "阳性" if z_oral_tone == "coral" else ("已采" if wen1_present else "待采"), + z_oral_tone if wen1_present else "neutral", + _clip(wen1_p1, 28), + _clip(wen1_p2, 28), + "oral_thirst", + ), + FourDiagCellVM( + "问", + "问诊 · 脾胃二便与肢末", + "阳性" if "coral" in {z_abd_tone, z_low_tone, z_head_tone} else ("已采" if wen2_present else "待采"), + "coral" if "coral" in {z_abd_tone, z_low_tone} else ("emerald" if wen2_present else "neutral"), + _clip(wen2_p1, 28), + _clip(wen2_p2, 28), + "kidney_limbs", + ), + FourDiagCellVM( + "切", + "切脉 · 证候与治则方义", + "已拟" if qie_present else "待拟", + "emerald" if qie_present else "gold", + _clip(qie_p1, 28), + _clip(qie_p2, 28), + "rx_principle", + ), + ), + ) + + # 6C. Whole-Body 12-Inquiry Positive / Normal / Unasked Matrix + inquiry_defs = ( + ("主诉", chief_txt, "oral_thirst"), + ("头部感觉", head_txt, "head_eye_sleep"), + ("眼底视物", eye_txt, "head_eye_sleep"), + ("夜眠质量", sleep_txt, "head_eye_sleep"), + ("口干食欲", oral_txt, "oral_thirst"), + ("每日饮水", water_txt, "oral_thirst"), + ("饮食习惯", diet_c_txt, "liver_pancreas_spleen"), + ("体重变化", weight_c_txt, "liver_pancreas_spleen"), + ("脂肪肝", fatty_txt, "liver_pancreas_spleen"), + ("大便性状", stool_txt, "kidney_limbs"), + ("小便频次", urine_txt, "kidney_limbs"), + ("腰肾精力", kidney_txt, "kidney_limbs"), + ("肢末汗肤", limb_txt or sweat_skin_txt, "kidney_limbs"), + ) + pos_tags: list[SyndromeTagItem] = [] + norm_tags: list[SyndromeTagItem] = [] + miss_tags: list[SyndromeTagItem] = [] + for lbl, val, loc in inquiry_defs: + if not val: + miss_tags.append(SyndromeTagItem(lbl, "待问诊", loc)) + elif _is_normal_or_negated(val): + norm_tags.append(SyndromeTagItem(lbl, _clip(val, 12), loc)) + else: + pos_tags.append(SyndromeTagItem(lbl, _clip(val, 14), loc)) + syndrome_tags_vm = SyndromeTagsVM( + has_patient=True, + positive_items=tuple(pos_tags), + normal_items=tuple(norm_tags), + missing_items=tuple(miss_tags), + ) + + # 6D. Prescription & Herb Composition Card + herb_chips: list[HerbChipVM] = [] + rx_formula_title = "本诊单暂未开具中药处方" + rx_dose_badge = "待开方" + rx_usage_line = "点击右上角「拟方/查方」直达处方工作台开具饮片或颗粒方" + if rx_list: + latest_rx = rx_list[0] + rx_sn = _clean_text(first_value(latest_rx, "sn", "prescription_no")) + rx_type = _clean_text(first_value(latest_rx, "prescription_type")) + rx_formula_title = ( + _clean_text(first_value(latest_rx, "prescription_name", "formula_name", "name")) + or (" · ".join(p for p in (f"中药{rx_type}" if rx_type else "电子处方", rx_sn or f"#{first_value(latest_rx, 'id', default=1)}") if p)) + ) + med_d_val = _clean_text( + first_value(latest_rx, "dose_count", "medication_days", "usage_days", "dosage_count") + ) + rx_dose_badge = f"{med_d_val} 剂" if med_d_val and not med_d_val.endswith("剂") else (med_d_val or f"共 {len(rx_list)} 张") + u_way = _clean_text(first_value(latest_rx, "usage_instruction", "usage_way", "usage_time", "usage_notes")) + decoc = "代煎" if str(first_value(latest_rx, "need_decoction", default="")) in {"1", "True", "true"} else "" + t_day = _clean_text(first_value(latest_rx, "times_per_day")) + audit_st = str(first_value(latest_rx, "audit_status", default="")) + audit_tag = "药师已审方" if audit_st == "1" else ("草稿/待审方" if audit_st == "0" else "") + rx_usage_line = " · ".join( + p for p in (rx_type, decoc, f"每日{t_day}次" if t_day else "", u_way, audit_tag) if p + ) or "常规水煎温服 · 遵医嘱复诊调方" + raw_herbs = first_value(latest_rx, "herbs", "medicines", "items", default=[]) or [] + for h in raw_herbs[:12]: + if isinstance(h, Mapping): + h_name = _clean_text(first_value(h, "name", "medicine_name", "herb_name")) + h_amt = _clean_text(first_value(h, "dosage", "amount", "dosage_amount")) + h_unit = _clean_text(first_value(h, "unit", "dosage_unit", default="g")) or "g" + if h_name: + dose_s = f"{h_amt}{h_unit}" if h_amt and not h_amt.endswith(h_unit) else h_amt + herb_chips.append(HerbChipVM(h_name, dose_s or "适量")) + elif has_rx: + rx_formula_title = "已关联有效电子处方" + rx_dose_badge = "已开方" + rx_usage_line = "已存在处方档案 · 点击打开处方分栏核对药味与电子签名状态" + + rx_card_vm = PrescriptionCardVM( + has_patient=True, + has_rx=has_rx, + rx_count=len(rx_list) or (1 if has_rx else 0), + formula_title=rx_formula_title, + dose_badge=rx_dose_badge, + usage_line=_clip(rx_usage_line, 44), + principle_text=_clip(principle_real, 42) if principle_real else "", + herbs=tuple(herb_chips), + western_meds_text=_clip(meds_full, 38) if meds_full else "暂未录入在用降糖西药 / 胰岛素", + ) + + # 6E. Allergy Alert & Comorbidity Safety Card + if allergy_alert: + al_state, al_title, al_detail = ("alert", "存在药物/食物过敏史", allergy_txt) + elif allergy_txt: + al_state, al_title, al_detail = ("safe", "已核实无药物过敏", allergy_txt) + else: + al_state, al_title, al_detail = ("unknown", "药物过敏史尚未核实", "开方前请点击核实并记录过敏史") + + comorb_tokens = [ + tok.strip() + for tok in re.split(r"[、,,;;\s]+", past_txt) + if tok.strip() and not _is_normal_or_negated(tok.strip()) + ] + diag_course_line = " · ".join( + p for p in (local_hosp or diag_title_real, f"病程:{course_real or course_early}" if (course_real or course_early) else "") if p + ) or "外院诊断与确切病程待补充" + safety_history_vm = SafetyHistoryVM( + has_patient=True, + allergy_state=al_state, + allergy_title=al_title, + allergy_detail=_clip(al_detail, 36), + diagnosis_course=_clip(diag_course_line, 42), + comorbidities=tuple(comorb_tokens[:8]), + family_history=_clip(family_txt, 34) if family_txt else "暂未记录糖尿病及心脑血管家族史", + current_meds=_clip(meds_full, 38) if meds_full else "暂未记录当前降糖西药或胰岛素方案", + ) + + # 6F. Diet, Exercise & Follow-up Lifestyle Timeline Card + life_raw: list[tuple[str, LifestyleEntryVM]] = [] + for r in diet_rows: + d_iso = _clean_date_iso(first_value(r, "record_date", "date", "create_time")) + meals = [ + f"{label}:{_clip(_clean_text(first_value(r, key, f'{key}_foods')), 10)}" + for key, label in (("breakfast", "早"), ("lunch", "午"), ("dinner", "晚")) + if _clean_text(first_value(r, key, f"{key}_foods")) + ] + if meals: + life_raw.append( + ( + d_iso or "0000-00-00", + LifestyleEntryVM(d_iso[5:] if len(d_iso) >= 10 else base_date_short, "饮食", "emerald", " · ".join(meals)), + ) + ) + for r in exercise_rows: + d_iso = _clean_date_iso(first_value(r, "record_date", "date", "create_time")) + ex_t = _clean_text(first_value(r, "exercise_type")) + dur = _clean_text(first_value(r, "duration")) + if ex_t or dur: + summary_ex = f"{ex_t or '日常运动'} {dur}分钟".strip() if dur and not dur.endswith("分钟") else f"{ex_t} {dur}".strip() + life_raw.append( + ( + d_iso or "0000-00-00", + LifestyleEntryVM(d_iso[5:] if len(d_iso) >= 10 else base_date_short, "运动", "cyan", summary_ex), + ) + ) + for n in tracking_notes or (): + d_iso = _clean_date_iso(first_value(n, "note_date", "record_date", "create_time")) + c_txt = _clean_text(first_value(n, "content", "tracking_content")) + if c_txt: + life_raw.append( + ( + d_iso or "0000-00-00", + LifestyleEntryVM(d_iso[5:] if len(d_iso) >= 10 else base_date_short, "随访", "gold", _clip(c_txt, 32)), + ) + ) + life_sorted = [item for _, item in sorted(life_raw, key=lambda pair: pair[0], reverse=True)[:5]] + lifestyle_log_vm = LifestyleLogVM( + has_patient=True, + diet_count=len(diet_dates), + exercise_count=len(exercise_by_date), + note_count=len(note_by_date), + entries=tuple(life_sorted), + ) + + # 6G. Doctor Notes & Tongue/Report Media Archive Card + note_entries: list[NoteEntryVM] = [] + for n in notes_list[:4]: + nd_iso = _clean_date_iso(first_value(n, "create_time", "update_time", "note_date")) + n_author = _clean_text(first_value(n, "doctor_name", "creator_name", default="接诊医师")) or "接诊医师" + n_body = _clean_text(first_value(n, "content", "remark")) + t_cnt = len(first_value(n, "tongue_images", default=[]) or []) + r_cnt = len(first_value(n, "report_files", default=[]) or []) + m_badge = " · ".join( + p for p in (f"舌图{t_cnt}" if t_cnt else "", f"报告{r_cnt}" if r_cnt else "") if p + ) + if n_body or m_badge: + note_entries.append( + NoteEntryVM( + date_label=nd_iso[5:] if len(nd_iso) >= 10 else base_date_short, + author=n_author, + content=_clip(n_body or "上传了影像/检验附件", 36), + media_badge=m_badge, + ) + ) + notes_media_vm = NotesMediaVM( + has_patient=True, + note_count=len(notes_list), + tongue_count=tongue_img_count, + report_count=report_file_count, + entries=tuple(note_entries), + ) + return CockpitSnapshotVM( has_patient=True, patient_name=patient_name, @@ -1541,4 +2041,11 @@ def derive_cockpit_snapshot( twin_tcm=twin_tcm, journey=journey_vm, aurora=aurora_vm, + metabolic_panel=metabolic_panel_vm, + tcm_four_diag=tcm_four_diag_vm, + syndrome_tags=syndrome_tags_vm, + rx_card=rx_card_vm, + safety_history=safety_history_vm, + lifestyle_log=lifestyle_log_vm, + notes_media=notes_media_vm, ) diff --git a/app/src/doctor_workstation/ui/visuals/ai_report_wing.py b/app/src/doctor_workstation/ui/visuals/ai_report_wing.py index 5d9b65a57..e2dac728b 100644 --- a/app/src/doctor_workstation/ui/visuals/ai_report_wing.py +++ b/app/src/doctor_workstation/ui/visuals/ai_report_wing.py @@ -603,7 +603,13 @@ class ClinicalAiReportWingPanel(QWidget): if snap is None: st = self._states.get(self._active_model, "missing") msg = self._messages.get(self._active_model, "") - if st == "loading": + if st == "reading": + self.state_title_lbl.setText(f"正在读取 {model_label} 的已保存报告…") + self.state_desc_lbl.setText(msg) + elif st == "permission": + self.state_title_lbl.setText("无查看权限") + self.state_desc_lbl.setText(msg) + elif st == "loading": self.state_title_lbl.setText(f"正在生成 {model_label} 循证分析报告…") self.state_desc_lbl.setText("正在结合患者实采四诊病历、近期血糖与用药信息进行推理,完成后将自动刷新。") elif st == "error": diff --git a/app/src/doctor_workstation/ui/visuals/aurora_sheet.py b/app/src/doctor_workstation/ui/visuals/aurora_sheet.py index db02a3724..04af6cad9 100644 --- a/app/src/doctor_workstation/ui/visuals/aurora_sheet.py +++ b/app/src/doctor_workstation/ui/visuals/aurora_sheet.py @@ -16,6 +16,7 @@ from PySide6.QtGui import ( QTextOption, ) from PySide6.QtWidgets import ( + QBoxLayout, QFrame, QHBoxLayout, QLabel, @@ -313,15 +314,20 @@ class CollapsibleObsidianSheet(QWidget): root.setContentsMargins(22, 18, 22, 14) root.setSpacing(10) - top_bar = QHBoxLayout() - top_bar.setContentsMargins(0, 0, 0, 0) - top_bar.setSpacing(10) + self._top_bar = QBoxLayout(QBoxLayout.Direction.LeftToRight) + self._top_bar.setContentsMargins(0, 0, 0, 0) + self._top_bar.setSpacing(10) + heading = QHBoxLayout() + heading.setSpacing(10) + self._top_bar.addLayout(heading, 1) - self.title_label = QLabel("AI 病历循证分析舱", self) + self.title_label = QLabel("AI 病历循证分析舱 · 未选择患者", self) + self.title_label.setTextFormat(Qt.TextFormat.PlainText) + self.title_label.setMinimumWidth(1) self.title_label.setStyleSheet( "color: #F6FAF9; font-size: 15px; font-weight: 600; background: transparent;" ) - top_bar.addWidget(self.title_label) + heading.addWidget(self.title_label) self.summary_label = QLabel("选择患者后自动读取千问 / OpenAI / 豆包实采病历分析报告", self) self.summary_label.setMinimumWidth(0) @@ -329,8 +335,11 @@ class CollapsibleObsidianSheet(QWidget): "color: rgba(220, 234, 231, 185); font-size: 12px; background: transparent;" ) self.summary_label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) - top_bar.addWidget(self.summary_label, 1) + heading.addWidget(self.summary_label, 1) + self._actions = QHBoxLayout() + self._actions.setSpacing(10) + self._top_bar.addLayout(self._actions) self._model_buttons: dict[str, QPushButton] = {} for m_key, m_text in (("qwen", "千问"), ("openai", "OpenAI"), ("doubao", "豆包")): btn = QPushButton(m_text, self) @@ -339,7 +348,7 @@ class CollapsibleObsidianSheet(QWidget): 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._actions.addWidget(btn) self._sync_model_pill_styles("qwen") self.report_button = QPushButton("完整循证报告", self) @@ -351,7 +360,7 @@ class CollapsibleObsidianSheet(QWidget): "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._actions.addWidget(self.report_button) self.consult_button = QPushButton("AI 深度对话", self) self.consult_button.setCursor(Qt.CursorShape.PointingHandCursor) @@ -362,7 +371,7 @@ class CollapsibleObsidianSheet(QWidget): "QPushButton:hover { background: #138770; }" ) self.consult_button.clicked.connect(self.open_ai_consult_requested.emit) - top_bar.addWidget(self.consult_button) + self._actions.addWidget(self.consult_button) self.toggle_button = QPushButton("展开分析舱 ▲", self) self.toggle_button.setCursor(Qt.CursorShape.PointingHandCursor) @@ -373,8 +382,8 @@ class CollapsibleObsidianSheet(QWidget): "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._actions.addWidget(self.toggle_button) + root.addLayout(self._top_bar) self.body_widget = QWidget(self) body_layout = QHBoxLayout(self.body_widget) @@ -463,6 +472,15 @@ class CollapsibleObsidianSheet(QWidget): w = self.width() if w <= 0: return + margins = self.layout().contentsMargins() + available = w - margins.left() - margins.right() + # Keep the patient's full name visible when a docked wing narrows the header. + stacked = available < self.title_label.sizeHint().width() + self._actions.sizeHint().width() + 20 + self._top_bar.setDirection( + QBoxLayout.Direction.TopToBottom if stacked else QBoxLayout.Direction.LeftToRight + ) + extra_height = self.title_label.sizeHint().height() + self._top_bar.spacing() if stacked else 0 + self.setFixedHeight((238 if self._expanded else 64) + extra_height) self.summary_label.setVisible(w >= 720) if hasattr(self, "left_meta_col"): self.left_meta_col.setVisible(w >= 1060) @@ -476,14 +494,15 @@ class CollapsibleObsidianSheet(QWidget): def _apply_expanded_geometry(self) -> None: self.body_widget.setVisible(self._expanded) self.toggle_button.setText("收起分析舱 ▼" if self._expanded else "展开分析舱 ▲") - self.setFixedHeight(238 if self._expanded else 64) self._sync_responsive_columns() self.update() def set_view_model(self, vm: ObsidianAuroraVM) -> None: self._vm = vm self._sync_model_pill_styles(vm.active_model_key) - self.title_label.setText(vm.program_title) + patient_label = f"患者 {vm.patient_name}" if vm.patient_name else "姓名未记录" + self.title_label.setText(f"{vm.program_title} · {patient_label if vm.has_patient else '未选择患者'}") + self._sync_responsive_columns() 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) diff --git a/app/src/doctor_workstation/ui/visuals/cockpit_cards_extra.py b/app/src/doctor_workstation/ui/visuals/cockpit_cards_extra.py new file mode 100644 index 000000000..34f1c8b40 --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/cockpit_cards_extra.py @@ -0,0 +1,1233 @@ +"""Eight additional 100%-real-data specialist Bento cards for Reception Cockpit v5.1.""" + +from __future__ import annotations + +from typing import Any + +from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal +from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen +from PySide6.QtWidgets import ( + QFrame, + QGridLayout, + QHBoxLayout, + QLabel, + QPushButton, + QScrollArea, + QVBoxLayout, + QWidget, +) + +from .. import icons +from ..diagnosis_editors import FlowLayout +from ..reception_style import body_family, heading_family, number_family +from ..viewmodels.cockpit_vm import ( + FourDiagCellVM, + LifestyleLogVM, + MetabolicGaugeItem, + MetabolicPanelVM, + NotesMediaVM, + ObsidianAuroraVM, + PrescriptionCardVM, + SafetyHistoryVM, + SyndromeTagsVM, + TcmFourDiagVM, +) +from ..widgets import clear_layout + +EXTRA_CARDS_QSS = """ +QFrame#CockpitBentoCard { + background-color: #FFFFFF; + border: 1px solid #E3ECE9; + border-radius: 22px; +} +QPushButton#ExtraCardLinkPill { + min-height: 24px; + max-height: 24px; + padding: 0 9px; + border-radius: 12px; + border: 1px solid #DCE8E4; + background-color: #F5F9F8; + color: #164840; + font-size: 11px; + font-weight: 600; +} +QPushButton#ExtraCardLinkPill:hover { + background-color: #E3F3EE; + border-color: #8AC8B8; + color: #0E6F5C; +} +QPushButton#ExtraCardPrimaryPill { + min-height: 26px; + max-height: 26px; + padding: 0 11px; + border-radius: 13px; + border: 0; + background-color: #0E6F5C; + color: #FFFFFF; + font-size: 11px; + font-weight: 600; +} +QPushButton#ExtraCardPrimaryPill:hover { + background-color: #0A5949; +} +QPushButton#InlineAiModelPill { + min-height: 22px; + max-height: 22px; + padding: 0 8px; + border-radius: 11px; + border: 0; + background: transparent; + color: #546E6A; + font-size: 10.5px; + font-weight: 600; +} +QPushButton#InlineAiModelPill:hover { + color: #0E6F5C; + background: rgba(14, 111, 92, 16); +} +QPushButton#InlineAiModelPill:checked { + background-color: #111918; + color: #FFFFFF; +} +""" + + +def _make_card_title(text: str, parent: QWidget) -> QLabel: + lbl = QLabel(text, parent) + f = QFont(heading_family()) + f.setPixelSize(15) + f.setWeight(QFont.Weight.DemiBold) + lbl.setFont(f) + lbl.setStyleSheet("color: #11201E; background: transparent;") + return lbl + + +def _make_tone_badge(text: str, tone: str, parent: QWidget) -> QLabel: + palette = { + "emerald": ("#E5F5EF", "#0E6F5C"), + "coral": ("#FDECE8", "#C84B31"), + "gold": ("#FBF3E2", "#9A6B16"), + "cyan": ("#E6F4F7", "#146374"), + "neutral": ("#EEF3F1", "#617874"), + } + bg, fg = palette.get(tone, palette["neutral"]) + lbl = QLabel(text, parent) + lbl.setAlignment(Qt.AlignmentFlag.AlignCenter) + lbl.setStyleSheet( + f"background-color: {bg}; color: {fg}; border-radius: 10px;" + " padding: 2px 8px; font-size: 10.5px; font-weight: 600;" + ) + return lbl + + +# ── 1. 糖脂代谢六维达标盘 (MetabolicTargetPanelCard) ───────────────────────── + + +class _CompletenessRingWidget(QWidget): + """Double-track jade-emerald radial ring showing 6-dimension clinical record completeness.""" + + clicked = Signal() + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setFixedSize(116, 124) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self._value_text = "0/6" + self._caption = "待选患者" + self._ratio = 0.0 + + def set_data(self, value_text: str, ratio: float, caption: str, tooltip: str) -> None: + self._value_text = value_text + self._ratio = max(0.0, min(1.0, ratio)) + self._caption = caption + self.setToolTip(tooltip) + self.update() + + 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: Any) -> None: # noqa: N802 + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing, True) + cx, cy = self.width() / 2.0, 52.0 + radius = 40.0 + arc_rect = QRectF(cx - radius, cy - radius, radius * 2, radius * 2) + + # Soft inner porcelain disc + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(QColor("#F6FAF8")) + p.drawEllipse(QPointF(cx, cy), radius - 7, radius - 7) + + # Background track + track_pen = QPen(QColor("#E2EDE9"), 7.5, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap) + p.setPen(track_pen) + p.setBrush(Qt.BrushStyle.NoBrush) + p.drawEllipse(arc_rect) + + # Active emerald arc + if self._ratio > 0.01: + fg_color = QColor("#0E6F5C") if self._ratio >= 0.66 else QColor("#248F78") + arc_pen = QPen(fg_color, 7.5, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap) + p.setPen(arc_pen) + span_angle = int(-360 * 16 * self._ratio) + p.drawArc(arc_rect, 90 * 16, span_angle) + + # Center numbers + num_f = QFont(number_family()) + num_f.setPixelSize(20) + num_f.setWeight(QFont.Weight.Bold) + p.setFont(num_f) + p.setPen(QColor("#102220")) + p.drawText(QRectF(0, cy - 16, self.width(), 24), Qt.AlignmentFlag.AlignCenter, self._value_text) + + sub_f = QFont(body_family()) + sub_f.setPixelSize(10) + p.setFont(sub_f) + p.setPen(QColor("#69817D")) + p.drawText(QRectF(0, cy + 5, self.width(), 16), Qt.AlignmentFlag.AlignCenter, "病历完备") + + # Bottom pill + pill_rect = QRectF(8, 101, self.width() - 16, 20) + path = QPainterPath() + path.addRoundedRect(pill_rect, 10, 10) + p.fillPath(path, QColor("#E7F4F0" if self._ratio >= 0.8 else "#F1F6F4")) + pill_f = QFont(body_family()) + pill_f.setPixelSize(10) + pill_f.setWeight(QFont.Weight.DemiBold) + p.setFont(pill_f) + p.setPen(QColor("#0E6F5C" if self._ratio >= 0.8 else "#566E6A")) + p.drawText(pill_rect, Qt.AlignmentFlag.AlignCenter, self._caption) + + +class _MetabolicBarRow(QWidget): + """Single clickable horizontal target gauge row with real value, target, status & date.""" + + clicked = Signal(str) + + def __init__(self, item: MetabolicGaugeItem, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.item = item + self.setFixedHeight(28) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self._hover = False + self.setToolTip( + f"{item.label}:{item.value_text} {item.unit}(控制目标 {item.target_text} · {item.date_label})\n点击跳转对应录入区" + ) + + def enterEvent(self, event: Any) -> None: # noqa: N802 + self._hover = True + self.update() + super().enterEvent(event) + + def leaveEvent(self, event: Any) -> None: # noqa: N802 + self._hover = False + self.update() + super().leaveEvent(event) + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + self.clicked.emit(self.item.locus_id) + event.accept() + return + super().mousePressEvent(event) + + def paintEvent(self, _event: Any) -> None: # noqa: N802 + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing, True) + w, h = self.width(), self.height() + + if self._hover: + bg_path = QPainterPath() + bg_path.addRoundedRect(QRectF(0, 1, w, h - 2), 8, 8) + p.fillPath(bg_path, QColor("#F2F8F6")) + + # 1. Left label + target + lbl_f = QFont(body_family()) + lbl_f.setPixelSize(12) + lbl_f.setWeight(QFont.Weight.DemiBold) + p.setFont(lbl_f) + p.setPen(QColor("#142725")) + p.drawText(QRectF(6, 0, 74, h), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, self.item.label) + + tgt_f = QFont(body_family()) + tgt_f.setPixelSize(10) + p.setFont(tgt_f) + p.setPen(QColor("#809692")) + p.drawText( + QRectF(80, 0, 56, h), + Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, + self.item.target_text, + ) + + # 2. Right value + status + date (wide enough for '126/78 mmHg' without clipping!) + compact_row = w < 380 + right_reserve = 148 if compact_row else 174 + bar_x = 132.0 if compact_row else 140.0 + bar_w = max(28.0, w - bar_x - right_reserve - 8) + bar_y = (h - 8.0) / 2.0 + + track = QPainterPath() + track.addRoundedRect(QRectF(bar_x, bar_y, bar_w, 8.0), 4.0, 4.0) + p.fillPath(track, QColor("#EBF1EF")) + + if self.item.ratio > 0.02: + fill_c = ( + QColor("#DE6B4F") + if self.item.tone == "coral" + else (QColor("#15846C") if self.item.tone == "emerald" else QColor("#9BB0AC")) + ) + fill = QPainterPath() + fill.addRoundedRect(QRectF(bar_x, bar_y, max(10.0, bar_w * self.item.ratio), 8.0), 4.0, 4.0) + p.fillPath(fill, fill_c) + + # Value text + val_x = w - right_reserve + val_w = 72 if compact_row else 96 + val_f = QFont(number_family()) + val_f.setPixelSize(12) + val_f.setWeight(QFont.Weight.DemiBold) + p.setFont(val_f) + p.setPen( + QColor("#C84B31") + if self.item.tone == "coral" + else (QColor("#112321") if self.item.tone == "emerald" else QColor("#859A96")) + ) + disp_v = ( + self.item.value_text + if compact_row and len(self.item.value_text) >= 5 + else f"{self.item.value_text} {self.item.unit}".strip() + ) + p.drawText(QRectF(val_x, 0, val_w, h), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignRight, disp_v) + + # Status badge + badge_rect = QRectF(w - 72, (h - 18) / 2.0, 38, 18) + b_bg, b_fg = ( + ("#FDECE8", "#C84B31") + if self.item.tone == "coral" + else (("#E5F5EF", "#0E6F5C") if self.item.tone == "emerald" else ("#EEF3F1", "#6D837F")) + ) + b_path = QPainterPath() + b_path.addRoundedRect(badge_rect, 9, 9) + p.fillPath(b_path, QColor(b_bg)) + b_f = QFont(body_family()) + b_f.setPixelSize(10) + b_f.setWeight(QFont.Weight.DemiBold) + p.setFont(b_f) + p.setPen(QColor(b_fg)) + p.drawText(badge_rect, Qt.AlignmentFlag.AlignCenter, self.item.status_badge) + + # Date short + p.setFont(tgt_f) + p.setPen(QColor("#7C928E")) + p.drawText(QRectF(w - 32, 0, 30, h), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignRight, self.item.date_label[:5]) + + +class MetabolicTargetPanelCard(QFrame): + """Card 3: 6-dimension completeness radial ring + 5 real metabolic target gauges.""" + + locus_selected = Signal(str) + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("CockpitBentoCard") + self.setStyleSheet(EXTRA_CARDS_QSS) + + root = QVBoxLayout(self) + root.setContentsMargins(16, 13, 16, 13) + root.setSpacing(8) + + head = QHBoxLayout() + head.addWidget(_make_card_title("糖脂代谢六维达标盘", self)) + head.addStretch(1) + self.sub_badge = _make_tone_badge("待选患者", "neutral", self) + head.addWidget(self.sub_badge) + edit_btn = QPushButton("录入体征 ↗", self) + edit_btn.setObjectName("ExtraCardLinkPill") + edit_btn.setCursor(Qt.CursorShape.PointingHandCursor) + edit_btn.clicked.connect(lambda: self.locus_selected.emit("vital:systolic_pressure")) + head.addWidget(edit_btn) + root.addLayout(head) + + body = QHBoxLayout() + body.setContentsMargins(0, 2, 0, 0) + body.setSpacing(14) + + self.ring = _CompletenessRingWidget(self) + self.ring.clicked.connect(lambda: self.locus_selected.emit("summary_capsule")) + body.addWidget(self.ring, 0, Qt.AlignmentFlag.AlignVCenter) + + self.rows_host = QWidget(self) + self.rows_host.setStyleSheet("background: transparent;") + self.rows_layout = QVBoxLayout(self.rows_host) + self.rows_layout.setContentsMargins(0, 0, 0, 0) + self.rows_layout.setSpacing(3) + body.addWidget(self.rows_host, 1) + root.addLayout(body, 1) + + def resizeEvent(self, event: Any) -> None: # noqa: N802 + super().resizeEvent(event) + self.ring.setVisible(self.width() >= 450) + + def set_view_model(self, vm: MetabolicPanelVM) -> None: + clear_layout(self.rows_layout) + if not vm.has_patient: + self.sub_badge.setText("等待患者") + self.ring.set_data("0/6", 0.0, "待选患者", "选择患者后自动计算六维实采完备度") + empty_lbl = QLabel("从门诊接诊队列选择患者后,实时呈现空腹、餐后、糖化、血压与 BMI 靶向达标分布", self.rows_host) + empty_lbl.setWordWrap(True) + empty_lbl.setStyleSheet("color: #6E8480; font-size: 12px;") + self.rows_layout.addWidget(empty_lbl) + return + + abn_cnt = sum(1 for m in vm.metrics if m.tone == "coral") + rec_cnt = sum(1 for m in vm.metrics if m.tone != "neutral") + if abn_cnt > 0: + self.sub_badge.setText(f"超标 {abn_cnt} 项 · 已测 {rec_cnt}/5") + self.sub_badge.setStyleSheet( + "background-color: #FDECE8; color: #C84B31; border-radius: 10px; padding: 2px 8px; font-size: 10.5px; font-weight: 600;" + ) + else: + self.sub_badge.setText(f"已测 {rec_cnt}/5 项") + self.sub_badge.setStyleSheet( + "background-color: #E5F5EF; color: #0E6F5C; border-radius: 10px; padding: 2px 8px; font-size: 10.5px; font-weight: 600;" + ) + tip = "待补维度:" + "、".join(vm.missing_dims) if vm.missing_dims else "六维临床病历均已完备" + self.ring.set_data(vm.completeness_value, vm.completeness_ratio, vm.completeness_caption, tip) + for m in vm.metrics: + row = _MetabolicBarRow(m, self.rows_host) + row.clicked.connect(self.locus_selected.emit) + self.rows_layout.addWidget(row) + + +# ── 2. 望闻问切·四诊矩阵 (TcmFourDiagMatrixCard) ────────────────────────────── + + +class _FourDiagQuadrant(QFrame): + clicked = Signal(str) + + def __init__(self, cell: FourDiagCellVM, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.locus_id = cell.locus_id + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + border_c = "#F0C5BA" if cell.tone == "coral" else ("#CFE5DF" if cell.tone == "emerald" else "#E5ECEA") + bg_c = "#FFFDFC" if cell.tone == "coral" else "#F8FBF9" + self.setStyleSheet( + f"QFrame {{ background-color: {bg_c}; border: 1px solid {border_c}; border-radius: 14px; }}" + "QFrame:hover { border-color: #0E6F5C; background-color: #EFF8F5; }" + ) + + lay = QVBoxLayout(self) + lay.setContentsMargins(11, 9, 11, 9) + lay.setSpacing(4) + + top = QHBoxLayout() + top.setSpacing(6) + seal = QLabel(cell.code, self) + seal.setFixedSize(26 if len(cell.code) == 1 else 34, 22) + seal.setAlignment(Qt.AlignmentFlag.AlignCenter) + seal_bg = "#C84B31" if cell.tone == "coral" else ("#0E6F5C" if cell.tone == "emerald" else "#6E8380") + seal.setStyleSheet( + f"background-color: {seal_bg}; color: #FFFFFF; border-radius: 7px;" + " font-size: 11px; font-weight: 700; border: 0;" + ) + top.addWidget(seal) + + t_lbl = QLabel(cell.title, self) + t_lbl.setStyleSheet("color: #132624; font-size: 12px; font-weight: 600; border: 0; background: transparent;") + top.addWidget(t_lbl, 1) + + st_lbl = _make_tone_badge(cell.status_text, cell.tone, self) + st_lbl.setStyleSheet(st_lbl.styleSheet() + " border: 0;") + top.addWidget(st_lbl) + lay.addLayout(top) + + p1 = QLabel(cell.primary_line, self) + p1.setWordWrap(True) + p1.setStyleSheet("color: #1A302D; font-size: 11.5px; font-weight: 500; border: 0; background: transparent;") + lay.addWidget(p1) + + p2 = QLabel(cell.secondary_line, self) + p2.setStyleSheet("color: #6B827E; font-size: 10.5px; border: 0; background: transparent;") + lay.addWidget(p2) + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + self.clicked.emit(self.locus_id) + event.accept() + return + super().mousePressEvent(event) + + +class TcmFourDiagMatrixCard(QFrame): + """Card 6: Structured 2x2 TCM 望闻问切 clinical workbench.""" + + locus_selected = Signal(str) + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("CockpitBentoCard") + self.setStyleSheet(EXTRA_CARDS_QSS) + + root = QVBoxLayout(self) + root.setContentsMargins(16, 13, 16, 13) + root.setSpacing(8) + + head = QHBoxLayout() + head.addWidget(_make_card_title("望闻问切·四诊矩阵", self)) + head.addStretch(1) + self.badge_lbl = _make_tone_badge("待选患者", "neutral", self) + head.addWidget(self.badge_lbl) + open_btn = QPushButton("四诊录入 ↗", self) + open_btn.setObjectName("ExtraCardLinkPill") + open_btn.setCursor(Qt.CursorShape.PointingHandCursor) + open_btn.clicked.connect(lambda: self.locus_selected.emit("summary_capsule")) + head.addWidget(open_btn) + root.addLayout(head) + + self.grid_host = QWidget(self) + self.grid_host.setStyleSheet("background: transparent;") + self.grid = QGridLayout(self.grid_host) + self.grid.setContentsMargins(0, 0, 0, 0) + self.grid.setHorizontalSpacing(10) + self.grid.setVerticalSpacing(9) + root.addWidget(self.grid_host, 1) + + self.foot_lbl = QLabel("", self) + self.foot_lbl.setStyleSheet("color: #5D7571; font-size: 11px; background: transparent;") + root.addWidget(self.foot_lbl) + + def set_view_model(self, vm: TcmFourDiagVM) -> None: + clear_layout(self.grid) + self.badge_lbl.setText(vm.badge_text) + self.foot_lbl.setText(f"辨证提要:{vm.syndrome_summary}") + if not vm.has_patient or not vm.cells: + placeholder = QLabel("选择接诊患者后,自动按「望舌形 · 闻问寒热 · 问脾胃二便 · 切脉治则」四宫格结构化呈现", self.grid_host) + placeholder.setWordWrap(True) + placeholder.setStyleSheet("color: #6E8480; font-size: 12px;") + self.grid.addWidget(placeholder, 0, 0) + return + for idx, cell in enumerate(vm.cells[:4]): + quad = _FourDiagQuadrant(cell, self.grid_host) + quad.clicked.connect(self.locus_selected.emit) + self.grid.addWidget(quad, idx // 2, idx % 2) + + +# ── 3. 全身十二问诊阳性核查卡 (SyndromePositiveTagsCard) ───────────────────── + + +class _SegmentedTriBar(QWidget): + """3-segment horizontal ratio bar (Positive coral / Normal emerald / Missing slate).""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setFixedHeight(8) + self._counts = (0, 0, 1) + + def set_counts(self, pos_n: int, norm_n: int, miss_n: int) -> None: + self._counts = (pos_n, norm_n, max(0, miss_n)) + self.update() + + def paintEvent(self, _event: Any) -> None: # noqa: N802 + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing, True) + total = sum(self._counts) or 1 + w, h = float(self.width()), float(self.height()) + clip = QPainterPath() + clip.addRoundedRect(QRectF(0, 0, w, h), 4, 4) + p.setClipPath(clip) + + x = 0.0 + for cnt, col in zip(self._counts, ("#DF684C", "#16856C", "#E4ECE9"), strict=False): + if cnt <= 0: + continue + seg_w = w * (cnt / total) + p.fillRect(QRectF(x, 0, seg_w + 0.5, h), QColor(col)) + x += seg_w + + +class SyndromePositiveTagsCard(QFrame): + """Card 7: High-density 12-symptom positive vs normal vs unasked interactive tag matrix.""" + + locus_selected = Signal(str) + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("CockpitBentoCard") + self.setStyleSheet(EXTRA_CARDS_QSS) + + root = QVBoxLayout(self) + root.setContentsMargins(16, 13, 16, 13) + root.setSpacing(7) + + head = QHBoxLayout() + head.addWidget(_make_card_title("十二问诊阳性核查", self)) + head.addStretch(1) + self.summary_badge = _make_tone_badge("待选患者", "neutral", self) + head.addWidget(self.summary_badge) + root.addLayout(head) + + self.tri_bar = _SegmentedTriBar(self) + root.addWidget(self.tri_bar) + + self.scroll = QScrollArea(self) + self.scroll.setWidgetResizable(True) + self.scroll.setFrameShape(QFrame.Shape.NoFrame) + self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.scroll.viewport().setObjectName("SyndromeTagsViewport") + self.scroll.setStyleSheet( + "QScrollArea, QWidget#SyndromeTagsViewport, QWidget#SyndromeTagsHost { background: transparent; border: 0; }" + ) + + self.host = QWidget(self.scroll) + self.host.setObjectName("SyndromeTagsHost") + self.host_layout = QVBoxLayout(self.host) + self.host_layout.setContentsMargins(0, 2, 2, 0) + self.host_layout.setSpacing(6) + self.scroll.setWidget(self.host) + root.addWidget(self.scroll, 1) + + def set_view_model(self, vm: SyndromeTagsVM) -> None: + clear_layout(self.host_layout) + if not vm.has_patient: + self.summary_badge.setText("等待患者") + self.tri_bar.set_counts(0, 0, 1) + lbl = QLabel("选择患者后自动拆解全身十二项专科问诊:突出阳性体征,标明待补问缺口", self.host) + lbl.setWordWrap(True) + lbl.setStyleSheet("color: #6E8480; font-size: 12px;") + self.host_layout.addWidget(lbl) + self.host_layout.addStretch(1) + return + + p_n, n_n, m_n = len(vm.positive_items), len(vm.normal_items), len(vm.missing_items) + self.tri_bar.set_counts(p_n, n_n, m_n) + self.summary_badge.setText(f"阳性 {p_n} · 正常 {n_n} · 待问 {m_n}") + self.summary_badge.setStyleSheet( + f"background-color: {'#FDECE8' if p_n else '#E5F5EF'};" + f" color: {'#C84B31' if p_n else '#0E6F5C'};" + " border-radius: 10px; padding: 2px 8px; font-size: 10.5px; font-weight: 600;" + ) + + groups = ( + ("阳性体征", vm.positive_items, "#FDF1EE", "#F0C3B8", "#B84027"), + ("已核无异常", vm.normal_items, "#EEF8F4", "#CBE6DC", "#0E6F5C"), + ("待补问诊(点击补录)", vm.missing_items, "#F5F8F7", "#DCE6E3", "#647B77"), + ) + for g_title, items, bg, bd, fg in groups: + if not items: + continue + g_lbl = QLabel(f"{g_title}({len(items)})", self.host) + g_lbl.setStyleSheet(f"color: {fg}; font-size: 10.5px; font-weight: 700;") + self.host_layout.addWidget(g_lbl) + + wrap = QWidget(self.host) + flow = FlowLayout(wrap, horizontal_spacing=6, vertical_spacing=5) + for it in items: + txt = f"+ {it.label}" if it.value == "待问诊" else f"{it.label}:{it.value}" + btn = QPushButton(txt, wrap) + btn.setCursor(Qt.CursorShape.PointingHandCursor) + btn.setStyleSheet( + f"QPushButton {{ min-height: 23px; max-height: 23px; padding: 0 8px; border-radius: 11px;" + f" background-color: {bg}; border: 1px solid {bd}; color: {fg}; font-size: 11px; font-weight: 600; }}" + "QPushButton:hover { border-color: #0E6F5C; }" + ) + btn.clicked.connect(lambda _c=False, loc=it.locus_id: self.locus_selected.emit(loc)) + flow.addWidget(btn) + self.host_layout.addWidget(wrap) + self.host_layout.addStretch(1) + + +# ── 4. 电子处方与方药组成卡 (PrescriptionHerbCard) ─────────────────────────── + + +class PrescriptionHerbCard(QFrame): + """Card 8: Active TCM prescription header, apothecary herb dosage grid & western med cross-check.""" + + locus_selected = Signal(str) + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("CockpitBentoCard") + self.setStyleSheet(EXTRA_CARDS_QSS) + + root = QVBoxLayout(self) + root.setContentsMargins(16, 13, 16, 13) + root.setSpacing(8) + + head = QHBoxLayout() + head.addWidget(_make_card_title("电子处方与方药组成", self)) + head.addStretch(1) + self.dose_badge = _make_tone_badge("待选患者", "neutral", self) + head.addWidget(self.dose_badge) + rx_btn = QPushButton("处方工作台 ↗", self) + rx_btn.setObjectName("ExtraCardPrimaryPill") + rx_btn.setCursor(Qt.CursorShape.PointingHandCursor) + rx_btn.clicked.connect(lambda: self.locus_selected.emit("rx_summary")) + head.addWidget(rx_btn) + root.addLayout(head) + + # Formula summary strip + self.formula_box = QFrame(self) + self.formula_box.setStyleSheet( + "QFrame { background-color: #F5FAF8; border: 1px solid #DCEBE6; border-radius: 13px; }" + ) + fb_lay = QVBoxLayout(self.formula_box) + fb_lay.setContentsMargins(12, 8, 12, 8) + fb_lay.setSpacing(2) + self.formula_title_lbl = QLabel("等待选择患者", self.formula_box) + self.formula_title_lbl.setStyleSheet( + "color: #102421; font-size: 13px; font-weight: 700; border: 0; background: transparent;" + ) + fb_lay.addWidget(self.formula_title_lbl) + self.usage_lbl = QLabel("", self.formula_box) + self.usage_lbl.setStyleSheet("color: #5C7671; font-size: 11px; border: 0; background: transparent;") + fb_lay.addWidget(self.usage_lbl) + root.addWidget(self.formula_box) + + # Herbs grid host + self.herbs_host = QWidget(self) + self.herbs_host.setStyleSheet("background: transparent;") + self.herbs_grid = QGridLayout(self.herbs_host) + self.herbs_grid.setContentsMargins(0, 0, 0, 0) + self.herbs_grid.setHorizontalSpacing(7) + self.herbs_grid.setVerticalSpacing(6) + root.addWidget(self.herbs_host, 1) + + # Western meds footer cross-check + self.west_btn = QPushButton("", self) + self.west_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.west_btn.setStyleSheet( + "QPushButton { text-align: left; padding: 5px 10px; border-radius: 10px;" + " background-color: #F6F8F7; border: 1px solid #E4ECE9; color: #4C6561; font-size: 11px; }" + "QPushButton:hover { background-color: #EBF5F2; border-color: #9BCBC0; color: #0E6F5C; }" + ) + self.west_btn.clicked.connect(lambda: self.locus_selected.emit("current_meds")) + root.addWidget(self.west_btn) + + def set_view_model(self, vm: PrescriptionCardVM) -> None: + clear_layout(self.herbs_grid) + self.formula_title_lbl.setText(vm.formula_title) + usage_full = f"{vm.usage_line} · 治则:{vm.principle_text}" if vm.principle_text else vm.usage_line + self.usage_lbl.setText(usage_full) + self.dose_badge.setText(vm.dose_badge) + tone = "emerald" if vm.has_rx else ("gold" if vm.has_patient else "neutral") + bg, fg = ( + ("#E5F5EF", "#0E6F5C") + if tone == "emerald" + else (("#FBF3E2", "#9A6B16") if tone == "gold" else ("#EEF3F1", "#617874")) + ) + self.dose_badge.setStyleSheet( + f"background-color: {bg}; color: {fg}; border-radius: 10px; padding: 2px 8px; font-size: 10.5px; font-weight: 600;" + ) + self.west_btn.setText(f"中西药联用核对:{vm.western_meds_text or '未录入在用降糖西药'}") + + if vm.herbs: + cols = 4 if len(vm.herbs) > 6 else 3 + for idx, h in enumerate(vm.herbs): + slip = QFrame(self.herbs_host) + slip.setStyleSheet( + "QFrame { background-color: #FBFDFC; border: 1px solid #D8E8E2;" + " border-left: 3px solid #0E6F5C; border-radius: 9px; }" + ) + sl = QHBoxLayout(slip) + sl.setContentsMargins(8, 4, 8, 4) + sl.setSpacing(4) + n_lbl = QLabel(h.name, slip) + n_lbl.setStyleSheet("color: #132724; font-size: 11.5px; font-weight: 600; border: 0;") + d_lbl = QLabel(h.dosage_text, slip) + d_lbl.setStyleSheet("color: #0E6F5C; font-size: 11px; font-weight: 700; border: 0;") + sl.addWidget(n_lbl, 1) + sl.addWidget(d_lbl) + self.herbs_grid.addWidget(slip, idx // cols, idx % cols) + else: + empty_msg = ( + "已开具处方(点击右上角「处方工作台 ↗」查看完整饮片明细与电子签章)" + if vm.has_rx + else "当前诊单尚未开具中药处方 · 点击「处方工作台 ↗」选用协定方或辨证加减拟方" + if vm.has_patient + else "选择接诊患者后,此处直接排布本诊单君臣佐使饮片签及剂量" + ) + hint = QLabel(empty_msg, self.herbs_host) + hint.setWordWrap(True) + hint.setStyleSheet("color: #6B827E; font-size: 11.5px; padding: 4px 2px;") + self.herbs_grid.addWidget(hint, 0, 0) + + +# ── 5. AI 循证辨证与风险速览卡 (AiEvidenceBriefCard) ───────────────────────── + + +class AiEvidenceBriefCard(QFrame): + """Card 9: Light-surface desktop AI clinical summary, risk tags & instant model switcher.""" + + ai_model_selected = Signal(str) + open_ai_report_requested = Signal() + open_ai_consult_requested = Signal() + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("CockpitBentoCard") + self.setStyleSheet(EXTRA_CARDS_QSS) + + root = QVBoxLayout(self) + root.setContentsMargins(16, 13, 16, 13) + root.setSpacing(8) + + head = QHBoxLayout() + head.setSpacing(6) + ic = QLabel(self) + ic.setPixmap(icons.pixmap("ai", "#0E6F5C", 16)) + head.addWidget(ic) + head.addWidget(_make_card_title("AI 循证辨证与风险速览", self)) + head.addStretch(1) + + model_bar = QFrame(self) + model_bar.setStyleSheet("QFrame { background: #F1F6F4; border: 1px solid #DFECE8; border-radius: 12px; }") + mb_lay = QHBoxLayout(model_bar) + mb_lay.setContentsMargins(2, 1, 2, 1) + mb_lay.setSpacing(2) + self._model_btns: dict[str, QPushButton] = {} + for mk, ml in (("qwen", "千问"), ("openai", "OpenAI"), ("doubao", "豆包")): + b = QPushButton(ml, model_bar) + b.setObjectName("InlineAiModelPill") + b.setCheckable(True) + b.setCursor(Qt.CursorShape.PointingHandCursor) + b.clicked.connect(lambda _c=False, k=mk: self.ai_model_selected.emit(k)) + mb_lay.addWidget(b) + self._model_btns[mk] = b + head.addWidget(model_bar) + root.addLayout(head) + + # Structured Advice Digest Box + self.digest_box = QFrame(self) + self.digest_box.setStyleSheet( + "QFrame { background-color: #F5FAF8; border: 1px solid #D6E8E2; border-radius: 14px; }" + ) + db_lay = QVBoxLayout(self.digest_box) + db_lay.setContentsMargins(12, 9, 12, 9) + db_lay.setSpacing(4) + self.digest_title = QLabel("辨证核心提要", self.digest_box) + self.digest_title.setStyleSheet("color: #0E6F5C; font-size: 11px; font-weight: 700; border: 0;") + db_lay.addWidget(self.digest_title) + self.digest_body = QLabel("", self.digest_box) + self.digest_body.setWordWrap(True) + self.digest_body.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft) + self.digest_body.setStyleSheet( + "color: #172B28; font-size: 12px; border: 0; background: transparent;" + ) + db_lay.addWidget(self.digest_body) + + self.treat_title = QLabel("治法与用药复核建议", self.digest_box) + self.treat_title.setStyleSheet("color: #2B6258; font-size: 11px; font-weight: 700; border: 0; margin-top: 3px;") + db_lay.addWidget(self.treat_title) + self.treat_body = QLabel("", self.digest_box) + self.treat_body.setWordWrap(True) + self.treat_body.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft) + self.treat_body.setStyleSheet( + "color: #36504C; font-size: 11.5px; border: 0; background: transparent;" + ) + db_lay.addWidget(self.treat_body) + db_lay.addStretch(1) + root.addWidget(self.digest_box, 1) + + # Risk chips flow + self.risk_host = QWidget(self) + self.risk_host.setStyleSheet("background: transparent;") + self.risk_layout = QHBoxLayout(self.risk_host) + self.risk_layout.setContentsMargins(0, 0, 0, 0) + self.risk_layout.setSpacing(6) + root.addWidget(self.risk_host) + + # Bottom Actions + foot = QHBoxLayout() + self.meta_lbl = QLabel("仅供临床辅助参考", self) + self.meta_lbl.setStyleSheet("color: #748B87; font-size: 10.5px;") + foot.addWidget(self.meta_lbl) + foot.addStretch(1) + + rep_btn = QPushButton("完整循证报告 ↗", self) + rep_btn.setObjectName("ExtraCardLinkPill") + rep_btn.setCursor(Qt.CursorShape.PointingHandCursor) + rep_btn.clicked.connect(self.open_ai_report_requested.emit) + foot.addWidget(rep_btn) + + ask_btn = QPushButton("AI 深度追问", self) + ask_btn.setObjectName("ExtraCardPrimaryPill") + ask_btn.setCursor(Qt.CursorShape.PointingHandCursor) + ask_btn.clicked.connect(self.open_ai_consult_requested.emit) + foot.addWidget(ask_btn) + root.addLayout(foot) + + def set_view_model(self, vm: ObsidianAuroraVM) -> None: + for mk, btn in self._model_btns.items(): + btn.setChecked(mk == vm.active_model_key) + + diag_card = vm.cards[0] if vm.cards else None + treat_card = vm.cards[1] if len(vm.cards) > 1 else None + risk_card = vm.cards[2] if len(vm.cards) > 2 else None + status_str = dict(vm.params).get("报告状态", "待加载") + self.digest_title.setText(f"{vm.active_model_label} · 辨证与病机梳理({status_str})") + raw_body = diag_card.body_text if diag_card else vm.ai_summary_line + clean_body = " ".join(raw_body.split()) + if len(clean_body) > 125: + clean_body = f"{clean_body[:124]}…" + self.digest_body.setText(clean_body) + + raw_treat = treat_card.body_text if treat_card else "" + clean_treat = " ".join(raw_treat.split()) + if len(clean_treat) > 110: + clean_treat = f"{clean_treat[:109]}…" + self.treat_title.setVisible(bool(clean_treat)) + self.treat_body.setVisible(bool(clean_treat)) + self.treat_body.setText(clean_treat) + self.meta_lbl.setText(f"病历实采 {vm.gauge_value} · 辅助参考不替代医嘱") + + clear_layout(self.risk_layout) + risks = risk_card.risk_items if risk_card else () + if risks: + for lvl, lbl in risks[:3]: + short_r = lbl if len(lbl) <= 15 else f"{lbl[:14]}…" + tone = "coral" if lvl == "high" else "gold" + prefix = "高危" if lvl == "high" else "关注" + self.risk_layout.addWidget(_make_tone_badge(f"{prefix} · {short_r}", tone, self.risk_host)) + self.risk_layout.addStretch(1) + else: + no_r = QLabel( + "风险分层:暂无已标记高危项(可点击「完整循证报告」生成或核对)" + if vm.has_patient + else "选择患者后自动加载风险分层胶囊", + self.risk_host, + ) + no_r.setStyleSheet("color: #6B827E; font-size: 11px;") + self.risk_layout.addWidget(no_r) + self.risk_layout.addStretch(1) + + +# ── 6. 过敏预警与慢病既往史卡 (SafetyHistoryGuardCard) ─────────────────────── + + +class SafetyHistoryGuardCard(QFrame): + """Card 10: Drug allergy safety shield/alert banner + comorbidities + family & western meds.""" + + locus_selected = Signal(str) + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("CockpitBentoCard") + self.setStyleSheet(EXTRA_CARDS_QSS) + + root = QVBoxLayout(self) + root.setContentsMargins(16, 13, 16, 13) + root.setSpacing(8) + + head = QHBoxLayout() + head.addWidget(_make_card_title("过敏预警与慢病病史", self)) + head.addStretch(1) + edit_btn = QPushButton("核对病史 ↗", self) + edit_btn.setObjectName("ExtraCardLinkPill") + edit_btn.setCursor(Qt.CursorShape.PointingHandCursor) + edit_btn.clicked.connect(lambda: self.locus_selected.emit("past_history")) + head.addWidget(edit_btn) + root.addLayout(head) + + # Prominent Allergy Guard Banner + self.allergy_btn = QPushButton("", self) + self.allergy_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.allergy_btn.clicked.connect(lambda: self.locus_selected.emit("allergy_family")) + root.addWidget(self.allergy_btn) + + # Comorbidity tags container + self.comorb_host = QWidget(self) + self.comorb_host.setStyleSheet("background: transparent;") + self.comorb_layout = QVBoxLayout(self.comorb_host) + self.comorb_layout.setContentsMargins(0, 0, 0, 0) + self.comorb_layout.setSpacing(5) + root.addWidget(self.comorb_host, 1) + + # Course & Family footer + self.course_lbl = QLabel("", self) + self.course_lbl.setStyleSheet("color: #364E4A; font-size: 11px; font-weight: 600;") + root.addWidget(self.course_lbl) + + self.family_lbl = QLabel("", self) + self.family_lbl.setStyleSheet("color: #6B827E; font-size: 10.5px;") + root.addWidget(self.family_lbl) + + def set_view_model(self, vm: SafetyHistoryVM) -> None: + if vm.allergy_state == "alert": + bg, bd, fg = ("#FDECE8", "#EDB1A3", "#B93C24") + ic_name = "alert" + elif vm.allergy_state == "safe": + bg, bd, fg = ("#E9F7F1", "#B7DFCF", "#0E6F5C") + ic_name = "check_circle" + else: + bg, bd, fg = ("#FCF5E5", "#E8D2A6", "#946817") + ic_name = "info" + + self.allergy_btn.setIcon(icons.icon(ic_name, fg, 15)) + self.allergy_btn.setIconSize(QSize(15, 15)) + self.allergy_btn.setText(f" {vm.allergy_title}:{vm.allergy_detail}") + self.allergy_btn.setStyleSheet( + f"QPushButton {{ text-align: left; min-height: 34px; padding: 4px 11px; border-radius: 12px;" + f" background-color: {bg}; border: 1px solid {bd}; color: {fg}; font-size: 11.5px; font-weight: 700; }}" + "QPushButton:hover { border-width: 1.5px; }" + ) + + clear_layout(self.comorb_layout) + c_hdr = QLabel("既往史与合并症标签:", self.comorb_host) + c_hdr.setStyleSheet("color: #5D7571; font-size: 10.5px; font-weight: 600;") + self.comorb_layout.addWidget(c_hdr) + + if vm.comorbidities: + wrap = QWidget(self.comorb_host) + flow = FlowLayout(wrap, horizontal_spacing=6, vertical_spacing=5) + for tag in vm.comorbidities: + pill = QPushButton(tag, wrap) + pill.setCursor(Qt.CursorShape.PointingHandCursor) + pill.setStyleSheet( + "QPushButton { min-height: 23px; max-height: 23px; padding: 0 9px; border-radius: 11px;" + " background-color: #FDF2EE; border: 1px solid #F0C8BE; color: #B4442C; font-size: 11px; font-weight: 600; }" + ) + pill.clicked.connect(lambda: self.locus_selected.emit("past_history")) + flow.addWidget(pill) + self.comorb_layout.addWidget(wrap) + else: + empty_c = QLabel( + "暂未记录特殊合并症(点击右上角「核对病史 ↗」勾选高血压、脂肪肝等)" + if vm.has_patient + else "选择患者后展示合并症胶囊", + self.comorb_host, + ) + empty_c.setWordWrap(True) + empty_c.setStyleSheet("color: #788E8A; font-size: 11px;") + self.comorb_layout.addWidget(empty_c) + self.comorb_layout.addStretch(1) + + self.course_lbl.setText(f"确诊与病程:{vm.diagnosis_course or '待选择患者'}") + self.family_lbl.setText(f"家族史:{vm.family_history or '—'}") + + +# ── 7. 饮食·运动·随访实录卡 (LifestyleInterventionCard) ────────────────────── + + +class LifestyleInterventionCard(QFrame): + """Card 4: Chronological patient diet, exercise & assistant follow-up log.""" + + locus_selected = Signal(str) + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("CockpitBentoCard") + self.setStyleSheet(EXTRA_CARDS_QSS) + + root = QVBoxLayout(self) + root.setContentsMargins(16, 13, 16, 13) + root.setSpacing(8) + + head = QHBoxLayout() + head.addWidget(_make_card_title("饮食·运动·随访实录", self)) + head.addStretch(1) + self.cnt_badge = _make_tone_badge("待选患者", "neutral", self) + head.addWidget(self.cnt_badge) + open_btn = QPushButton("日常记录 ↗", self) + open_btn.setObjectName("ExtraCardLinkPill") + open_btn.setCursor(Qt.CursorShape.PointingHandCursor) + open_btn.clicked.connect(lambda: self.locus_selected.emit("daily_glucose")) + head.addWidget(open_btn) + root.addLayout(head) + + self.list_host = QWidget(self) + self.list_host.setStyleSheet("background: transparent;") + self.list_layout = QVBoxLayout(self.list_host) + self.list_layout.setContentsMargins(0, 0, 0, 0) + self.list_layout.setSpacing(6) + root.addWidget(self.list_host, 1) + + def set_view_model(self, vm: LifestyleLogVM) -> None: + clear_layout(self.list_layout) + if not vm.has_patient: + self.cnt_badge.setText("等待患者") + lbl = QLabel("选择患者后,按时间轴聚合小程序上传的三餐饮食、运动时长与院外随访记录", self.list_host) + lbl.setWordWrap(True) + lbl.setStyleSheet("color: #6E8480; font-size: 12px;") + self.list_layout.addWidget(lbl) + self.list_layout.addStretch(1) + return + + total = vm.diet_count + vm.exercise_count + vm.note_count + self.cnt_badge.setText(f"饮食 {vm.diet_count} · 运动 {vm.exercise_count} · 随访 {vm.note_count}") + self.cnt_badge.setStyleSheet( + f"background-color: {'#E5F5EF' if total else '#EEF3F1'};" + f" color: {'#0E6F5C' if total else '#617874'};" + " border-radius: 10px; padding: 2px 8px; font-size: 10.5px; font-weight: 600;" + ) + + if not vm.entries: + empty_box = QFrame(self.list_host) + empty_box.setStyleSheet( + "QFrame { background: #F7FAF9; border: 1px dashed #CFE0DC; border-radius: 13px; }" + ) + el = QVBoxLayout(empty_box) + el.setContentsMargins(12, 12, 12, 12) + msg = QLabel("近期暂无患者自录三餐饮食、运动或随访打卡记录。\n可点击右上角「日常记录 ↗」补录或通知医助院外跟进。", empty_box) + msg.setWordWrap(True) + msg.setStyleSheet("color: #657D79; font-size: 11.5px; border: 0;") + el.addWidget(msg) + self.list_layout.addWidget(empty_box) + self.list_layout.addStretch(1) + return + + for entry in vm.entries[:4]: + row = QFrame(self.list_host) + row.setStyleSheet( + "QFrame { background-color: #F7FAF9; border: 1px solid #E5EEEB; border-radius: 12px; }" + ) + rl = QHBoxLayout(row) + rl.setContentsMargins(10, 6, 10, 6) + rl.setSpacing(8) + d_lbl = QLabel(entry.date_label, row) + d_lbl.setFixedWidth(40) + d_lbl.setStyleSheet("color: #5E7672; font-size: 11px; font-weight: 700; border: 0;") + rl.addWidget(d_lbl) + + cat = _make_tone_badge(entry.category, entry.tone, row) + cat.setStyleSheet(cat.styleSheet() + " border: 0;") + rl.addWidget(cat) + + s_lbl = QLabel(entry.summary_text, row) + s_lbl.setStyleSheet("color: #162927; font-size: 11.5px; border: 0;") + rl.addWidget(s_lbl, 1) + self.list_layout.addWidget(row) + self.list_layout.addStretch(1) + + +# ── 8. 医嘱手记与舌像附件归档卡 (NotesMediaArchiveCard) ───────────────────── + + +class NotesMediaArchiveCard(QFrame): + """Card 13: Tongue photo & lab report counters + doctor clinical notes timeline.""" + + locus_selected = Signal(str) + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("CockpitBentoCard") + self.setStyleSheet(EXTRA_CARDS_QSS) + + root = QVBoxLayout(self) + root.setContentsMargins(16, 13, 16, 13) + root.setSpacing(8) + + head = QHBoxLayout() + head.addWidget(_make_card_title("医嘱手记与舌像附件", self)) + head.addStretch(1) + add_btn = QPushButton("上传舌像/记笔记 ↗", self) + add_btn.setObjectName("ExtraCardLinkPill") + add_btn.setCursor(Qt.CursorShape.PointingHandCursor) + add_btn.clicked.connect(lambda: self.locus_selected.emit("notes_media")) + head.addWidget(add_btn) + root.addLayout(head) + + # 3 Counter bricks + counters = QHBoxLayout() + counters.setSpacing(8) + self._tongue_val = self._add_counter_tile(counters, "舌苔影像", "picture") + self._report_val = self._add_counter_tile(counters, "检验报告", "report") + self._note_val = self._add_counter_tile(counters, "医生手记", "pencil") + root.addLayout(counters) + + self.notes_host = QWidget(self) + self.notes_host.setStyleSheet("background: transparent;") + self.notes_layout = QVBoxLayout(self.notes_host) + self.notes_layout.setContentsMargins(0, 0, 0, 0) + self.notes_layout.setSpacing(5) + root.addWidget(self.notes_host, 1) + + def _add_counter_tile(self, parent_lay: QHBoxLayout, label: str, icon_name: str) -> QLabel: + box = QFrame(self) + box.setCursor(Qt.CursorShape.PointingHandCursor) + box.setStyleSheet( + "QFrame { background-color: #F5FAF8; border: 1px solid #DFECE8; border-radius: 12px; }" + "QFrame:hover { border-color: #8CC9B9; background-color: #ECF7F3; }" + ) + box.mousePressEvent = lambda e: ( # type: ignore[method-assign] + self.locus_selected.emit("notes_media") + if e.button() == Qt.MouseButton.LeftButton + else None + ) + bl = QHBoxLayout(box) + bl.setContentsMargins(9, 6, 9, 6) + bl.setSpacing(6) + ic = QLabel(box) + ic.setPixmap(icons.pixmap(icon_name, "#0E6F5C", 14)) + ic.setStyleSheet("border: 0; background: transparent;") + bl.addWidget(ic) + + meta = QVBoxLayout() + meta.setContentsMargins(0, 0, 0, 0) + meta.setSpacing(0) + v_lbl = QLabel("0", box) + v_lbl.setStyleSheet("color: #102321; font-size: 13px; font-weight: 700; border: 0;") + t_lbl = QLabel(label, box) + t_lbl.setStyleSheet("color: #6B827E; font-size: 10px; border: 0;") + meta.addWidget(v_lbl) + meta.addWidget(t_lbl) + bl.addLayout(meta, 1) + parent_lay.addWidget(box, 1) + return v_lbl + + def set_view_model(self, vm: NotesMediaVM) -> None: + self._tongue_val.setText(f"{vm.tongue_count} 张" if vm.has_patient else "—") + self._report_val.setText(f"{vm.report_count} 份" if vm.has_patient else "—") + self._note_val.setText(f"{vm.note_count} 条" if vm.has_patient else "—") + + clear_layout(self.notes_layout) + if not vm.has_patient: + lbl = QLabel("选择患者后展示已归档舌苔照片、理化报告单与历次医师门诊手记", self.notes_host) + lbl.setWordWrap(True) + lbl.setStyleSheet("color: #6E8480; font-size: 11.5px;") + self.notes_layout.addWidget(lbl) + self.notes_layout.addStretch(1) + return + + if not vm.entries: + empty = QLabel("本诊单暂无医生备注或舌像附件 · 点击右上角即可上传患者舌苔图或追加接诊手记", self.notes_host) + empty.setWordWrap(True) + empty.setStyleSheet("color: #6D837F; font-size: 11.5px; padding-top: 4px;") + self.notes_layout.addWidget(empty) + self.notes_layout.addStretch(1) + return + + for n in vm.entries[:3]: + row = QFrame(self.notes_host) + row.setStyleSheet( + "QFrame { background: #F7FAF9; border: 1px solid #E5EEEB; border-radius: 11px; }" + ) + rl = QHBoxLayout(row) + rl.setContentsMargins(9, 5, 9, 5) + rl.setSpacing(6) + d_lbl = QLabel(f"{n.date_label} · {n.author}", row) + d_lbl.setStyleSheet("color: #5D7571; font-size: 10.5px; font-weight: 600; border: 0;") + rl.addWidget(d_lbl) + c_lbl = QLabel(n.content, row) + c_lbl.setStyleSheet("color: #162927; font-size: 11px; border: 0;") + rl.addWidget(c_lbl, 1) + if n.media_badge: + rl.addWidget(_make_tone_badge(n.media_badge, "emerald", row)) + self.notes_layout.addWidget(row) + self.notes_layout.addStretch(1) + + +__all__ = [ + "AiEvidenceBriefCard", + "LifestyleInterventionCard", + "MetabolicTargetPanelCard", + "NotesMediaArchiveCard", + "PrescriptionHerbCard", + "SafetyHistoryGuardCard", + "SyndromePositiveTagsCard", + "TcmFourDiagMatrixCard", +] diff --git a/app/src/doctor_workstation/ui/visuals/cockpit_layout.py b/app/src/doctor_workstation/ui/visuals/cockpit_layout.py new file mode 100644 index 000000000..8d215879c --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/cockpit_layout.py @@ -0,0 +1,1487 @@ +"""Modular Bento Card Library, Multi-Suite Presets, Drag-Sort & Persistence for Reception Cockpit.""" + +from __future__ import annotations + +import json +import os +from collections.abc import Callable +from contextlib import suppress +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from PySide6.QtCore import QMimeData, QPoint, QRect, QSize, Qt, Signal +from PySide6.QtGui import ( + QColor, + QDrag, + QDragEnterEvent, + QDragLeaveEvent, + QDropEvent, + QFont, + QMouseEvent, + QPainter, + QPen, +) +from PySide6.QtWidgets import ( + QFrame, + QHBoxLayout, + QLabel, + QMenu, + QPushButton, + QScrollArea, + QVBoxLayout, + QWidget, +) + +from ...config import AppConfig +from .. import icons +from ..reception_style import body_family, heading_family + +MIME_COCKPIT_CARD = "application/x-zyt-cockpit-card" + +CARD_CATEGORIES: tuple[tuple[str, str], ...] = ( + ("all", "全部卡片"), + ("metabolic", "监测指标"), + ("tcm", "四诊辨证"), + ("rx_ai", "方药循证"), + ("workflow", "队列随访"), +) +CATEGORY_LABELS: dict[str, str] = dict(CARD_CATEGORIES) + + +@dataclass(frozen=True) +class CockpitCardSpec: + key: str + title: str + short_title: str + category: str # "metabolic" | "tcm" | "rx_ai" | "workflow" + icon_name: str + default_span: int # out of 12 columns: 4 (1/3), 6 (1/2), 8 (2/3), 12 (full) + min_height: int + description: str + + +COCKPIT_CARD_SPECS: tuple[CockpitCardSpec, ...] = ( + # 1. 监测指标 (Metabolic & Vitals) + CockpitCardSpec( + "fasting", + "空腹血糖监测", + "空腹血糖", + "metabolic", + "chart", + 4, + 168, + "实测空腹血糖柱状序列、7.0 控制线与对应测量日期", + ), + CockpitCardSpec( + "diurnal", + "餐后2h血糖与体征", + "餐后与体征", + "metabolic", + "blood_pressure", + 4, + 214, + "餐后2h血糖区间标尺、日常打卡柱与带日期体征砖块", + ), + CockpitCardSpec( + "metabolic_panel", + "糖脂代谢六维达标盘", + "六维达标盘", + "metabolic", + "trend", + 8, + 204, + "病历六维实采双环 + 空腹/餐后/糖化/血压/BMI 五项靶向达标条", + ), + CockpitCardSpec( + "lifestyle_log", + "饮食·运动·随访实录", + "饮食运动实录", + "metabolic", + "exercise", + 6, + 204, + "聚合小程序三餐食谱、运动时长与医助院外跟踪时间线", + ), + # 2. 四诊辨证 (TCM Four Diagnostics & Syndromes) + CockpitCardSpec( + "twin_stage", + "全身症候与四诊图谱", + "全身症候图谱", + "tcm", + "body", + 6, + 276, + "全息人体三焦/病史/舌脉三态热力图,悬停阅览、点击直达对应病历区", + ), + CockpitCardSpec( + "tcm_four_diag", + "望闻问切·四诊矩阵", + "四诊矩阵", + "tcm", + "consultations", + 6, + 244, + "2×2 中医四诊结构化宫格:望舌形、闻问寒热口渴、问脾胃二便、切脉治则", + ), + CockpitCardSpec( + "syndrome_tags", + "全身十二问诊阳性卡", + "阳性症状核查", + "tcm", + "pulse", + 4, + 228, + "十二项专科问诊自动归类为阳性体征、已核正常与待补问诊胶囊", + ), + # 3. 方药循证 (Prescriptions, Safety & AI Evidence) + CockpitCardSpec( + "rx_herb_card", + "电子处方与方药组成", + "处方与药味", + "rx_ai", + "meds", + 6, + 236, + "本诊单中药处方剂数用法、饮片剂量签网格及现用西药/胰岛素对照", + ), + CockpitCardSpec( + "ai_brief_card", + "AI 循证辨证与风险速览", + "AI辨证速览", + "rx_ai", + "ai", + 6, + 236, + "桌面级千问/OpenAI/豆包模型切换、辨证结论摘要与高危风险分层标签", + ), + CockpitCardSpec( + "safety_history", + "过敏预警与慢病既往史", + "过敏与既往史", + "rx_ai", + "alert", + 4, + 224, + "药物过敏安全盾/高危警示条、外院诊断病程、合并症标签与家族史核对", + ), + # 4. 队列随访 (Outpatient Queue, Notes & Follow-up) + CockpitCardSpec( + "queue", + "门诊接诊队列", + "接诊队列", + "workflow", + "patients", + 4, + 208, + "今日待诊、今日全部、近期挂号与在管诊单四源实时切换队列", + ), + CockpitCardSpec( + "care_team", + "诊疗协作与归档", + "诊疗协作", + "workflow", + "check_circle", + 4, + 170, + "主诊病历修订、通知医助随访与完成门诊闭环核验快捷入口", + ), + CockpitCardSpec( + "notes_media", + "医嘱手记与舌像附件", + "备注与舌像", + "workflow", + "picture", + 4, + 224, + "已传舌苔图与检查报告计数徽章 + 历次医生门诊备注时间线", + ), + CockpitCardSpec( + "journey", + "近14天健康打卡与复诊", + "14天打卡日历", + "workflow", + "calendar", + 12, + 146, + "近14天实测血糖/饮食/运动状态矩阵与复诊药尽提醒", + ), +) + +CARD_SPEC_MAP: dict[str, CockpitCardSpec] = {s.key: s for s in COCKPIT_CARD_SPECS} +ALL_CARD_KEYS: tuple[str, ...] = tuple(s.key for s in COCKPIT_CARD_SPECS) +DEFAULT_CARD_ORDER: tuple[str, ...] = ( + "fasting", + "diurnal", + "twin_stage", + "queue", + "care_team", + "journey", +) + + +@dataclass(frozen=True) +class CockpitSuiteSpec: + key: str + title: str + short_title: str + layout_mode: str + card_keys: tuple[str, ...] + card_spans: dict[str, int] + description: str + + +COCKPIT_PRESET_SUITES: tuple[CockpitSuiteSpec, ...] = ( + CockpitSuiteSpec( + key="holistic", + title="全息综合接诊套", + short_title="全息综合", + layout_mode="classic", + card_keys=("fasting", "diurnal", "twin_stage", "queue", "care_team", "journey"), + card_spans={ + "fasting": 4, + "diurnal": 4, + "twin_stage": 6, + "queue": 4, + "care_team": 4, + "journey": 12, + }, + description="初诊与日常综合门诊:左血糖体征 · 中全身症候图谱 · 右接诊队列与协作 · 底14天打卡日历", + ), + CockpitSuiteSpec( + key="tcm_rx", + title="中医辨证处方套", + short_title="中医处方", + layout_mode="bento_flow", + card_keys=("tcm_four_diag", "rx_herb_card", "syndrome_tags", "safety_history", "notes_media"), + card_spans={ + "tcm_four_diag": 6, + "rx_herb_card": 6, + "syndrome_tags": 4, + "safety_history": 4, + "notes_media": 4, + }, + description="老中医辨证审方专属:望闻问切四诊矩阵 + 电子处方药味签 + 十二问诊阳性核查 + 过敏既往史 + 舌像手记", + ), + CockpitSuiteSpec( + key="metabolic", + title="糖代谢慢病精管套", + short_title="慢病精管", + layout_mode="bento_flow", + card_keys=("metabolic_panel", "fasting", "diurnal", "lifestyle_log", "journey"), + card_spans={ + "metabolic_panel": 8, + "fasting": 4, + "diurnal": 6, + "lifestyle_log": 6, + "journey": 12, + }, + description="糖代谢专科随访:六维靶向达标盘 + 空腹/餐后血糖曲线 + 三餐饮食运动实录 + 14天打卡复诊轴", + ), + CockpitSuiteSpec( + key="rapid_ai", + title="极速叫号·AI循证套", + short_title="AI速诊", + layout_mode="stage_focus", + card_keys=("ai_brief_card", "queue", "care_team", "safety_history", "rx_herb_card", "metabolic_panel"), + card_spans={ + "ai_brief_card": 8, + "queue": 4, + "care_team": 4, + "safety_history": 4, + "rx_herb_card": 4, + "metabolic_panel": 4, + }, + description="高峰复诊快速过号与疑难AI核查:左AI辨证与风险主卡 + 右队列叫号闭环 + 底安全过敏/处方/达标盘", + ), +) +SUITE_SPEC_MAP: dict[str, CockpitSuiteSpec] = {s.key: s for s in COCKPIT_PRESET_SUITES} + +LAYOUT_MODES: tuple[tuple[str, str, str], ...] = ( + ("classic", "经典三栏", "非对称三栏全息舱 + 通栏底坞,支持任意列序互换与空栏自动收拢"), + ("stage_focus", "主图聚焦", "左侧 56% 大幅聚焦核心卡,右侧 44% 紧凑聚合控制与指标卡"), + ("dual_grid", "双列矩阵", "均衡对称 2×N 双列临床看板,通栏卡片自动独占整行"), + ("bento_flow", "自由磁贴", "12 栅格自由流式磁贴,每张卡片可独立切换 1/3 · 1/2 · 2/3 · 通栏宽度"), +) +VALID_LAYOUT_MODES: set[str] = {m[0] for m in LAYOUT_MODES} +VALID_SPANS: tuple[int, ...] = (4, 6, 8, 12) +SPAN_LABELS: dict[int, str] = { + 4: "1/3 窄卡", + 6: "1/2 半宽", + 8: "2/3 宽幅", + 12: "1/1 通栏", +} + + +def _normalize_deck_order(raw: Any) -> list[str]: + seen: list[str] = [] + if isinstance(raw, (list, tuple)): + for item in raw: + k = str(item or "").strip() + if k in CARD_SPEC_MAP and k not in seen: + seen.append(k) + if not seen: + return list(DEFAULT_CARD_ORDER) + return seen + + +def _normalize_hidden(raw: Any, order: list[str]) -> list[str]: + hidden: list[str] = [] + order_set = set(order) + if isinstance(raw, (list, tuple, set)): + for item in raw: + k = str(item or "").strip() + if k in order_set and k not in hidden: + hidden.append(k) + if len(hidden) >= len(order) and order: + hidden = hidden[:-1] + return hidden + + +def _normalize_spans(raw: Any) -> dict[str, int]: + spans = {s.key: s.default_span for s in COCKPIT_CARD_SPECS} + if isinstance(raw, dict): + for k, v in raw.items(): + sk = str(k or "").strip() + try: + iv = int(v) + except (TypeError, ValueError): + continue + if sk in spans and iv in VALID_SPANS: + spans[sk] = iv + return spans + + +@dataclass +class CockpitLayoutState: + """Mutable, serializable multi-suite & 14-card state for the Reception Clinical Cockpit.""" + + active_suite: str = "holistic" + layout_mode: str = "classic" + card_order: list[str] = field(default_factory=lambda: list(DEFAULT_CARD_ORDER)) + hidden_cards: list[str] = field(default_factory=list) + card_spans: dict[str, int] = field( + default_factory=lambda: {s.key: s.default_span for s in COCKPIT_CARD_SPECS} + ) + custom_suite_snapshot: dict[str, Any] | None = None + + @classmethod + def from_dict(cls, data: Any) -> CockpitLayoutState: + if not isinstance(data, dict): + return cls() + suite = str(data.get("active_suite") or "holistic").strip() + if suite not in SUITE_SPEC_MAP and suite != "custom": + suite = "holistic" + mode = str(data.get("layout_mode") or "classic").strip() + if mode not in VALID_LAYOUT_MODES: + mode = "classic" + order = _normalize_deck_order(data.get("card_order")) + hidden = _normalize_hidden(data.get("hidden_cards"), order) + spans = _normalize_spans(data.get("card_spans")) + custom_snap = data.get("custom_suite_snapshot") + if not isinstance(custom_snap, dict): + custom_snap = None + return cls( + active_suite=suite, + layout_mode=mode, + card_order=order, + hidden_cards=hidden, + card_spans=spans, + custom_suite_snapshot=custom_snap, + ) + + def to_dict(self) -> dict[str, Any]: + payload: dict[str, Any] = { + "version": 2, + "active_suite": self.active_suite, + "layout_mode": self.layout_mode, + "card_order": list(self.card_order), + "hidden_cards": list(self.hidden_cards), + "card_spans": dict(self.card_spans), + } + if self.custom_suite_snapshot: + payload["custom_suite_snapshot"] = dict(self.custom_suite_snapshot) + return payload + + @property + def visible_cards(self) -> list[str]: + hidden_set = set(self.hidden_cards) + vis = [k for k in self.card_order if k not in hidden_set] + return vis or [self.card_order[0]] + + @property + def removed_cards(self) -> list[str]: + """Cards removed from the active suite's configured deck.""" + + vis_set = set(self.visible_cards) + return [k for k in self.card_order if k not in vis_set] + + @property + def unplaced_library_cards(self) -> list[str]: + """All cards in the 14-card catalog not currently shown on the canvas.""" + + vis_set = set(self.visible_cards) + return [k for k in ALL_CARD_KEYS if k not in vis_set] + + @property + def has_custom_suite(self) -> bool: + return isinstance(self.custom_suite_snapshot, dict) and bool( + self.custom_suite_snapshot.get("card_order") + ) + + def span_for(self, key: str) -> int: + return self.card_spans.get(key, CARD_SPEC_MAP[key].default_span) + + def apply_suite(self, suite_key: str) -> bool: + if suite_key == "custom": + if not self.has_custom_suite or self.custom_suite_snapshot is None: + return False + snap = self.custom_suite_snapshot + self.active_suite = "custom" + mode = str(snap.get("layout_mode") or "bento_flow") + self.layout_mode = mode if mode in VALID_LAYOUT_MODES else "bento_flow" + self.card_order = _normalize_deck_order(snap.get("card_order")) + self.hidden_cards = _normalize_hidden(snap.get("hidden_cards"), self.card_order) + self.card_spans.update(_normalize_spans(snap.get("card_spans"))) + return True + + spec = SUITE_SPEC_MAP.get(suite_key) + if spec is None: + return False + self.active_suite = spec.key + self.layout_mode = spec.layout_mode + self.card_order = list(spec.card_keys) + self.hidden_cards = [] + for s in COCKPIT_CARD_SPECS: + self.card_spans[s.key] = spec.card_spans.get(s.key, s.default_span) + return True + + def save_as_custom_suite(self) -> None: + self.custom_suite_snapshot = { + "layout_mode": self.layout_mode, + "card_order": list(self.visible_cards), + "hidden_cards": [], + "card_spans": dict(self.card_spans), + } + self.active_suite = "custom" + + def set_layout_mode(self, mode: str) -> bool: + if mode not in VALID_LAYOUT_MODES or mode == self.layout_mode: + return False + self.layout_mode = mode + return True + + def add_card(self, key: str) -> bool: + """Place any card from the 14-card catalog onto the canvas.""" + + if key not in CARD_SPEC_MAP: + return False + if key in self.visible_cards: + return False + if key in self.hidden_cards: + self.hidden_cards = [k for k in self.hidden_cards if k != key] + return True + self.card_order.append(key) + return True + + def remove_card(self, key: str) -> bool: + if key not in CARD_SPEC_MAP or key not in self.visible_cards: + return False + if len(self.visible_cards) <= 1: + return False + if key not in self.hidden_cards: + self.hidden_cards.append(key) + return True + + def restore_card(self, key: str) -> bool: + return self.add_card(key) + + def toggle_card(self, key: str) -> bool: + if key in self.visible_cards: + return self.remove_card(key) + return self.add_card(key) + + def swap_card(self, old_key: str, new_key: str) -> bool: + """Replace `old_key` in-place with `new_key` while preserving slot position & span.""" + + if ( + old_key == new_key + or old_key not in self.visible_cards + or new_key not in CARD_SPEC_MAP + ): + return False + old_span = self.span_for(old_key) + # Ensure new_key is unhidden + self.hidden_cards = [k for k in self.hidden_cards if k != new_key] + if new_key in self.card_order: + # Both exist in card_order -> swap positions, hide old_key if it wasn't visible before + ia = self.card_order.index(old_key) + ib = self.card_order.index(new_key) + self.card_order[ia], self.card_order[ib] = self.card_order[ib], self.card_order[ia] + if old_key not in self.hidden_cards: + self.hidden_cards.append(old_key) + else: + idx = self.card_order.index(old_key) + self.card_order[idx] = new_key + if new_key != "journey" and old_span in VALID_SPANS: + self.card_spans[new_key] = old_span + return True + + def move_card_step(self, key: str, delta: int) -> bool: + vis = self.visible_cards + if key not in vis or len(vis) <= 1: + return False + idx = vis.index(key) + new_idx = max(0, min(len(vis) - 1, idx + delta)) + if new_idx == idx: + return False + partner = vis[new_idx] + ia = self.card_order.index(key) + ib = self.card_order.index(partner) + self.card_order[ia], self.card_order[ib] = self.card_order[ib], self.card_order[ia] + return True + + def reorder_card(self, source_key: str, target_key: str) -> bool: + """Move `source_key` to `target_key`'s position in `card_order`.""" + + if ( + source_key == target_key + or source_key not in self.card_order + or target_key not in self.card_order + ): + return False + src_idx = self.card_order.index(source_key) + tgt_idx = self.card_order.index(target_key) + item = self.card_order.pop(src_idx) + self.card_order.insert(tgt_idx, item) + return True + + def set_card_span(self, key: str, span: int) -> bool: + if key not in CARD_SPEC_MAP or span not in VALID_SPANS: + return False + if self.card_spans.get(key) == span: + return False + self.card_spans[key] = span + return True + + def cycle_card_span(self, key: str) -> int: + cur = self.span_for(key) + nxt = VALID_SPANS[(VALID_SPANS.index(cur) + 1) % len(VALID_SPANS)] + self.card_spans[key] = nxt + return nxt + + def reset_defaults(self) -> None: + custom_keep = self.custom_suite_snapshot + self.apply_suite("holistic") + self.custom_suite_snapshot = custom_keep + + +class CockpitLayoutStore: + """Atomic JSON persistence for CockpitLayoutState.""" + + def __init__(self, storage_path: Path | None = None, *, persist: bool | None = None) -> None: + if persist is None: + persist = os.environ.get("QT_QPA_PLATFORM") != "offscreen" + self._persist = bool(persist) + self._path = storage_path or (AppConfig().config_dir / "cockpit_layout.json") + + def load(self) -> CockpitLayoutState: + if not self._persist: + return CockpitLayoutState() + if not self._path.exists(): + return CockpitLayoutState() + try: + raw = json.loads(self._path.read_text(encoding="utf-8")) + except (OSError, ValueError, TypeError): + return CockpitLayoutState() + return CockpitLayoutState.from_dict(raw) + + def save(self, state: CockpitLayoutState) -> None: + if not self._persist: + return + with suppress(OSError): + self._path.parent.mkdir(parents=True, exist_ok=True) + tmp = self._path.with_suffix(".tmp") + tmp.write_text( + json.dumps(state.to_dict(), ensure_ascii=False, indent=2), + encoding="utf-8", + ) + tmp.replace(self._path) + + +# ── Layout Computation: Convert State -> Nested Rows / Columns Blueprint ──── + + +@dataclass(frozen=True) +class ColumnSlot: + """One column inside a horizontal row, holding 1 or 2 stacked card keys.""" + + card_keys: tuple[str, ...] + stretch: int + card_stretches: tuple[int, ...] = () + + +@dataclass(frozen=True) +class LayoutBand: + """One horizontal row in the Cockpit layout.""" + + columns: tuple[ColumnSlot, ...] + row_stretch: int + + +def compute_layout_bands(state: CockpitLayoutState) -> list[LayoutBand]: + """Compute balanced, zero-gap row/column bands for the active layout mode & card order.""" + + vis = state.visible_cards + if not vis: + return [] + + mode = state.layout_mode + + if mode == "classic": + bands: list[LayoutBand] = [] + pending_pool: list[str] = [] + + def _flush_classic_pool(pool: list[str]) -> None: + if not pool: + return + cols: list[ColumnSlot] = [] + idx = 0 + while idx < len(pool): + k = pool[idx] + sp = state.span_for(k) + if len(cols) >= 3: + # Flush current 3-column band so extra cards start a clean row instead of cramping! + bands.append(LayoutBand(tuple(cols), row_stretch=10 if not bands else 6)) + cols.clear() + if sp >= 6 or (len(cols) == 2 and idx == len(pool) - 1): + stretch = 46 if sp == 6 else (58 if sp >= 8 else 32) + cols.append(ColumnSlot((k,), stretch, (100,))) + idx += 1 + else: + if idx + 1 < len(pool) and state.span_for(pool[idx + 1]) <= 4: + k2 = pool[idx + 1] + s1, s2 = ( + (62, 38) + if k == "queue" + else ((44, 56) if k == "fasting" else (50, 50)) + ) + col_stretch = 28 if "queue" in {k, k2} else 26 + cols.append(ColumnSlot((k, k2), col_stretch, (s1, s2))) + idx += 2 + else: + cols.append(ColumnSlot((k,), 28, (100,))) + idx += 1 + if cols: + bands.append(LayoutBand(tuple(cols), row_stretch=10 if not bands else 6)) + pool.clear() + + for k in vis: + if state.span_for(k) >= 12 and len(vis) > 1: + _flush_classic_pool(pending_pool) + bands.append(LayoutBand((ColumnSlot((k,), 12, (100,)),), row_stretch=0)) + else: + pending_pool.append(k) + _flush_classic_pool(pending_pool) + if bands and all(b.row_stretch == 0 for b in bands): + last = bands[-1] + bands[-1] = LayoutBand(last.columns, row_stretch=10) + return bands + + if mode == "stage_focus": + hero_key = vis[0] + rest = vis[1:] + if not rest: + return [LayoutBand((ColumnSlot((hero_key,), 12, (100,)),), row_stretch=10)] + right_stack = tuple(rest[:2]) + r_stretches = (58, 42) if len(right_stack) == 2 else (100,) + top_band = LayoutBand( + ( + ColumnSlot((hero_key,), 56, (100,)), + ColumnSlot(right_stack, 44, r_stretches), + ), + row_stretch=10, + ) + bottom_rest = rest[2:] + if not bottom_rest: + return [top_band] + result = [top_band] + for chunk_start in range(0, len(bottom_rest), 3): + chunk = bottom_rest[chunk_start : chunk_start + 3] + if len(chunk) == 1 and state.span_for(chunk[0]) >= 12: + result.append(LayoutBand((ColumnSlot((chunk[0],), 12, (100,)),), row_stretch=0)) + else: + col_w = max(1, 12 // len(chunk)) + b_cols = tuple(ColumnSlot((bk,), col_w, (100,)) for bk in chunk) + result.append(LayoutBand(b_cols, row_stretch=6)) + return result + + if mode == "dual_grid": + bands = [] + row_buf: list[str] = [] + for k in vis: + if state.span_for(k) >= 12: + if row_buf: + bands.append( + LayoutBand( + tuple(ColumnSlot((rk,), 6, (100,)) for rk in row_buf), + row_stretch=6, + ) + ) + row_buf.clear() + bands.append( + LayoutBand( + (ColumnSlot((k,), 12, (100,)),), + row_stretch=0 if k == "journey" and len(vis) > 2 else 5, + ) + ) + else: + row_buf.append(k) + if len(row_buf) == 2: + bands.append( + LayoutBand( + ( + ColumnSlot((row_buf[0],), 6, (100,)), + ColumnSlot((row_buf[1],), 6, (100,)), + ), + row_stretch=6, + ) + ) + row_buf.clear() + if row_buf: + bands.append(LayoutBand((ColumnSlot((row_buf[0],), 12, (100,)),), row_stretch=6)) + if bands and all(b.row_stretch == 0 for b in bands): + bands[-1] = LayoutBand(bands[-1].columns, row_stretch=6) + return bands + + # mode == "bento_flow": 12-column free Bento grid honoring each card's exact span (4 / 6 / 8 / 12) + bands = [] + cur_row: list[tuple[str, int]] = [] + cur_sum = 0 + for k in vis: + sp = state.span_for(k) + if cur_row and cur_sum + sp > 12: + bands.append( + LayoutBand( + tuple(ColumnSlot((rk,), rsp, (100,)) for rk, rsp in cur_row), + row_stretch=6, + ) + ) + cur_row = [] + cur_sum = 0 + cur_row.append((k, sp)) + cur_sum += sp + if cur_sum == 12: + is_compact_banner = len(cur_row) == 1 and cur_row[0][0] == "journey" and len(vis) > 2 + bands.append( + LayoutBand( + tuple(ColumnSlot((rk,), rsp, (100,)) for rk, rsp in cur_row), + row_stretch=0 if is_compact_banner else 6, + ) + ) + cur_row = [] + cur_sum = 0 + if cur_row: + bands.append( + LayoutBand( + tuple(ColumnSlot((rk,), rsp, (100,)) for rk, rsp in cur_row), + row_stretch=6, + ) + ) + if bands and all(b.row_stretch == 0 for b in bands): + bands[-1] = LayoutBand(bands[-1].columns, row_stretch=6) + return bands + + +# ── UI Widgets: Per-Card Edit Overlay, Drag-Drop Tile & 2-Row Card Library ── + + +class _CardEditControlBar(QFrame): + """Floating translucent control pill shown on top-right of each card in Edit Mode.""" + + move_left_clicked = Signal() + move_right_clicked = Signal() + span_clicked = Signal() + swap_clicked = Signal(QPoint) + remove_clicked = Signal() + drag_initiated = Signal(QPoint) + + def __init__(self, spec: CockpitCardSpec, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.spec = spec + self.setObjectName("CockpitCardEditBar") + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self._drag_origin: QPoint | None = None + + self.setStyleSheet( + "QFrame#CockpitCardEditBar {" + " background-color: rgba(17, 29, 27, 234);" + " border: 1px solid rgba(134, 212, 192, 145);" + " border-radius: 14px; }" + "QPushButton#CardEditMiniBtn {" + " min-width: 24px; max-width: 24px; min-height: 22px; max-height: 22px;" + " border-radius: 11px; border: 0; background: rgba(255,255,255,22);" + " color: #F1F8F6; font-size: 11px; font-weight: 600; padding: 0; }" + "QPushButton#CardEditMiniBtn:hover { background: #0E6F5C; color: #FFFFFF; }" + "QPushButton#CardEditMiniBtn:disabled { color: rgba(255,255,255,75); background: transparent; }" + "QPushButton#CardEditSpanBtn {" + " min-height: 22px; max-height: 22px; padding: 0 7px;" + " border-radius: 11px; border: 1px solid rgba(158, 218, 202, 95);" + " background: rgba(255,255,255,18); color: #A6ECD8; font-size: 10.5px; font-weight: 600; }" + "QPushButton#CardEditSpanBtn:hover { background: #0E6F5C; color: #FFFFFF; }" + "QPushButton#CardEditSwapBtn {" + " min-height: 22px; max-height: 22px; padding: 0 7px;" + " border-radius: 11px; border: 0; background: rgba(223, 199, 147, 42);" + " color: #F7E4B4; font-size: 10.5px; font-weight: 600; }" + "QPushButton#CardEditSwapBtn:hover { background: #C2963E; color: #FFFFFF; }" + "QPushButton#CardEditRemoveBtn {" + " min-width: 24px; max-width: 24px; min-height: 22px; max-height: 22px;" + " border-radius: 11px; border: 0; background: rgba(224, 96, 76, 55);" + " color: #FFB3A6; font-size: 13px; font-weight: 700; padding: 0; }" + "QPushButton#CardEditRemoveBtn:hover { background: #D9534F; color: #FFFFFF; }" + ) + + row = QHBoxLayout(self) + row.setContentsMargins(9, 3, 5, 3) + row.setSpacing(4) + + self.drag_lbl = QLabel(f":: {spec.short_title}", self) + self.drag_lbl.setCursor(Qt.CursorShape.OpenHandCursor) + self.drag_lbl.setToolTip("按住拖拽至其他卡片上方即可互换/调整顺序") + self.drag_lbl.setStyleSheet( + f"color: #FFFFFF; font-family: '{body_family()}'; font-size: 11px; font-weight: 600; padding-right: 2px;" + ) + row.addWidget(self.drag_lbl) + + self.prev_btn = QPushButton("‹", self) + self.prev_btn.setObjectName("CardEditMiniBtn") + self.prev_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.prev_btn.setToolTip("前移卡片顺序") + self.prev_btn.clicked.connect(self.move_left_clicked.emit) + row.addWidget(self.prev_btn) + + self.next_btn = QPushButton("›", self) + self.next_btn.setObjectName("CardEditMiniBtn") + self.next_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.next_btn.setToolTip("后移卡片顺序") + self.next_btn.clicked.connect(self.move_right_clicked.emit) + row.addWidget(self.next_btn) + + self.span_btn = QPushButton("1/3", self) + self.span_btn.setObjectName("CardEditSpanBtn") + self.span_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.span_btn.setToolTip("点击切换卡片跨度尺寸(1/3 · 1/2 · 2/3 · 通栏)") + self.span_btn.clicked.connect(self.span_clicked.emit) + row.addWidget(self.span_btn) + + self.swap_btn = QPushButton("换卡", self) + self.swap_btn.setObjectName("CardEditSwapBtn") + self.swap_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.swap_btn.setToolTip("将此位置原地替换为卡片库中的其他临床卡片") + self.swap_btn.clicked.connect( + lambda: self.swap_clicked.emit(self.swap_btn.mapToGlobal(QPoint(0, self.swap_btn.height() + 4))) + ) + row.addWidget(self.swap_btn) + + self.remove_btn = QPushButton("×", self) + self.remove_btn.setObjectName("CardEditRemoveBtn") + self.remove_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.remove_btn.setToolTip(f"从当前接诊舱移除「{spec.title}」(可在顶部卡片库随时加回)") + self.remove_btn.clicked.connect(self.remove_clicked.emit) + row.addWidget(self.remove_btn) + + self.adjustSize() + + def sync_controls(self, *, span: int, can_prev: bool, can_next: bool, can_remove: bool) -> None: + short_map = {4: "1/3", 6: "1/2", 8: "2/3", 12: "通栏"} + self.span_btn.setText(short_map.get(span, "1/2")) + self.prev_btn.setEnabled(can_prev) + self.next_btn.setEnabled(can_next) + self.remove_btn.setEnabled(can_remove) + self.adjustSize() + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + child = self.childAt(event.position().toPoint()) + if not isinstance(child, QPushButton): + self._drag_origin = event.position().toPoint() + self.drag_lbl.setCursor(Qt.CursorShape.ClosedHandCursor) + event.accept() + return + super().mousePressEvent(event) + + def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if ( + self._drag_origin is not None + and (event.buttons() & Qt.MouseButton.LeftButton) + and (event.position().toPoint() - self._drag_origin).manhattanLength() >= 8 + ): + origin = self._drag_origin + self._drag_origin = None + self.drag_lbl.setCursor(Qt.CursorShape.OpenHandCursor) + self.drag_initiated.emit(origin) + event.accept() + return + super().mouseMoveEvent(event) + + def mouseReleaseEvent(self, event: QMouseEvent) -> None: # noqa: N802 + self._drag_origin = None + self.drag_lbl.setCursor(Qt.CursorShape.OpenHandCursor) + super().mouseReleaseEvent(event) + + +class CockpitCardTile(QWidget): + """Wrapper tile providing drag-sort, span-resize, in-place swap & right-click menu.""" + + move_step_requested = Signal(str, int) + drop_reorder_requested = Signal(str, str) + cycle_span_requested = Signal(str) + set_span_requested = Signal(str, int) + swap_menu_requested = Signal(str, QPoint) + remove_requested = Signal(str) + context_menu_requested = Signal(str, QPoint) + + def __init__(self, spec: CockpitCardSpec, content: QWidget, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.spec = spec + self.card_key = spec.key + self.content = content + self.setObjectName(f"CockpitTile_{spec.key}") + self.setAcceptDrops(True) + self.setMinimumHeight(spec.min_height) + self._edit_mode = False + self._drop_hover = False + + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(0) + content.setParent(self) + layout.addWidget(content, 1) + + self.edit_bar = _CardEditControlBar(spec, self) + self.edit_bar.hide() + self.edit_bar.move_left_clicked.connect(lambda: self.move_step_requested.emit(self.card_key, -1)) + self.edit_bar.move_right_clicked.connect(lambda: self.move_step_requested.emit(self.card_key, 1)) + self.edit_bar.span_clicked.connect(lambda: self.cycle_span_requested.emit(self.card_key)) + self.edit_bar.swap_clicked.connect(lambda gpos: self.swap_menu_requested.emit(self.card_key, gpos)) + self.edit_bar.remove_clicked.connect(lambda: self.remove_requested.emit(self.card_key)) + self.edit_bar.drag_initiated.connect(self._start_drag) + + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.customContextMenuRequested.connect( + lambda pos: self.context_menu_requested.emit(self.card_key, self.mapToGlobal(pos)) + ) + + def set_edit_state( + self, + enabled: bool, + *, + span: int, + can_prev: bool, + can_next: bool, + can_remove: bool, + ) -> None: + self._edit_mode = enabled + self.edit_bar.sync_controls( + span=span, + can_prev=can_prev, + can_next=can_next, + can_remove=can_remove, + ) + self.edit_bar.setVisible(enabled) + if enabled: + self._reposition_edit_bar() + self.edit_bar.raise_() + self.update() + + def _reposition_edit_bar(self) -> None: + self.edit_bar.adjustSize() + bw = self.edit_bar.width() + x = max(6, self.width() - bw - 10) + self.edit_bar.move(x, 8) + + def resizeEvent(self, event: Any) -> None: # noqa: N802 + super().resizeEvent(event) + if self._edit_mode: + self._reposition_edit_bar() + + def _start_drag(self, _origin: QPoint) -> None: + drag = QDrag(self) + mime = QMimeData() + mime.setData(MIME_COCKPIT_CARD, self.card_key.encode("utf-8")) + drag.setMimeData(mime) + + snap = self.grab() + if not snap.isNull(): + scaled = snap.scaled( + min(260, max(140, int(self.width() * 0.65))), + min(170, max(90, int(self.height() * 0.65))), + Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation, + ) + translucent = scaled.copy() + translucent.fill(Qt.GlobalColor.transparent) + p = QPainter(translucent) + p.setOpacity(0.86) + p.drawPixmap(0, 0, scaled) + p.setOpacity(1.0) + p.setPen(QPen(QColor("#0E6F5C"), 2.0)) + p.drawRoundedRect(QRect(1, 1, translucent.width() - 2, translucent.height() - 2), 14, 14) + p.end() + drag.setPixmap(translucent) + drag.setHotSpot(QPoint(translucent.width() // 2, 18)) + + drag.exec(Qt.DropAction.MoveAction) + + def dragEnterEvent(self, event: QDragEnterEvent) -> None: # noqa: N802 + if event.mimeData().hasFormat(MIME_COCKPIT_CARD): + src = bytes(event.mimeData().data(MIME_COCKPIT_CARD)).decode("utf-8", errors="ignore") + if src and src != self.card_key: + self._drop_hover = True + self.update() + event.acceptProposedAction() + return + event.ignore() + + def dragLeaveEvent(self, event: QDragLeaveEvent) -> None: # noqa: N802 + if self._drop_hover: + self._drop_hover = False + self.update() + super().dragLeaveEvent(event) + + def dropEvent(self, event: QDropEvent) -> None: # noqa: N802 + self._drop_hover = False + self.update() + if event.mimeData().hasFormat(MIME_COCKPIT_CARD): + src = bytes(event.mimeData().data(MIME_COCKPIT_CARD)).decode("utf-8", errors="ignore") + if src and src != self.card_key: + self.drop_reorder_requested.emit(src, self.card_key) + event.acceptProposedAction() + return + event.ignore() + + def paintEvent(self, event: Any) -> None: # noqa: N802 + super().paintEvent(event) + if not self._edit_mode and not self._drop_hover: + return + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + r = self.rect().adjusted(1, 1, -1, -1) + if self._drop_hover: + painter.setBrush(QColor(14, 111, 92, 24)) + painter.setPen(QPen(QColor("#0E6F5C"), 2.2, Qt.PenStyle.SolidLine)) + painter.drawRoundedRect(r, 22, 22) + elif self._edit_mode: + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.setPen(QPen(QColor("#7FC7B6"), 1.3, Qt.PenStyle.DashLine)) + painter.drawRoundedRect(r, 22, 22) + + +class CockpitLayoutStudioBar(QFrame): + """Two-tier Card Library & Suite Studio: 4+1 Preset Suites, 4 Layout Modes & 14-Card Picker.""" + + suite_selected = Signal(str) + save_custom_requested = Signal() + mode_selected = Signal(str) + toggle_card_requested = Signal(str) + restore_card_requested = Signal(str) + reset_requested = Signal() + done_requested = Signal() + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setObjectName("CockpitLayoutStudioBar") + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self._active_category = "all" + self._last_state: CockpitLayoutState | None = None + + self.setStyleSheet( + "QFrame#CockpitLayoutStudioBar {" + " background-color: #FFFFFF; border: 1px solid #C8DFD9; border-radius: 18px; }" + "QFrame#LayoutModeIsland {" + " background-color: #F2F7F5; border: 1px solid #E1ECE8; border-radius: 14px; }" + "QPushButton#SuitePresetPill {" + " min-height: 26px; max-height: 26px; padding: 0 11px; border-radius: 13px;" + " border: 0; background: transparent; color: #3D5955; font-size: 11.5px; font-weight: 600; }" + "QPushButton#SuitePresetPill:hover { color: #0E6F5C; background: rgba(14,111,92,16); }" + "QPushButton#SuitePresetPill:checked { background-color: #0E6F5C; color: #FFFFFF; }" + "QPushButton#LayoutModePill {" + " min-height: 26px; max-height: 26px; padding: 0 10px; border-radius: 13px;" + " border: 0; background: transparent; color: #4A635F; font-size: 11px; font-weight: 600; }" + "QPushButton#LayoutModePill:hover { color: #0E6F5C; background: rgba(14,111,92,16); }" + "QPushButton#LayoutModePill:checked { background-color: #111918; color: #FFFFFF; }" + "QPushButton#CategoryTabPill {" + " min-height: 24px; max-height: 24px; padding: 0 9px; border-radius: 12px;" + " border: 0; background: transparent; color: #647C78; font-size: 11px; font-weight: 600; }" + "QPushButton#CategoryTabPill:hover { color: #0E6F5C; background: #EAF4F1; }" + "QPushButton#CategoryTabPill:checked { background: #DFF1EC; color: #0E6F5C; }" + "QPushButton#ActiveCardLibraryChip {" + " min-height: 26px; max-height: 26px; padding: 0 10px; border-radius: 13px;" + " border: 1px solid #0E6F5C; background: #0E6F5C; color: #FFFFFF;" + " font-size: 11px; font-weight: 600; }" + "QPushButton#ActiveCardLibraryChip:hover { background: #0A5949; }" + "QPushButton#CandidateCardLibraryChip {" + " min-height: 26px; max-height: 26px; padding: 0 10px; border-radius: 13px;" + " border: 1px dashed #82C4B3; background: #F5FBF9; color: #194A41;" + " font-size: 11px; font-weight: 600; }" + "QPushButton#CandidateCardLibraryChip:hover {" + " background: #E3F5EF; border-style: solid; border-color: #0E6F5C; color: #0E6F5C; }" + "QPushButton#StudioGhostBtn {" + " min-height: 27px; max-height: 27px; padding: 0 11px; border-radius: 13px;" + " border: 1px solid #D9E6E2; background: #F7FAF9; color: #364E4A;" + " font-size: 11px; font-weight: 600; }" + "QPushButton#StudioGhostBtn:hover { background: #E6F3EF; color: #0E6F5C; }" + "QPushButton#StudioDoneBtn {" + " min-height: 27px; max-height: 27px; padding: 0 13px; border-radius: 13px;" + " border: 0; background: #0E6F5C; color: #FFFFFF; font-size: 11px; font-weight: 600; }" + "QPushButton#StudioDoneBtn:hover { background: #0A5949; }" + ) + + root = QVBoxLayout(self) + root.setContentsMargins(14, 9, 14, 9) + root.setSpacing(7) + + # ── Tier 1: 4 Preset Suites (+ Custom) & 4 Layout Engines + Actions ─ + top_row = QHBoxLayout() + top_row.setContentsMargins(0, 0, 0, 0) + top_row.setSpacing(8) + + s_lbl = QLabel("预设套系", self) + f_bold = QFont(heading_family()) + f_bold.setPixelSize(12) + f_bold.setWeight(QFont.Weight.DemiBold) + s_lbl.setFont(f_bold) + s_lbl.setStyleSheet("color: #122422;") + top_row.addWidget(s_lbl) + + suite_island = QFrame(self) + suite_island.setObjectName("LayoutModeIsland") + sl = QHBoxLayout(suite_island) + sl.setContentsMargins(3, 2, 3, 2) + sl.setSpacing(2) + self._suite_buttons: dict[str, QPushButton] = {} + for s_spec in COCKPIT_PRESET_SUITES: + btn = QPushButton(s_spec.short_title, suite_island) + btn.setObjectName("SuitePresetPill") + btn.setCheckable(True) + btn.setCursor(Qt.CursorShape.PointingHandCursor) + btn.setToolTip(f"{s_spec.title}:{s_spec.description}") + btn.clicked.connect(lambda _c=False, k=s_spec.key: self.suite_selected.emit(k)) + sl.addWidget(btn) + self._suite_buttons[s_spec.key] = btn + + self.custom_suite_btn = QPushButton("我的方案", suite_island) + self.custom_suite_btn.setObjectName("SuitePresetPill") + self.custom_suite_btn.setCheckable(True) + self.custom_suite_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.custom_suite_btn.setToolTip("切换到您保存的专属卡片组合方案") + self.custom_suite_btn.clicked.connect(lambda: self.suite_selected.emit("custom")) + self.custom_suite_btn.hide() + sl.addWidget(self.custom_suite_btn) + self._suite_buttons["custom"] = self.custom_suite_btn + top_row.addWidget(suite_island) + + m_lbl = QLabel("栅格排布", self) + m_lbl.setFont(f_bold) + m_lbl.setStyleSheet("color: #122422; margin-left: 4px;") + top_row.addWidget(m_lbl) + + mode_island = QFrame(self) + mode_island.setObjectName("LayoutModeIsland") + ml = QHBoxLayout(mode_island) + ml.setContentsMargins(3, 2, 3, 2) + ml.setSpacing(2) + self._mode_buttons: dict[str, QPushButton] = {} + for m_key, m_label, m_tip in LAYOUT_MODES: + btn = QPushButton(m_label, mode_island) + btn.setObjectName("LayoutModePill") + btn.setCheckable(True) + btn.setCursor(Qt.CursorShape.PointingHandCursor) + btn.setToolTip(m_tip) + btn.clicked.connect(lambda _c=False, k=m_key: self.mode_selected.emit(k)) + ml.addWidget(btn) + self._mode_buttons[m_key] = btn + top_row.addWidget(mode_island) + + top_row.addStretch(1) + + self.save_custom_btn = QPushButton("存为我的方案", self) + self.save_custom_btn.setObjectName("StudioGhostBtn") + self.save_custom_btn.setIcon(icons.icon("plus", "#0E6F5C", 12)) + self.save_custom_btn.setIconSize(QSize(12, 12)) + self.save_custom_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.save_custom_btn.setToolTip("将当前卡片选择、排序与跨度保存为「我的方案」随时一键调出") + self.save_custom_btn.clicked.connect(self.save_custom_requested.emit) + top_row.addWidget(self.save_custom_btn) + + self.reset_btn = QPushButton("恢复默认", self) + self.reset_btn.setObjectName("StudioGhostBtn") + self.reset_btn.setIcon(icons.icon("refresh", "#364E4A", 12)) + self.reset_btn.setIconSize(QSize(12, 12)) + self.reset_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.reset_btn.setToolTip("还原为默认「全息综合接诊套」经典三栏布局") + self.reset_btn.clicked.connect(self.reset_requested.emit) + top_row.addWidget(self.reset_btn) + + self.done_btn = QPushButton("完成编排", self) + self.done_btn.setObjectName("StudioDoneBtn") + self.done_btn.setIcon(icons.icon("check", "#FFFFFF", 12)) + self.done_btn.setIconSize(QSize(12, 12)) + self.done_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.done_btn.clicked.connect(self.done_requested.emit) + top_row.addWidget(self.done_btn) + root.addLayout(top_row) + + # ── Tier 2: 14-Card Component Library Shelf (Category Tabs + Chips) ─ + lib_row = QHBoxLayout() + lib_row.setContentsMargins(0, 0, 0, 0) + lib_row.setSpacing(6) + + c_lbl = QLabel("卡片组件库", self) + c_lbl.setFont(f_bold) + c_lbl.setStyleSheet("color: #122422;") + lib_row.addWidget(c_lbl) + + self._cat_buttons: dict[str, QPushButton] = {} + for cat_key, cat_title in CARD_CATEGORIES: + cbtn = QPushButton(cat_title, self) + cbtn.setObjectName("CategoryTabPill") + cbtn.setCheckable(True) + cbtn.setChecked(cat_key == "all") + cbtn.setCursor(Qt.CursorShape.PointingHandCursor) + cbtn.clicked.connect(lambda _c=False, ck=cat_key: self._select_category(ck)) + lib_row.addWidget(cbtn) + self._cat_buttons[cat_key] = cbtn + + self.chips_scroll = QScrollArea(self) + self.chips_scroll.setObjectName("StudioLibraryChipsScroll") + self.chips_scroll.setWidgetResizable(True) + self.chips_scroll.setFrameShape(QFrame.Shape.NoFrame) + self.chips_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.chips_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.chips_scroll.setFixedHeight(30) + self.chips_scroll.viewport().setObjectName("StudioLibraryChipsViewport") + self.chips_scroll.setStyleSheet( + "QScrollArea#StudioLibraryChipsScroll, QWidget#StudioLibraryChipsViewport," + " QWidget#StudioLibraryChipsHost { background: transparent; border: 0; }" + ) + + self.center_host = QWidget(self.chips_scroll) + self.center_host.setObjectName("StudioLibraryChipsHost") + self.center_layout = QHBoxLayout(self.center_host) + self.center_layout.setContentsMargins(2, 1, 2, 1) + self.center_layout.setSpacing(6) + self.chips_scroll.setWidget(self.center_host) + lib_row.addWidget(self.chips_scroll, 1) + + self.count_badge = QLabel("", self) + self.count_badge.setStyleSheet("color: #5C7571; font-size: 11px; font-weight: 600;") + lib_row.addWidget(self.count_badge) + root.addLayout(lib_row) + + def _select_category(self, cat_key: str) -> None: + self._active_category = cat_key + for k, btn in self._cat_buttons.items(): + btn.setChecked(k == cat_key) + if self._last_state is not None: + self.sync_from_state(self._last_state) + + def sync_from_state(self, state: CockpitLayoutState) -> None: + self._last_state = state + self.custom_suite_btn.setVisible(state.has_custom_suite or state.active_suite == "custom") + for s_key, s_btn in self._suite_buttons.items(): + s_btn.setChecked(s_key == state.active_suite) + for m_key, m_btn in self._mode_buttons.items(): + m_btn.setChecked(m_key == state.layout_mode) + + while self.center_layout.count(): + item = self.center_layout.takeAt(0) + w = item.widget() + if w is not None: + w.hide() + w.setParent(None) + w.deleteLater() + + vis_set = set(state.visible_cards) + filtered_specs = [ + spec + for spec in COCKPIT_CARD_SPECS + if self._active_category == "all" or spec.category == self._active_category + ] + # Show candidate (+ addable) cards and active (✓ placed) cards clearly + for spec in filtered_specs: + is_on = spec.key in vis_set + chip = QPushButton(spec.short_title, self.center_host) + chip.setObjectName("ActiveCardLibraryChip" if is_on else "CandidateCardLibraryChip") + chip.setIcon( + icons.icon("check", "#FFFFFF", 11) + if is_on + else icons.icon("plus", "#0E6F5C", 11) + ) + chip.setIconSize(QSize(11, 11)) + chip.setCursor(Qt.CursorShape.PointingHandCursor) + action_hint = "已在当前桌面(点击可移除)" if is_on else "点击添加到当前接诊总览" + chip.setToolTip( + f"【{CATEGORY_LABELS.get(spec.category, '')}】{spec.title}\n{spec.description}\n— {action_hint}" + ) + chip.clicked.connect(lambda _c=False, key=spec.key: self.toggle_card_requested.emit(key)) + self.center_layout.addWidget(chip) + self.center_layout.addStretch(1) + self.count_badge.setText(f"已摆 {len(vis_set)}/{len(COCKPIT_CARD_SPECS)} 卡") + + +def build_swap_card_menu( + parent: QWidget, + state: CockpitLayoutState, + source_key: str, + on_swap: Callable[[str, str], None], +) -> QMenu: + """Popup menu to swap `source_key` in-place with any other card from the 14-card catalog.""" + + menu = QMenu(parent) + src_spec = CARD_SPEC_MAP[source_key] + vis_set = set(state.visible_cards) + hdr = menu.addAction(f"将「{src_spec.short_title}」原地替换为:") + hdr.setEnabled(False) + menu.addSeparator() + + for cat_key, cat_title in CARD_CATEGORIES: + if cat_key == "all": + continue + sub = menu.addMenu(cat_title) + for spec in COCKPIT_CARD_SPECS: + if spec.category != cat_key or spec.key == source_key: + continue + tag = "(已在桌面 · 互换位置)" if spec.key in vis_set else "" + act = sub.addAction(f"{spec.title}{tag}") + act.triggered.connect(lambda _c=False, nk=spec.key: on_swap(source_key, nk)) + return menu + + +def build_cockpit_context_menu( + parent: QWidget, + state: CockpitLayoutState, + card_key: str, + *, + edit_mode: bool, + on_toggle_edit: Callable[[], None], + on_suite: Callable[[str], None], + on_save_custom: Callable[[], None], + on_mode: Callable[[str], None], + on_move: Callable[[str, int], None], + on_span: Callable[[str, int], None], + on_swap: Callable[[str, str], None], + on_add: Callable[[str], None], + on_remove: Callable[[str], None], + on_reset: Callable[[], None], +) -> QMenu: + """Build a rich Jade-Porcelain right-click menu for quick suite, card library & layout control.""" + + menu = QMenu(parent) + spec = CARD_SPEC_MAP[card_key] + vis = state.visible_cards + idx = vis.index(card_key) if card_key in vis else -1 + + act_edit = menu.addAction( + "退出卡片库与布局编排" if edit_mode else "打开 14 卡组件库与布局编排工作台" + ) + act_edit.triggered.connect(on_toggle_edit) + menu.addSeparator() + + suite_menu = menu.addMenu("一键切换预设卡片套系(4套)") + for s_spec in COCKPIT_PRESET_SUITES: + act_s = suite_menu.addAction(f"{s_spec.title}({len(s_spec.card_keys)}张卡)") + act_s.setCheckable(True) + act_s.setChecked(state.active_suite == s_spec.key) + act_s.triggered.connect(lambda _c=False, sk=s_spec.key: on_suite(sk)) + if state.has_custom_suite: + act_cs = suite_menu.addAction("我的自定义方案") + act_cs.setCheckable(True) + act_cs.setChecked(state.active_suite == "custom") + act_cs.triggered.connect(lambda: on_suite("custom")) + suite_menu.addSeparator() + act_save_c = suite_menu.addAction("将当前桌面保存为「我的方案」") + act_save_c.triggered.connect(on_save_custom) + + mode_menu = menu.addMenu("切换页面栅格布局模式") + for m_key, m_label, _tip in LAYOUT_MODES: + act = mode_menu.addAction(m_label) + act.setCheckable(True) + act.setChecked(state.layout_mode == m_key) + act.triggered.connect(lambda _c=False, k=m_key: on_mode(k)) + + # Add new cards from the 14-card library + unplaced = state.unplaced_library_cards + if unplaced: + add_menu = menu.addMenu(f"+ 添加其他临床卡片(可选 {len(unplaced)} 张)") + for cat_key, cat_title in CARD_CATEGORIES: + if cat_key == "all": + continue + cat_items = [CARD_SPEC_MAP[k] for k in unplaced if CARD_SPEC_MAP[k].category == cat_key] + if not cat_items: + continue + cat_sub = add_menu.addMenu(cat_title) + for c_spec in cat_items: + act_a = cat_sub.addAction(f"+ {c_spec.title}") + act_a.triggered.connect(lambda _c=False, ck=c_spec.key: on_add(ck)) + + swap_sub = menu.addMenu(f"将「{spec.short_title}」替换为其他卡片") + for cat_key, cat_title in CARD_CATEGORIES: + if cat_key == "all": + continue + c_sub = swap_sub.addMenu(cat_title) + for c_spec in COCKPIT_CARD_SPECS: + if c_spec.category != cat_key or c_spec.key == card_key: + continue + act_sw = c_sub.addAction(c_spec.title) + act_sw.triggered.connect(lambda _c=False, nk=c_spec.key: on_swap(card_key, nk)) + + span_menu = menu.addMenu(f"调整「{spec.short_title}」宽度跨度") + cur_span = state.span_for(card_key) + for sp_val in VALID_SPANS: + act_sp = span_menu.addAction(SPAN_LABELS[sp_val]) + act_sp.setCheckable(True) + act_sp.setChecked(cur_span == sp_val) + act_sp.triggered.connect(lambda _c=False, s=sp_val: on_span(card_key, s)) + + menu.addSeparator() + act_prev = menu.addAction(f"前移「{spec.short_title}」") + act_prev.setEnabled(idx > 0) + act_prev.triggered.connect(lambda: on_move(card_key, -1)) + + act_next = menu.addAction(f"后移「{spec.short_title}」") + act_next.setEnabled(0 <= idx < len(vis) - 1) + act_next.triggered.connect(lambda: on_move(card_key, 1)) + + act_rm = menu.addAction(f"移除「{spec.title}」卡片") + act_rm.setEnabled(len(vis) > 1) + act_rm.triggered.connect(lambda: on_remove(card_key)) + + menu.addSeparator() + act_reset = menu.addAction("恢复默认全息综合套(经典三栏)") + act_reset.triggered.connect(on_reset) + return menu + + +__all__ = [ + "ALL_CARD_KEYS", + "CARD_CATEGORIES", + "CARD_SPEC_MAP", + "COCKPIT_CARD_SPECS", + "COCKPIT_PRESET_SUITES", + "CockpitCardSpec", + "CockpitCardTile", + "CockpitLayoutState", + "CockpitLayoutStore", + "CockpitLayoutStudioBar", + "CockpitSuiteSpec", + "DEFAULT_CARD_ORDER", + "LAYOUT_MODES", + "SPAN_LABELS", + "SUITE_SPEC_MAP", + "VALID_LAYOUT_MODES", + "VALID_SPANS", + "build_cockpit_context_menu", + "build_swap_card_menu", + "compute_layout_bands", +] diff --git a/app/src/doctor_workstation/ui/visuals/diurnal_strip.py b/app/src/doctor_workstation/ui/visuals/diurnal_strip.py index 272629baf..d06d4cf2e 100644 --- a/app/src/doctor_workstation/ui/visuals/diurnal_strip.py +++ b/app/src/doctor_workstation/ui/visuals/diurnal_strip.py @@ -4,7 +4,7 @@ from __future__ import annotations import html -from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal +from PySide6.QtCore import QRectF, QSize, Qt, Signal from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen from PySide6.QtWidgets import QToolTip, QWidget @@ -222,8 +222,13 @@ class DiurnalStabilityCard(QWidget): bar_area_top = cursor_y + 13.0 bar_area_h = 24.0 if compact else 30.0 n_slots = len(vm.slots) - s_gap = 8.0 if n_slots <= 5 else 5.0 - s_w = min(34.0, max(16.0, (avail_w - s_gap * (n_slots - 1)) / n_slots)) + min_s_gap = 8.0 if n_slots <= 5 else 5.0 + s_w = min(32.0, max(16.0, (avail_w - min_s_gap * (n_slots - 1)) / n_slots)) + s_gap = ( + min(24.0, max(min_s_gap, (avail_w - n_slots * s_w) / (n_slots - 1))) + if n_slots >= 3 + else 16.0 + ) pitch = s_w + s_gap val_font = QFont(number_family()) val_font.setPixelSize(10) @@ -293,7 +298,7 @@ class DiurnalStabilityCard(QWidget): self._brick_rects.append((r_rect, brick)) rp = QPainterPath() rp.addRoundedRect(r_rect, 11.0, 11.0) - painter.fillPath(rp, QColor("#FDF3EF") if brick.alert else "#F6FAF9") + painter.fillPath(rp, QColor("#FDF3EF" if brick.alert else "#F6FAF9")) painter.setPen(QPen(QColor("#F2D4CA" if brick.alert else "#E3ECE9"), 1.0)) painter.drawPath(rp) @@ -340,7 +345,7 @@ class DiurnalStabilityCard(QWidget): self._brick_rects.append((b_rect, brick)) bp = QPainterPath() bp.addRoundedRect(b_rect, 12.0, 12.0) - painter.fillPath(bp, QColor("#FDF2EE") if brick.alert else "#F5F9F8") + painter.fillPath(bp, QColor("#FDF2EE" if brick.alert else "#F5F9F8")) painter.setPen(QPen(QColor("#F2D4CA" if brick.alert else "#E3ECE9"), 1.0)) painter.drawPath(bp) diff --git a/app/src/doctor_workstation/ui/visuals/pill_chart.py b/app/src/doctor_workstation/ui/visuals/pill_chart.py index 1e4af3612..44d2b4253 100644 --- a/app/src/doctor_workstation/ui/visuals/pill_chart.py +++ b/app/src/doctor_workstation/ui/visuals/pill_chart.py @@ -285,10 +285,15 @@ class PillProgressionCard(QWidget): ) n = len(real_bars) - gap = 10.0 if n <= 5 else 6.0 - bar_w = min(34.0, max(14.0, (avail_w - gap * (n - 1)) / n)) + min_gap = 10.0 if n <= 5 else 6.0 + bar_w = min(34.0, max(14.0, (avail_w - min_gap * (n - 1)) / n)) + gap = ( + min(26.0, max(min_gap, (avail_w - n * bar_w) / (n - 1))) + if n >= 3 + else 18.0 + ) total_span = n * bar_w + (n - 1) * gap - start_x = left + max(0.0, (avail_w - total_span) * 0.5) if n <= 4 else left + start_x = left + max(0.0, (avail_w - total_span) * 0.5) if n == 2 else left # Show every date when spacing permits (>= 34px pitch), otherwise alternate + first/last pitch = bar_w + gap diff --git a/app/src/doctor_workstation/ui/visuals/reception_cockpit.py b/app/src/doctor_workstation/ui/visuals/reception_cockpit.py index af2842025..b03435b99 100644 --- a/app/src/doctor_workstation/ui/visuals/reception_cockpit.py +++ b/app/src/doctor_workstation/ui/visuals/reception_cockpit.py @@ -4,9 +4,10 @@ from __future__ import annotations from collections.abc import Sequence from datetime import date +from pathlib import Path from typing import Any -from PySide6.QtCore import QSize, Qt, Signal +from PySide6.QtCore import QPoint, QSize, Qt, Signal from PySide6.QtGui import QFont from PySide6.QtWidgets import ( QFrame, @@ -23,7 +24,29 @@ from ...core.appointment_modes import appointment_type_description, appointment_ from .. import icons from ..reception_style import body_family, heading_family from ..viewmodels.cockpit_vm import CockpitSnapshotVM, derive_cockpit_snapshot -from ..widgets import clear_layout, display_text, first_value, gender_text +from ..widgets import clear_layout, display_text, first_value, gender_text, show_toast +from .cockpit_cards_extra import ( + AiEvidenceBriefCard, + LifestyleInterventionCard, + MetabolicTargetPanelCard, + NotesMediaArchiveCard, + PrescriptionHerbCard, + SafetyHistoryGuardCard, + SyndromePositiveTagsCard, + TcmFourDiagMatrixCard, +) +from .cockpit_layout import ( + CARD_SPEC_MAP, + COCKPIT_CARD_SPECS, + SUITE_SPEC_MAP, + CockpitCardTile, + CockpitLayoutState, + CockpitLayoutStore, + CockpitLayoutStudioBar, + build_cockpit_context_menu, + build_swap_card_menu, + compute_layout_bands, +) from .diurnal_strip import DiurnalStabilityCard from .journey_track import CareJourneyCard from .pill_chart import PillProgressionCard @@ -38,11 +61,12 @@ QFrame#CockpitBentoCard { border: 1px solid #E3ECE9; border-radius: 22px; } +QFrame#CockpitBentoCard QPushButton#CockpitFilterPill, QPushButton#CockpitFilterPill { min-width: 0px; min-height: 24px; max-height: 24px; - padding: 0 6px; + padding: 0 7px; border-radius: 12px; border: 0; background-color: #F2F6F5; @@ -50,12 +74,15 @@ QPushButton#CockpitFilterPill { font-size: 10.5px; font-weight: 500; } +QFrame#CockpitBentoCard QPushButton#CockpitFilterPill:hover, QPushButton#CockpitFilterPill:hover { background-color: #E5F1EE; color: #0E6F5C; } +QFrame#CockpitBentoCard QPushButton#CockpitFilterPill:checked, QPushButton#CockpitFilterPill:checked { background-color: #111918; + border: 0; color: #FFFFFF; font-weight: 600; } @@ -296,7 +323,7 @@ class _TimelineRowWidget(QFrame): class ReceptionDigitalTwinCockpit(QWidget): - """Full Alveo × Serene 3-column Clinical Cockpit + 21-Day Real Check-in Track.""" + """Modular, multi-layout Alveo × Serene Clinical Cockpit supporting remove, reorder & 4 layouts.""" appointment_selected = Signal(object) filter_status_requested = Signal(object) @@ -308,75 +335,366 @@ class ReceptionDigitalTwinCockpit(QWidget): notify_assistant_requested = Signal() complete_visit_requested = Signal() open_chart_tab_requested = Signal(int) + ai_model_selected = Signal(str) + open_ai_report_requested = Signal() + open_ai_consult_requested = Signal() + layout_state_changed = Signal(object, bool) - def __init__(self, parent: QWidget | None = None) -> None: + def __init__( + self, + parent: QWidget | None = None, + *, + layout_storage_path: Path | None = None, + persist_layout: bool | None = None, + ) -> None: super().__init__(parent) self.setObjectName("ReceptionDigitalTwinCockpit") self.setStyleSheet(COCKPIT_QSS) + self._layout_store = CockpitLayoutStore(layout_storage_path, persist=persist_layout) + self._layout_state: CockpitLayoutState = self._layout_store.load() + self._layout_edit_mode = False + root = QVBoxLayout(self) root.setContentsMargins(0, 0, 0, 0) - root.setSpacing(12) + root.setSpacing(10) - # ── Layer 3: Asymmetric 3-Column Clinical Cockpit ────────────────── - cockpit_row = QHBoxLayout() - cockpit_row.setContentsMargins(0, 0, 0, 0) - cockpit_row.setSpacing(14) + # Collapsible Top 14-Card Library & Multi-Suite Studio Ribbon + self.layout_studio_bar = CockpitLayoutStudioBar(self) + self.layout_studio_bar.hide() + self.layout_studio_bar.suite_selected.connect(self.apply_suite) + self.layout_studio_bar.save_custom_requested.connect(self.save_custom_suite) + self.layout_studio_bar.mode_selected.connect(self.set_layout_mode) + self.layout_studio_bar.toggle_card_requested.connect(self.toggle_card) + self.layout_studio_bar.restore_card_requested.connect(self.restore_card) + self.layout_studio_bar.reset_requested.connect(self.reset_layout_defaults) + self.layout_studio_bar.done_requested.connect(lambda: self.set_layout_edit_mode(False)) + root.addWidget(self.layout_studio_bar) - # Column 1 (Left 26%): Real Fasting Glucose + Postprandial & Real Vitals - left_wing = QWidget(self) - left_wing.setMinimumWidth(214) - left_wing.setMaximumWidth(390) - left_layout = QVBoxLayout(left_wing) - left_layout.setContentsMargins(0, 0, 0, 0) - left_layout.setSpacing(12) + # Scroll-capable Modular Bento Grid Host + self.canvas_scroll = QScrollArea(self) + self.canvas_scroll.setObjectName("CockpitCanvasScroll") + self.canvas_scroll.setWidgetResizable(True) + self.canvas_scroll.setFrameShape(QFrame.Shape.NoFrame) + self.canvas_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.canvas_scroll.viewport().setObjectName("CockpitCanvasViewport") + self.canvas_scroll.setStyleSheet( + "QScrollArea#CockpitCanvasScroll, QWidget#CockpitCanvasViewport, QWidget#CockpitGridCanvas {" + " background: transparent; border: 0; }" + ) - self.progression_card = PillProgressionCard(left_wing) + self.grid_canvas = QWidget(self.canvas_scroll) + self.grid_canvas.setObjectName("CockpitGridCanvas") + self.grid_canvas_layout = QVBoxLayout(self.grid_canvas) + self.grid_canvas_layout.setContentsMargins(0, 0, 0, 0) + self.grid_canvas_layout.setSpacing(12) + self.canvas_scroll.setWidget(self.grid_canvas) + root.addWidget(self.canvas_scroll, 1) + + # Build all 14 Clinical Cards (6 Classic + 8 New Specialist Cards) + self.progression_card = PillProgressionCard(self.grid_canvas) self.progression_card.open_daily_requested.connect( lambda: self.locus_selected.emit("daily_glucose") ) - self.diurnal_card = DiurnalStabilityCard(left_wing) + self.diurnal_card = DiurnalStabilityCard(self.grid_canvas) self.diurnal_card.open_daily_requested.connect( lambda: self.locus_selected.emit("daily_glucose") ) self.diurnal_card.vital_clicked.connect( lambda fk: self.locus_selected.emit(f"vital:{fk}") ) - left_layout.addWidget(self.progression_card, 44) - left_layout.addWidget(self.diurnal_card, 56) - cockpit_row.addWidget(left_wing, 26) - - # Column 2 (Center 46%): Human Body & Metabolic Visceral Symptom Stage - self.twin_stage = ClinicalTwinStageWidget(self) + self.twin_stage = ClinicalTwinStageWidget(self.grid_canvas) self.twin_stage.locus_clicked.connect(self.locus_selected.emit) self.twin_stage.open_chart_requested.connect(lambda: self.open_chart_tab_requested.emit(0)) - cockpit_row.addWidget(self.twin_stage, 46) - # Column 3 (Right 28%): Outpatient Queue + Care Team Actions - right_wing = QWidget(self) - right_wing.setMinimumWidth(256) - right_wing.setMaximumWidth(404) - right_layout = QVBoxLayout(right_wing) - right_layout.setContentsMargins(0, 0, 0, 0) - right_layout.setSpacing(12) + self.plan_card = self._build_today_plan_card(self.grid_canvas) + self.team_card = self._build_care_team_card(self.grid_canvas) - 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 Real Daily Check-in Matrix ───────────── - self.journey_card = CareJourneyCard(self) + self.journey_card = CareJourneyCard(self.grid_canvas) self.journey_card.open_full_plan_requested.connect(lambda: self.open_chart_tab_requested.emit(3)) self.journey_card.day_selected.connect(lambda _d: self.open_chart_tab_requested.emit(3)) - root.addWidget(self.journey_card) + + # 8 Additional Specialist Clinical Cards + self.metabolic_panel_card = MetabolicTargetPanelCard(self.grid_canvas) + self.metabolic_panel_card.locus_selected.connect(self.locus_selected.emit) + + self.lifestyle_card = LifestyleInterventionCard(self.grid_canvas) + self.lifestyle_card.locus_selected.connect(self.locus_selected.emit) + + self.tcm_matrix_card = TcmFourDiagMatrixCard(self.grid_canvas) + self.tcm_matrix_card.locus_selected.connect(self.locus_selected.emit) + + self.syndrome_tags_card = SyndromePositiveTagsCard(self.grid_canvas) + self.syndrome_tags_card.locus_selected.connect(self.locus_selected.emit) + + self.rx_herb_card = PrescriptionHerbCard(self.grid_canvas) + self.rx_herb_card.locus_selected.connect(self.locus_selected.emit) + + self.ai_brief_card = AiEvidenceBriefCard(self.grid_canvas) + self.ai_brief_card.ai_model_selected.connect(self.ai_model_selected.emit) + self.ai_brief_card.open_ai_report_requested.connect(self.open_ai_report_requested.emit) + self.ai_brief_card.open_ai_consult_requested.connect(self.open_ai_consult_requested.emit) + + self.safety_history_card = SafetyHistoryGuardCard(self.grid_canvas) + self.safety_history_card.locus_selected.connect(self.locus_selected.emit) + + self.notes_media_card = NotesMediaArchiveCard(self.grid_canvas) + self.notes_media_card.locus_selected.connect(self.locus_selected.emit) + + raw_widgets: dict[str, QWidget] = { + "fasting": self.progression_card, + "diurnal": self.diurnal_card, + "metabolic_panel": self.metabolic_panel_card, + "lifestyle_log": self.lifestyle_card, + "twin_stage": self.twin_stage, + "tcm_four_diag": self.tcm_matrix_card, + "syndrome_tags": self.syndrome_tags_card, + "rx_herb_card": self.rx_herb_card, + "ai_brief_card": self.ai_brief_card, + "safety_history": self.safety_history_card, + "queue": self.plan_card, + "care_team": self.team_card, + "notes_media": self.notes_media_card, + "journey": self.journey_card, + } + self._card_tiles: dict[str, CockpitCardTile] = {} + for spec in COCKPIT_CARD_SPECS: + inner = raw_widgets[spec.key] + tile = CockpitCardTile(spec, inner, self.grid_canvas) + inner.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + inner.customContextMenuRequested.connect( + lambda pos, src_w=inner, k=spec.key: self._show_card_context_menu(k, src_w.mapToGlobal(pos)) + ) + tile.move_step_requested.connect(self.move_card_step) + tile.drop_reorder_requested.connect(self.reorder_card) + tile.cycle_span_requested.connect(self.cycle_card_span) + tile.set_span_requested.connect(self.set_card_span) + tile.swap_menu_requested.connect(self._show_swap_card_menu) + tile.remove_requested.connect(self.remove_card) + tile.context_menu_requested.connect(self._show_card_context_menu) + self._card_tiles[spec.key] = tile + + self._rebuild_layout_canvas(save=False) # Initialize with honest empty snapshot until a patient is loaded self.set_snapshot(derive_cockpit_snapshot()) + # ── Modular Suites, 14-Card Library, Swap, Removal & Reordering API ──── + + @property + def layout_state(self) -> CockpitLayoutState: + return self._layout_state + + @property + def is_layout_edit_mode(self) -> bool: + return self._layout_edit_mode + + def toggle_layout_edit_mode(self) -> bool: + self.set_layout_edit_mode(not self._layout_edit_mode) + return self._layout_edit_mode + + def set_layout_edit_mode(self, enabled: bool) -> None: + target = bool(enabled) + if self._layout_edit_mode == target: + return + self._layout_edit_mode = target + self.layout_studio_bar.sync_from_state(self._layout_state) + self.layout_studio_bar.setVisible(target) + self._sync_tile_edit_overlays() + self.layout_state_changed.emit(self._layout_state, self._layout_edit_mode) + + def apply_suite(self, suite_key: str) -> bool: + if not self._layout_state.apply_suite(suite_key): + return False + self._rebuild_layout_canvas(save=True) + s_spec = SUITE_SPEC_MAP.get(suite_key) + title = s_spec.title if s_spec is not None else "我的自定义方案" + show_toast(self, f"已切换至「{title}」卡片组合。", "info", 2400) + return True + + def save_custom_suite(self) -> None: + self._layout_state.save_as_custom_suite() + self._rebuild_layout_canvas(save=True) + show_toast(self, "已将当前卡片组合保存为「我的方案」,可随时一键切换。", "success", 2800) + + def set_layout_mode(self, mode_key: str) -> bool: + if not self._layout_state.set_layout_mode(mode_key): + return False + self._rebuild_layout_canvas(save=True) + return True + + def add_card(self, card_key: str) -> bool: + if not self._layout_state.add_card(card_key): + return False + self._rebuild_layout_canvas(save=True) + spec = CARD_SPEC_MAP.get(card_key) + if spec is not None: + show_toast(self, f"已向桌面添加「{spec.title}」。", "info", 2200) + return True + + def toggle_card(self, card_key: str) -> bool: + if card_key in self._layout_state.visible_cards: + return self.remove_card(card_key) + return self.add_card(card_key) + + def swap_card(self, old_key: str, new_key: str) -> bool: + if not self._layout_state.swap_card(old_key, new_key): + return False + self._rebuild_layout_canvas(save=True) + new_spec = CARD_SPEC_MAP.get(new_key) + if new_spec is not None: + show_toast(self, f"已将该卡片位替换为「{new_spec.title}」。", "info", 2200) + return True + + def remove_card(self, card_key: str) -> bool: + if len(self._layout_state.visible_cards) <= 1: + show_toast(self, "至少需保留 1 张临床工作卡片。", "warning") + return False + if not self._layout_state.remove_card(card_key): + return False + spec = CARD_SPEC_MAP.get(card_key) + self._rebuild_layout_canvas(save=True) + if spec is not None: + show_toast(self, f"已移除「{spec.title}」,可在卡片库随时加回。", "info", 2600) + return True + + def restore_card(self, card_key: str) -> bool: + if not self._layout_state.restore_card(card_key): + return False + self._rebuild_layout_canvas(save=True) + return True + + def move_card_step(self, card_key: str, delta: int) -> bool: + if not self._layout_state.move_card_step(card_key, delta): + return False + self._rebuild_layout_canvas(save=True) + return True + + def reorder_card(self, source_key: str, target_key: str) -> bool: + if not self._layout_state.reorder_card(source_key, target_key): + return False + self._rebuild_layout_canvas(save=True) + return True + + def set_card_span(self, card_key: str, span: int) -> bool: + if not self._layout_state.set_card_span(card_key, span): + return False + self._rebuild_layout_canvas(save=True) + return True + + def cycle_card_span(self, card_key: str) -> int: + new_span = self._layout_state.cycle_card_span(card_key) + self._rebuild_layout_canvas(save=True) + return new_span + + def reset_layout_defaults(self) -> None: + self._layout_state.reset_defaults() + self._rebuild_layout_canvas(save=True) + + def _show_swap_card_menu(self, card_key: str, global_pos: QPoint) -> None: + menu = build_swap_card_menu(self, self._layout_state, card_key, self.swap_card) + menu.exec(global_pos) + + def _show_card_context_menu(self, card_key: str, global_pos: QPoint) -> None: + menu = build_cockpit_context_menu( + self, + self._layout_state, + card_key, + edit_mode=self._layout_edit_mode, + on_toggle_edit=self.toggle_layout_edit_mode, + on_suite=self.apply_suite, + on_save_custom=self.save_custom_suite, + on_mode=self.set_layout_mode, + on_move=self.move_card_step, + on_span=self.set_card_span, + on_swap=self.swap_card, + on_add=self.add_card, + on_remove=self.remove_card, + on_reset=self.reset_layout_defaults, + ) + menu.exec(global_pos) + + def _sync_tile_edit_overlays(self) -> None: + vis = self._layout_state.visible_cards + can_rm = len(vis) > 1 + for k, tile in self._card_tiles.items(): + if k in vis: + idx = vis.index(k) + tile.set_edit_state( + self._layout_edit_mode, + span=self._layout_state.span_for(k), + can_prev=idx > 0, + can_next=idx < len(vis) - 1, + can_remove=can_rm, + ) + else: + tile.set_edit_state(False, span=4, can_prev=False, can_next=False, can_remove=False) + + def _rebuild_layout_canvas(self, *, save: bool = True) -> None: + """Atomically reconstruct the Bento grid from `self._layout_state` without deleting card tiles.""" + + updates_on = self.updatesEnabled() + if updates_on: + self.setUpdatesEnabled(False) + try: + # 1. Detach all immortal tiles back onto `grid_canvas` BEFORE clearing transient row/col hosts! + for tile in self._card_tiles.values(): + tile.setParent(self.grid_canvas) + tile.hide() + + clear_layout(self.grid_canvas_layout) + + bands = compute_layout_bands(self._layout_state) + is_classic_3col = self._layout_state.layout_mode == "classic" + + for band in bands: + row_host = QWidget(self.grid_canvas) + row_layout = QHBoxLayout(row_host) + row_layout.setContentsMargins(0, 0, 0, 0) + row_layout.setSpacing(14) + + num_cols = len(band.columns) + for col in band.columns: + if len(col.card_keys) == 1: + k = col.card_keys[0] + tile = self._card_tiles[k] + tile.setMinimumWidth(214 if (is_classic_3col and num_cols >= 3 and col.stretch < 35) else 0) + tile.setMaximumWidth( + 404 if (is_classic_3col and num_cols >= 3 and col.stretch < 35) else 16777215 + ) + tile.show() + row_layout.addWidget(tile, col.stretch) + else: + col_host = QWidget(row_host) + if is_classic_3col and num_cols >= 3: + has_q = "queue" in col.card_keys + col_host.setMinimumWidth(256 if has_q else 214) + col_host.setMaximumWidth(404 if has_q else 390) + col_layout = QVBoxLayout(col_host) + col_layout.setContentsMargins(0, 0, 0, 0) + col_layout.setSpacing(12) + for sub_idx, ck in enumerate(col.card_keys): + tile = self._card_tiles[ck] + tile.setMinimumWidth(0) + tile.setMaximumWidth(16777215) + tile.show() + st = col.card_stretches[sub_idx] if sub_idx < len(col.card_stretches) else 50 + col_layout.addWidget(tile, st) + row_layout.addWidget(col_host, col.stretch) + + self.grid_canvas_layout.addWidget(row_host, band.row_stretch) + + self.layout_studio_bar.sync_from_state(self._layout_state) + self._sync_tile_edit_overlays() + self.grid_canvas_layout.activate() + finally: + if updates_on: + self.setUpdatesEnabled(True) + + if save: + self._layout_store.save(self._layout_state) + self.layout_state_changed.emit(self._layout_state, self._layout_edit_mode) + def _build_today_plan_card(self, parent: QWidget) -> QFrame: card = QFrame(parent) card.setObjectName("CockpitBentoCard") @@ -556,6 +874,14 @@ class ReceptionDigitalTwinCockpit(QWidget): self.diurnal_card.set_view_model(snapshot.diurnal) self.twin_stage.set_snapshot(snapshot) self.journey_card.set_view_model(snapshot.journey) + self.metabolic_panel_card.set_view_model(snapshot.metabolic_panel) + self.lifestyle_card.set_view_model(snapshot.lifestyle_log) + self.tcm_matrix_card.set_view_model(snapshot.tcm_four_diag) + self.syndrome_tags_card.set_view_model(snapshot.syndrome_tags) + self.rx_herb_card.set_view_model(snapshot.rx_card) + self.ai_brief_card.set_view_model(snapshot.aurora) + self.safety_history_card.set_view_model(snapshot.safety_history) + self.notes_media_card.set_view_model(snapshot.notes_media) def set_care_team_context( self, diff --git a/app/src/doctor_workstation/ui/visuals/twin_material_styles.py b/app/src/doctor_workstation/ui/visuals/twin_material_styles.py new file mode 100644 index 000000000..6462ce2cf --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/twin_material_styles.py @@ -0,0 +1,395 @@ +"""Static illustration layers for the clinical twin, in its shared body coordinates.""" + +from __future__ import annotations + +import math +from functools import cache + +from PySide6.QtCore import QPointF, QRectF, Qt +from PySide6.QtGui import QColor, QLinearGradient, QPainter, QPainterPath, QPen + + +def _polygon(points: tuple[tuple[float, float], ...]) -> QPainterPath: + path = QPainterPath(QPointF(*points[0])) + for point in points[1:]: + path.lineTo(*point) + path.closeSubpath() + return path + + +def _gradient(x1: float, y1: float, x2: float, y2: float, *colors: str) -> QLinearGradient: + gradient = QLinearGradient(x1, y1, x2, y2) + for i, color in enumerate(colors): + gradient.setColorAt(i / (len(colors) - 1), QColor(color)) + return gradient + + +def _stroke(p: QPainter, path: QPainterPath, color: str, width: float) -> None: + p.strokePath( + path, + QPen( + QColor(color), + width, + Qt.PenStyle.SolidLine, + Qt.PenCapStyle.RoundCap, + Qt.PenJoinStyle.RoundJoin, + ), + ) + + +@cache +def _crystal_planes() -> tuple[tuple[QPainterPath, QColor], ...]: + rows = ( + ((-36, -161), (-18, -157), (0, -158), (16, -152), (36, -156)), + ((-37, -128), (-16, -135), (-4, -143), (13, -134), (37, -127)), + ((-33, -112), (-13, -115), (3, -123), (19, -114), (36, -111)), + ((-49, -94), (-17, -95), (1, -99), (14, -94), (49, -94)), + ((-84, -73), (-50, -75), (-2, -70), (43, -78), (84, -72)), + ((-84, -29), (-43, -39), (2, -55), (46, -41), (84, -26)), + ((-76, 8), (-39, -5), (-2, -13), (38, 2), (77, 8)), + ((-71, 35), (-37, 29), (4, 16), (41, 28), (71, 31)), + ((-66, 80), (-38, 67), (-4, 60), (40, 68), (66, 84)), + ((-64, 111), (-37, 98), (1, 94), (42, 99), (64, 115)), + ((-60, 145), (-33, 145), (3, 140), (33, 145), (60, 145)), + ) + # Light enters from the upper left. Keep neighbouring triangles on opposing planes. + colors = ( + ("#CCC6EA", "#F3EEFF", "#B9ABD9", "#E0DEF7"), + ("#EDE7FA", "#C0B2DE", "#F8F3FE", "#D7C9EB"), + ("#C1B2DF", "#DAD4F1", "#AA9ACA", "#E9E1F8"), + ("#9184BB", "#B9ACD6", "#ADA3CE", "#8E84B0"), + ) + planes = [] + for row, (top, bottom) in enumerate(zip(rows, rows[1:], strict=False)): + for col in range(4): + a, b = top[col : col + 2] + d, c = bottom[col : col + 2] + tris = ((a, b, c), (a, c, d)) if (row + col) % 2 else ((a, b, d), (b, c, d)) + for side, tri in enumerate(tris): + tone = colors[col][(row + side * 2 + col) % 4] + planes.append((_polygon(tri), QColor(tone))) + return tuple(planes) + + +def draw_facets(p: QPainter, outline: QPainterPath, organs: tuple[QPainterPath, ...]) -> None: + p.save() + p.setClipPath(outline, Qt.ClipOperation.IntersectClip) + p.fillPath(outline, QColor("#CEC4E6")) + seam = QPen(QColor(255, 251, 255, 85), 0.65) + for triangle, color in _crystal_planes(): + p.fillPath(triangle, color) + p.strokePath(triangle, seam) + organ_tones = ( + ("#E5E3FC", "#ACA2D1"), + ("#D6D1F5", "#9E93CC"), + ("#B5AAE0", "#8171AF"), + ("#EAD9B9", "#BFA883"), + ("#B6A5D3", "#8372AB"), + ("#B6A5D3", "#8372AB"), + ) + for shape, (light, shade) in zip(organs, organ_tones, strict=False): + r = shape.boundingRect() + p.fillPath(shape, QColor(light)) + p.save() + p.setClipPath(shape, Qt.ClipOperation.IntersectClip) + tip = (r.center().x() + r.width() * 0.13, r.center().y() - r.height() * 0.16) + fold = _polygon( + ((r.left(), r.bottom()), tip, (r.right(), r.top()), (r.right(), r.bottom())) + ) + p.fillPath(fold, QColor(shade)) + p.strokePath(fold, seam) + p.restore() + _stroke(p, shape, "#F6F1FF", 0.95) + p.restore() + _stroke(p, outline, "#9384B5", 1.0) + + +@cache +def _glass_panes() -> tuple[tuple[QPainterPath, QLinearGradient], ...]: + # The curves are shared by adjacent panes so the leadwork has continuous joints. + rows = ( + ((0, -161), (8, -158), (19, -156), (36, -157)), + ((0, -143), (9, -138), (18, -132), (36, -128)), + ((0, -118), (10, -124), (20, -116), (36, -113)), + ((0, -99), (9, -105), (18, -99), (36, -95)), + ((0, -75), (16, -85), (43, -78), (82, -75)), + ((0, -49), (12, -67), (46, -63), (83, -42)), + ((0, -22), (17, -25), (45, -31), (83, -25)), + ((0, 1), (13, -5), (39, -7), (74, -1)), + ((0, 25), (18, 35), (39, 19), (72, 12)), + ((0, 62), (16, 50), (42, 49), (70, 42)), + ((0, 84), (15, 78), (38, 73), (65, 69)), + ((0, 101), (13, 112), (43, 93), (67, 87)), + ((0, 145), (18, 145), (43, 145), (66, 145)), + ) + palettes = ( + ("#F4EFDC", "#D2D9C7"), + ("#C2E0D9", "#85BCBC"), + ("#ACD5CC", "#55999D"), + ("#E4EBDF", "#A5C6C3"), + ("#EADFBD", "#D4BB87"), + ("#CBDFE6", "#83B1C2"), + ) + panes = [] + for sign in (-1, 1): + for i, (top, bottom) in enumerate(zip(rows, rows[1:], strict=False)): + for j in range(3): + a, b = top[j : j + 2] + d, c = bottom[j : j + 2] + + path = QPainterPath(QPointF(sign * a[0], a[1])) + for start, end, dx, dy in ( + (a, b, 0, -3), + (b, c, 3, 0), + (c, d, 0, -3), + (d, a, 3 if j else 0, 0), + ): + mid_x = sign * ((start[0] + end[0]) / 2 + dx) + mid_y = (start[1] + end[1]) / 2 + dy + path.quadTo(mid_x, mid_y, sign * end[0], end[1]) + path.closeSubpath() + tone = (i + 2 * j + int(sign > 0)) % len(palettes) + r = path.boundingRect() + panes.append( + (path, _gradient(r.left(), r.top(), r.right(), r.bottom(), *palettes[tone])) + ) + return tuple(panes) + + +def draw_glass(p: QPainter, outline: QPainterPath, organs: tuple[QPainterPath, ...]) -> None: + p.save() + p.setClipPath(outline, Qt.ClipOperation.IntersectClip) + lead = QPen(QColor("#466966"), 1.55) + for pane, glass in _glass_panes(): + p.fillPath(pane, glass) + p.strokePath(pane, lead) + glass_colors = ( + ("#DFF3E9", "#78BAB3"), + ("#D6E9E1", "#70AAAD"), + ("#9ED2C4", "#58998C"), + ("#F3DAA3", "#CEAB67"), + ("#DCDEEB", "#A29DBF"), + ("#D1DFE8", "#8CA4BD"), + ) + for shape, (light, dark) in zip(organs, glass_colors, strict=False): + r = shape.boundingRect() + p.fillPath(shape, _gradient(r.left(), r.top(), r.right(), r.bottom(), light, dark)) + p.save() + p.setClipPath(shape, Qt.ClipOperation.IntersectClip) + vein = QPainterPath(r.bottomLeft()) + vein.quadTo(r.center(), r.topRight()) + p.strokePath(vein, lead) + glint = QPainterPath() + glint.moveTo(r.left() + r.width() * 0.16, r.top() + r.height() * 0.55) + glint.quadTo( + r.left() + r.width() * 0.21, + r.top() + r.height() * 0.24, + r.center().x(), + r.top() + r.height() * 0.13, + ) + _stroke(p, glint, "#EDF6EA", 1.05) + p.restore() + p.strokePath(shape, lead) + p.restore() + _stroke(p, outline, "#41615E", 1.9) + + +@cache +def _wire_mesh() -> tuple[QPainterPath, QPainterPath]: + latitudes, meridians = QPainterPath(), QPainterPath() + for degrees in range(-72, 73, 18): + angle = math.radians(degrees) + line = QPainterPath() + for i in range(41): + sweep = math.pi * (i / 40 - 0.5) + x = 25 * math.cos(angle) * math.sin(sweep) + y = -126 + 30 * math.sin(angle) + 4 * math.cos(angle) * math.cos(sweep) + (line.lineTo if i else line.moveTo)(x, y) + latitudes.addPath(line) + for degrees in range(-75, 76, 15): + angle = math.radians(degrees) + line = QPainterPath() + for i in range(41): + elevation = math.pi * (i / 40 - 0.5) + x = 25 * math.sin(angle) * math.cos(elevation) + y = -126 + 30 * math.sin(elevation) + 4 * math.cos(angle) * math.cos(elevation) + (line.lineTo if i else line.moveTo)(x, y) + meridians.addPath(line) + # (elevation, silhouette half-width, forward bulge) along the body. + section = ( + (-96, 11, 2), + (-88, 20, 5), + (-81, 36, 7), + (-74, 58, 9), + (-64, 68, 12), + (-53, 71, 13), + (-40, 71, 13), + (-27, 70, 12), + (-14, 68, 12), + (0, 66, 9), + (14, 63, 7), + (28, 60, 6), + (42, 58, 7), + (56, 57, 8), + (70, 56, 9), + (84, 55, 10), + (98, 53, 10), + (112, 51, 8), + (125, 48, 7), + (139, 44, 6), + ) + for y, width, bulge in section: + latitudes.moveTo(-width, y) + latitudes.cubicTo(-width * 0.64, y + bulge * 1.34, width * 0.64, y + bulge * 1.34, width, y) + for degrees in range(-80, 81, 16): + angle = math.radians(degrees) + for i, (y, width, bulge) in enumerate(section): + x = width * math.sin(angle) + z = y + bulge * math.cos(angle) + (meridians.lineTo if i else meridians.moveTo)(x, z) + return latitudes, meridians + + +def draw_wireframe(p: QPainter, outline: QPainterPath, organs: tuple[QPainterPath, ...]) -> None: + p.save() + p.fillPath(outline, _gradient(-65, 15, 70, 10, "#21575C", "#347477", "#153E46")) + p.setClipPath(outline, Qt.ClipOperation.IntersectClip) + rings, meridians = _wire_mesh() + _stroke(p, rings, "#6AAEAF", 0.85) + _stroke(p, meridians, "#9CD9D1", 0.85) + for shape in organs: + r = shape.boundingRect() + p.fillPath(shape, QColor(24, 72, 77, 185)) + p.save() + p.setClipPath(shape, Qt.ClipOperation.IntersectClip) + net = QPainterPath() + for i in range(1, 5): + y = r.top() + r.height() * i / 5 + net.moveTo(r.left(), y) + net.quadTo(r.center().x(), y + r.width() * 0.27, r.right(), y) + for i in range(1, 4): + x = r.left() + r.width() * i / 4 + net.moveTo(x, r.top()) + net.quadTo(x - r.width() * 0.24, r.center().y(), x, r.bottom()) + _stroke(p, net, "#96C8B6", 0.68) + p.restore() + _stroke(p, shape, "#E0EBC5", 1.05) + p.restore() + _stroke(p, outline, "#AEF0DE", 1.3) + + +@cache +def _paper_edges() -> tuple[QPainterPath, ...]: + # One continuous scissor cut runs from the crown past the cheek and waist to the thigh. + cut = QPainterPath(QPointF(9, -161)) + cut.cubicTo(-18, -146, -18, -122, -3, -114) + cut.cubicTo(16, -104, 5, -86, -25, -79) + cut.cubicTo(-58, -67, -56, -24, -45, -1) + cut.cubicTo(-39, 15, -50, 29, -48, 49) + cut.cubicTo(-46, 73, -22, 83, -26, 105) + cut.quadTo(-30, 128, -39, 146) + cut.lineTo(90, 146) + cut.lineTo(90, -161) + cut.closeSubpath() + return tuple(cut.translated(dx, dy) for dx, dy in ((-13, 0), (-6, 0), (0, 0), (9, 0))) + + +def draw_papercut(p: QPainter, outline: QPainterPath, organs: tuple[QPainterPath, ...]) -> None: + p.save() + p.fillPath(outline.translated(2.5, 3.3), QColor(101, 72, 51, 65)) + p.fillPath(outline.translated(1.1, 1.6), QColor("#966954")) + p.fillPath(outline, QColor("#CFA381")) + p.setClipPath(outline, Qt.ClipOperation.IntersectClip) + for edge, tone in zip( + _paper_edges(), ("#B67C65", "#DBA37E", "#E9BB8E", "#F1D3AE"), strict=True + ): + p.fillPath(edge, QColor(tone)) + _stroke(p, edge, "#F8DDC0", 0.7) + collar = QPainterPath(QPointF(-50, -79)) + collar.quadTo(-13, -80, -3, -60) + collar.quadTo(9, -80, 46, -79) + collar.quadTo(11, -91, 12, -98) + collar.lineTo(-12, -98) + collar.quadTo(-12, -86, -50, -79) + p.fillPath(collar.translated(0, 1.8), QColor("#C89A72")) + p.fillPath(collar, QColor("#F7E1BB")) + sheets = ("#FFE7B9", "#F8D49C", "#C7876A", "#E3BB77", "#BC8B87", "#C5958A") + for shape, sheet in zip(organs, sheets, strict=False): + p.fillPath(shape.translated(2.1, 2.7), QColor(117, 77, 62, 96)) + p.fillPath(shape.translated(0.6, 1.3), QColor("#AE8062")) + p.fillPath(shape, QColor(sheet)) + p.save() + p.setClipPath(shape, Qt.ClipOperation.IntersectClip) + inset = shape.translated(3.0, 1.3) + _stroke(p, inset, "#FFEDCB", 0.9) + p.restore() + p.restore() + + +_PIXEL_COLORS = ( + "#334D72", + "#6987AA", + "#87A2C0", + "#B0C4D8", + "#D8EBEC", + "#8298BC", + "#47658A", + "#98CFD8", + "#689BB1", + "#D0E9E7", + "#A495C6", + "#877BA9", + "#F0CC87", + "#BF9C6E", + "#A6B3D6", + "#7889AC", +) + + +def _pixel_sprite( + outline: QPainterPath, organs: tuple[QPainterPath, ...] +) -> tuple[tuple[QPainterPath, QColor], ...]: + cell = 5 + covered = {} + for row in range(-31, 28): + for col in range(-15, 15): + center = QPointF((col + 0.5) * cell, (row + 0.5) * cell) + if outline.contains(center): + covered[col, row] = next( + (i for i, path in enumerate(organs) if path.contains(center)), -1 + ) + layers = [QPainterPath() for _ in _PIXEL_COLORS] + for (x, y), organ in covered.items(): + left = covered.get((x - 1, y)) + top = covered.get((x, y - 1)) + right = covered.get((x + 1, y)) + bottom = covered.get((x, y + 1)) + if None in (left, top, right, bottom): + ink = 0 + elif organ >= 0: + base = (7, 7, 10, 12, 14, 14)[organ] + ink = base + int(right != organ or bottom != organ) + if organ in (0, 1) and (left != organ or top != organ): + ink = 9 + elif (x - 2, y) not in covered or (x, y - 2) not in covered: + ink = 4 + elif (x + 3, y) not in covered or (x, y + 2) not in covered: + ink = 6 + elif x > 6 or (y > 16 and x > 1): + ink = 1 if (x + y) % 4 else 5 + elif x < -4 or (y < -25 and x < 1): + ink = 3 + else: + ink = 2 + layers[ink].addRect(QRectF(cell * x, cell * y, cell, cell)) + return tuple( + (layer, QColor(color)) for layer, color in zip(layers, _PIXEL_COLORS, strict=True) + ) + + +def draw_pixel(p: QPainter, outline: QPainterPath, organs: tuple[QPainterPath, ...]) -> None: + p.save() + p.setRenderHint(QPainter.RenderHint.Antialiasing, False) + for pixels, ink in _pixel_sprite(outline, organs): + p.fillPath(pixels, ink) + p.restore() diff --git a/app/src/doctor_workstation/ui/visuals/twin_print_styles.py b/app/src/doctor_workstation/ui/visuals/twin_print_styles.py new file mode 100644 index 000000000..618312a74 --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/twin_print_styles.py @@ -0,0 +1,275 @@ +"""Four vector print treatments for the clinical body atlas.""" + +from __future__ import annotations + +import math +from contextlib import contextmanager +from functools import lru_cache +from random import Random + +from PySide6.QtCore import QPointF, Qt +from PySide6.QtGui import ( + QColor, + QLinearGradient, + QPainter, + QPainterPath, + QPen, + QPolygonF, + QTransform, +) + + +@contextmanager +def _saved(p: QPainter, clip: QPainterPath | None = None): + p.save() + try: + p.setRenderHint(QPainter.RenderHint.Antialiasing) + if clip is not None: + p.setClipPath(clip, Qt.ClipOperation.IntersectClip) + yield + finally: + p.restore() + + +def _stroke(p: QPainter, path: QPainterPath, color: str, width: float) -> None: + pen = QPen(QColor(color), width) + pen.setCapStyle(Qt.PenCapStyle.RoundCap) + pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin) + p.strokePath(path, pen) + + +def _curve(path: QPainterPath, start: tuple, *segments: tuple) -> None: + path.moveTo(*start) + for segment in segments: + path.cubicTo(*segment) + + +def _both_sides(path: QPainterPath) -> QPainterPath: + result = QPainterPath(path) + result.addPath(QTransform.fromScale(-1, 1).map(path)) + return result + + +@lru_cache(maxsize=1) +def _figure_lines() -> tuple[QPainterPath, QPainterPath, QPainterPath]: + # Long gestures describe the arm, clavicle and folded iliac crest. + side = QPainterPath() + _curve(side, (5, -91), (9, -78, 19, -78, 31, -77), (42, -77, 50, -74, 54, -71)) + _curve(side, (63, -65), (55, -66, 49, -55, 48, -40), (45, -19, 51, -9, 55, 4)) + _curve(side, (56, 11), (49, 29, 50, 47, 47, 63)) + _curve(side, (46, 73), (42, 89, 20, 94, 12, 108), (9, 115, 7, 120, 6, 125)) + _curve(side, (43, 93), (41, 101, 35, 124, 34, 134)) + silhouette = _both_sides(side) + + face = QPainterPath() + _curve(face, (19, -137), (22, -129, 18, -115, 13, -109), (10, -106, 7, -104, 4, -103)) + _curve(face, (16, -133), (12, -136, 7, -135, 5, -133)) + _curve(face, (7, -130), (10, -131, 13, -131, 15, -130)) + face = _both_sides(face) + _curve(face, (-1, -132), (-1, -127, -2, -123, -4, -121), (-2, -119, 1, -120, 3, -120)) + _curve(face, (-5, -114), (-2, -115, 2, -115, 5, -114)) + + branches = QPainterPath() + _curve(branches, (0, -76), (1, -63, 14, -58, 18, -49), (20, -41, 24, -32, 33, -25)) + _curve(branches, (16, -53), (20, -53, 25, -54, 29, -59)) + _curve(branches, (20, -46), (28, -43, 32, -42, 36, -45)) + _curve(branches, (23, -39), (20, -36, 18, -31, 17, -27)) + branches = _both_sides(branches) + _curve(branches, (-37, 2), (-25, 10, -17, 12, -4, 13)) + _curve(branches, (-26, 8), (-27, 13, -25, 16, -23, 18)) + _curve(branches, (-8, 23), (8, 27, 17, 26, 29, 26)) + return silhouette, face, branches + + +@lru_cache(maxsize=1) +def _engraving() -> QPainterPath: + strokes = QPainterPath() + for i in range(7): + x, y = 11 + i * 1.6, -105 - i * 2.5 + _curve(strokes, (x, y), (x + 3, y - 3, x + 4, y - 6, x + 4.5, y - 8)) + for i in range(12): + x, y = 55 + i * 1.45, -65 + i * 1.75 + _curve(strokes, (x, y), (x - 4, y + 6, x - 6, y + 14, x - 6.5, y + 23)) + for i in range(14): + x, y = 46 + i * 1.35, 66 + i * 1.65 + _curve(strokes, (x, y), (x - 2, y + 7, x - 6, y + 13, x - 9, y + 16)) + for i in range(9): + x, y = 19 + i * 2.45, -20 - i * 0.55 + _curve(strokes, (x, y), (x - 2, y - 2, x - 4, y - 5, x - 4.5, y - 8)) + return _both_sides(strokes) + + +def draw_ink(p: QPainter, outline: QPainterPath, organs: tuple[QPainterPath, ...]) -> None: + """Warm rag paper, modulated wash and fine pen hatching.""" + with _saved(p): + wash = QLinearGradient(-63, -13, 69, 10) + for stop, color in ((0, "#d2bc96"), (0.23, "#ebdbb9"), (0.53, "#fff2d6"), (0.85, "#f2e1be"), (1, "#cbb28b")): + wash.setColorAt(stop, QColor(color)) + p.fillPath(outline, wash) + _stroke(p, outline, "#584a38", 1.65) + structure, face, branches = _figure_lines() + with _saved(p, outline): + _stroke(p, structure, "#8c7657", 1.04) + _stroke(p, face, "#8c775c", 0.76) + tints = ("#e2c3a1", "#e2c3a1", "#cda77d", "#e7ca92", "#dcb78e", "#dcb78e") + for organ, tint in zip(organs, tints, strict=False): + p.fillPath(organ, QColor(tint)) + _stroke(p, organ, "#735943", 1.12) + _stroke(p, _engraving(), "#9f8362", 0.60) + _stroke(p, branches, "#947454", 0.80) + + +@lru_cache(maxsize=1) +def _drafting() -> tuple[QPainterPath, QPainterPath, QPainterPath, QPainterPath]: + mesh = QPainterPath() + for x in range(-80, 81, 10): + mesh.moveTo(x, -158) + mesh.lineTo(x, 141) + for y in range(-150, 141, 10): + mesh.moveTo(-83, y) + mesh.lineTo(83, y) + marks = QPainterPath() + for y, half_width in ((-126, 35), (-65, 82), (27, 69), (136, 55)): + for sign in (-1, 1): + x = sign * half_width + marks.moveTo(x - 2.5, y) + marks.lineTo(x + 2.5, y) + marks.moveTo(x, y - 2.5) + marks.lineTo(x, y + 2.5) + levels = QPainterPath() + for y, span in ((-126, 30), (-65, 76), (27, 63), (136, 50)): + levels.moveTo(-span, y) + levels.lineTo(span, y) + levels.moveTo(0, -157) + levels.lineTo(0, 139) + ribs = QPainterPath() + for i in range(4): + y = -61 + i * 9 + _curve(ribs, (2, y), (11, y + 1, 30, y - 13, 40 + i, y - 4)) + _curve(ribs, (6, -17), (17, -7, 35, -5, 43, -14)) + _curve(ribs, (0, 93), (13, 90, 33, 72, 45, 74)) + _curve(ribs, (0, 102), (13, 101, 30, 90, 37, 83)) + framework = _both_sides(ribs) + framework.addEllipse(QPointF(0, -126), 14, 27) + framework.addEllipse(QPointF(0, -127), 22, 7) + return mesh, marks, levels, framework + + +def draw_blueprint(p: QPainter, outline: QPainterPath, organs: tuple[QPainterPath, ...]) -> None: + """Cyanotype with registration crosses, sectional guides and white linework.""" + with _saved(p): + mesh, marks, levels, framework = _drafting() + p.fillPath(outline, QColor("#184669")) + with _saved(p, outline): + _stroke(p, mesh, "#436887", 0.46) + structure, _, _ = _figure_lines() + _stroke(p, structure, "#98cde3", 0.91) + for organ in organs: + p.fillPath(organ, QColor("#316489")) + _stroke(p, organ, "#e8f7fc", 1.34) + _stroke(p, framework, "#a1cadf", 0.77) + pen = QPen(QColor("#87b6c9"), 0.58) + pen.setDashPattern([7, 4, 1.5, 4]) + p.strokePath(levels, pen) + _stroke(p, marks, "#c7e7f3", 0.82) + _stroke(p, outline, "#e1f4fd", 1.54) + + +@lru_cache(maxsize=1) +def _stipple_plates() -> tuple[tuple[QPolygonF, ...], tuple[QPolygonF, ...]]: + # Engraved dots accumulate in the turning planes of the brow, arm and flank. + random = Random(63019) + body = tuple(QPolygonF() for _ in range(3)) + tissue = tuple(QPolygonF() for _ in range(3)) + for _ in range(8500): + x, y = random.uniform(-75, 75), random.uniform(-157, 139) + if y < -96: + edge = math.hypot(x / 24, (y + 126) / 29) + density = 0.025 + 0.52 * edge**4 + 0.11 * (x + 24) / 48 + density += 0.42 * math.exp(-((abs(x) - 11) / 8) ** 2 - ((y + 127) / 3) ** 2) + density += 0.32 * math.exp(-((x - 13) / 7) ** 2 - ((y + 113) / 8) ** 2) + else: + edge = abs(x) / (61 - 0.068 * y) + density = 0.027 + 0.34 * edge**3 + 0.09 * (x + 74) / 148 + density += 0.64 * math.exp(-((abs(x) - 32) / 17) ** 2 - ((y - 92) / 10) ** 2) + density += 0.52 * math.exp(-((abs(x) - 54) / 6) ** 2 - ((y + 38) / 26) ** 2) + if random.random() < density: + body[random.randrange(3)].append(QPointF(x, y)) + if abs(x) < 45 and -69 < y < 74 and random.random() < 0.42: + tissue[random.randrange(3)].append(QPointF(x, y)) + return body, tissue + + +def _print_dots(p: QPainter, groups: tuple[QPolygonF, ...], color: str) -> None: + for points, diameter in zip(groups, (0.65, 0.99, 1.35), strict=True): + pen = QPen(QColor(color), diameter) + pen.setCapStyle(Qt.PenCapStyle.RoundCap) + p.setPen(pen) + p.drawPoints(points) + + +def draw_stipple(p: QPainter, outline: QPainterPath, organs: tuple[QPainterPath, ...]) -> None: + """Copperplate stippling, with tonal dots printed from cached vector plates.""" + with _saved(p): + body_dots, organ_dots = _stipple_plates() + p.fillPath(outline, QColor("#f5e5d0")) + with _saved(p, outline): + _print_dots(p, body_dots, "#8f6954") + structure, face, branches = _figure_lines() + _stroke(p, structure, "#997661", 0.82) + _stroke(p, face, "#805d50", 0.85) + organ_mask = QPainterPath() + organ_mask.setFillRule(Qt.FillRule.WindingFill) + tones = ("#e1c6af", "#e1c6af", "#ccaa8e", "#edcfad", "#d6b49c", "#d6b49c") + for organ, tone in zip(organs, tones, strict=False): + p.fillPath(organ, QColor(tone)) + _stroke(p, organ, "#785444", 1.18) + organ_mask.addPath(organ) + with _saved(p, organ_mask): + _print_dots(p, organ_dots, "#785648") + _stroke(p, branches, "#9b7861", 0.68) + _stroke(p, outline, "#714e41", 1.37) + + +@lru_cache(maxsize=1) +def _relief_lines() -> QPainterPath: + """Interpolated cross-sections around the brow, chest, hips and upper legs.""" + relief = QPainterPath() + for baseline in range(-182, 167, 6): + points = [] + for x in range(-84, 85, 7): + deflection = 0 + for cx, cy, rx, ry, height in ( + (0, -137, 19, 24, -17), (-31, -53, 24, 32, -22), (31, -53, 24, 32, -22), + (0, 0, 28, 24, 12), (0, 49, 23, 34, -19), (-35, 91, 19, 33, -20), + (35, 91, 19, 33, -20), + ): + deflection += height * math.exp(-((x - cx) / rx) ** 2 - ((baseline - cy) / ry) ** 2) + points.append(QPointF(x, baseline + deflection)) + relief.moveTo(points[0]) + for point, following in zip(points[1:-1], points[2:], strict=True): + relief.quadTo(point, (point + following) * 0.5) + relief.lineTo(points[-1]) + return relief + + +def draw_contours(p: QPainter, outline: QPainterPath, organs: tuple[QPainterPath, ...]) -> None: + """Celadon relief map with continuous section lines and nested organ contours.""" + with _saved(p): + p.fillPath(outline, QColor("#d4e5d8")) + with _saved(p, outline): + _stroke(p, _relief_lines(), "#93b6a6", 0.83) + structure, face, _ = _figure_lines() + _stroke(p, structure, "#769c8e", 0.85) + _stroke(p, face, "#668979", 0.78) + for organ in organs: + center = organ.boundingRect().center() + p.fillPath(organ, QColor("#a4c8b5")) + _stroke(p, organ, "#416f65", 1.19) + for level in (0.72, 0.44, 0.17): + transform = QTransform() + transform.translate(center.x(), center.y()) + transform.scale(level, level) + transform.translate(-center.x(), -center.y()) + _stroke(p, transform.map(organ), "#668f7e", 0.70) + _stroke(p, outline, "#527d71", 1.42) diff --git a/app/src/doctor_workstation/ui/visuals/twin_stage.py b/app/src/doctor_workstation/ui/visuals/twin_stage.py index 0a78546df..6bff54f09 100644 --- a/app/src/doctor_workstation/ui/visuals/twin_stage.py +++ b/app/src/doctor_workstation/ui/visuals/twin_stage.py @@ -4,23 +4,27 @@ from __future__ import annotations import math -from PySide6.QtCore import QPointF, QRectF, QSize, Qt, QTimer, Signal +from PySide6.QtCore import QPointF, QRectF, QSettings, QSize, Qt, QTimer, Signal from PySide6.QtGui import ( + QActionGroup, QColor, QFont, - QLinearGradient, QMouseEvent, QPainter, QPainterPath, QPen, QRadialGradient, + QResizeEvent, QTextOption, ) -from PySide6.QtWidgets import QWidget +from PySide6.QtWidgets import QMenu, QToolButton, QWidget from .. import motion from ..reception_style import body_family, heading_family from ..viewmodels.cockpit_vm import CockpitSnapshotVM, TwinCalloutNode +from .twin_stage_styles import BODY_BOUNDS, TWIN_STYLES, body_image, style_icon + +_STYLE_SETTING = "appearance/twinStageStyle" _MODES: tuple[tuple[str, str], ...] = ( ("sanjiao", "全身症候"), @@ -36,7 +40,7 @@ class ClinicalTwinStageWidget(QWidget): locus_clicked = Signal(str) open_chart_requested = Signal() - def __init__(self, parent: QWidget | None = None) -> None: + def __init__(self, parent: QWidget | None = None, *, settings: QSettings | None = None) -> None: super().__init__(parent) self.setObjectName("ClinicalTwinStageWidget") self.setMouseTracking(True) @@ -51,11 +55,72 @@ class ClinicalTwinStageWidget(QWidget): self._bottom_capsule_rect = QRectF() self._active_popover: tuple[str, QRectF] | None = None self._hover_target = "" + self._settings = settings if settings is not None else QSettings("ZhenYangTang", "DoctorWorkstation") + saved = self._settings.value(_STYLE_SETTING, "jade") + self._style_key = saved if isinstance(saved, str) and saved in TWIN_STYLES else "jade" + self.style_button = QToolButton(self) + self.style_button.setObjectName("TwinStyleButton") + self.style_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) + self.style_button.setCursor(Qt.CursorShape.PointingHandCursor) + self.style_button.setStyleSheet( + "QToolButton#TwinStyleButton { background: #FFFFFF; color: #203A35;" + " border: 1px solid #CDDCD7; border-radius: 14px; padding: 0 12px 0 4px;" + " font-size: 11px; font-weight: 600; }" + "QToolButton#TwinStyleButton:hover, QToolButton#TwinStyleButton:focus {" + " background: #EBF5F1; border-color: #549384; }" + "QToolButton#TwinStyleButton::menu-indicator { subcontrol-position: right center;" + " subcontrol-origin: padding; right: 5px; }" + ) + menu = QMenu(self.style_button) + group = QActionGroup(menu) + for key, style in TWIN_STYLES.items(): + action = group.addAction(menu.addAction(style.title)) + action.setCheckable(True) + action.setData(key) + action.setChecked(key == self._style_key) + group.triggered.connect(lambda action: self.set_style(action.data())) + menu.aboutToShow.connect(self._load_style_icons) + self.style_button.setMenu(menu) + self._position_style_button() self._anim_timer = QTimer(self) self._anim_timer.setInterval(900) self._anim_timer.timeout.connect(self._tick_breath) + @property + def style_key(self) -> str: + return self._style_key + + def set_style(self, key: str) -> None: + if key not in TWIN_STYLES or key == self._style_key: + return + self._style_key = key + self._settings.setValue(_STYLE_SETTING, key) + for action in self.style_button.menu().actions(): + action.setChecked(action.data() == key) + self._hover_target = "" + self._active_popover = None + self._position_style_button() + self.update() + + def _load_style_icons(self) -> None: + for action in self.style_button.menu().actions(): + if action.icon().isNull(): + action.setIcon(style_icon(action.data())) + + def _position_style_button(self) -> None: + title = TWIN_STYLES[self._style_key].title + wide = self.width() >= 580 + width = 116 if wide else 58 + self.style_button.setText(f"样式 · {title}" if wide else "样式") + self.style_button.setAccessibleName(f"选择图谱样式,当前为{title}") + self.style_button.setToolTip(f"图谱样式 · {title}") + self.style_button.setGeometry(self.width() - width - 13, self.height() - 43, width, 30) + + def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 + super().resizeEvent(event) + self._position_style_button() + def sizeHint(self) -> QSize: # noqa: N802 return QSize(580, 500) @@ -162,7 +227,7 @@ class ClinicalTwinStageWidget(QWidget): *, dimmed: bool = False, ) -> None: - """Paint an anatomical translucent Jade-Crystal Human Body & Metabolic Organs Twin.""" + """Composite the selected illustration with the current case's evidence.""" cx = rect.center().x() cy = rect.center().y() + 4.0 @@ -170,132 +235,15 @@ class ClinicalTwinStageWidget(QWidget): scale = max(0.58, min(1.15, (h - 110.0) / 340.0)) if rect.width() < 430.0: scale *= 0.82 - alpha_mul = 0.42 if dimmed else 1.0 - - def _c(r_v: int, g_v: int, b_v: int, a_v: int) -> QColor: - 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)) + painter.save() + painter.translate(cx, cy) + painter.scale(scale, scale) + painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) + if dimmed: + painter.setOpacity(0.42) + painter.drawImage(BODY_BOUNDS, body_image(self._style_key)) + painter.restore() if dimmed: return @@ -368,7 +316,8 @@ class ClinicalTwinStageWidget(QWidget): dot_hex, pill_bg_hex, pill_fg_hex = tone_map.get(node.status_tone, tone_map["neutral"]) painter.setBrush(Qt.BrushStyle.NoBrush) - painter.setPen(QPen(QColor("#8BA29E"), 1.0, Qt.PenStyle.DashLine)) + style = TWIN_STYLES[self._style_key] + painter.setPen(QPen(QColor(style.caption), 1.0, Qt.PenStyle.DashLine)) painter.drawLine(line_start, anchor) painter.setPen(QPen(QColor("#FFFFFF"), 2.0)) @@ -377,7 +326,8 @@ class ClinicalTwinStageWidget(QWidget): hovered = self._hover_target == f"locus:{node.locus_id}" cpath = QPainterPath() - cpath.addRoundedRect(card_rect, 12.0 if compact else 15.0, 12.0 if compact else 15.0) + radius = min(12, style.card_radius) if compact else style.card_radius + cpath.addRoundedRect(card_rect, radius, radius) 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)) @@ -458,6 +408,34 @@ class ClinicalTwinStageWidget(QWidget): ) return card_rect + def _draw_backdrop(self, painter: QPainter, rect: QRectF) -> None: + style = TWIN_STYLES[self._style_key] + painter.save() + painter.setClipRect(rect.adjusted(8, 51, -8, -49)) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.setOpacity(0.44 if style.backdrop == "rings" else 0.30) + pen = QPen(QColor(style.guide), 1) + painter.setPen(pen) + if style.backdrop == "rings": + scale = max(0.72, min(1.18, min(rect.width(), rect.height()) / 490)) + for radius in (175 * scale, 132 * scale): + painter.drawEllipse(rect.center() + QPointF(0, 4), radius, radius) + pen.setStyle(Qt.PenStyle.DashLine) + painter.setPen(pen) + elif style.backdrop == "grid": + center = rect.center().toPoint() + for x in range(center.x() % 24, self.width(), 24): + painter.drawLine(x, 50, x, self.height() - 49) + for y in range(center.y() % 24, self.height(), 24): + painter.drawLine(8, y, self.width() - 8, y) + elif style.backdrop == "plate": + frame = rect.adjusted(21, 62, -21, -55) + for point, dx, dy in ((frame.topLeft(), 1, 1), (frame.topRight(), -1, 1), + (frame.bottomLeft(), 1, -1), (frame.bottomRight(), -1, -1)): + painter.drawLine(point, point + QPointF(22 * dx, 0)) + painter.drawLine(point, point + QPointF(0, 15 * dy)) + painter.restore() + def paintEvent(self, _event: object) -> None: # noqa: N802 painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) @@ -468,9 +446,9 @@ class ClinicalTwinStageWidget(QWidget): 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")) + style = TWIN_STYLES[self._style_key] + bg_grad.setColorAt(0.0, QColor(style.center)) + bg_grad.setColorAt(1.0, QColor(style.edge)) painter.setBrush(Qt.BrushStyle.NoBrush) painter.fillPath(stage_path, bg_grad) painter.setPen(QPen(QColor("#E1EBE8"), 1.0)) @@ -478,24 +456,12 @@ class ClinicalTwinStageWidget(QWidget): 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) + self._draw_backdrop(painter, rect) # Top Segmented Mode Pill Island: [全身症候 / 病史用药 / 四诊处方] narrow_bar = rect.width() < 395.0 - pill_w = 198.0 if narrow_bar else 246.0 + chart_btn_w = 64.0 if narrow_bar else 108.0 + pill_w = min(198.0, rect.width() - chart_btn_w - 26) if narrow_bar else 246.0 pill_host = QRectF(rect.left() + (10 if narrow_bar else 16), rect.top() + 14, pill_w, 34) pill_host_path = QPainterPath() pill_host_path.addRoundedRect(pill_host, 17.0, 17.0) @@ -521,7 +487,6 @@ class ClinicalTwinStageWidget(QWidget): painter.drawText(m_rect, Qt.AlignmentFlag.AlignCenter, m_label) vm = self._snapshot.twin_for_mode(self._mode_key) if self._snapshot else None - chart_btn_w = 82.0 if narrow_bar else 108.0 self._open_chart_rect = QRectF( rect.right() - chart_btn_w - (10 if narrow_bar else 16), rect.top() + 15, chart_btn_w, 32 ) @@ -543,7 +508,7 @@ class ClinicalTwinStageWidget(QWidget): ) self._scan_badge_rect = QRectF() - if vm is not None and rect.width() >= 520: + if vm is not None and self._open_chart_rect.left() - pill_host.right() >= 164: badge_w = 148.0 scan_rect = QRectF(self._open_chart_rect.left() - badge_w - 8, rect.top() + 15, badge_w, 32) self._scan_badge_rect = scan_rect @@ -569,7 +534,8 @@ class ClinicalTwinStageWidget(QWidget): 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) + empty_width = min(390.0, rect.width() - 24) + empty_box = QRectF(cx - empty_width / 2, cy - 44, empty_width, 88) ep = QPainterPath() ep.addRoundedRect(empty_box, 18.0, 18.0) painter.setBrush(Qt.BrushStyle.NoBrush) @@ -615,13 +581,12 @@ class ClinicalTwinStageWidget(QWidget): 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.setPen(QColor(style.caption)) painter.drawText(QRectF(rect.left() + 31, ly + dy - 1, 86, 15), Qt.AlignmentFlag.AlignLeft, txt) - cap_w = min(380.0, max(180.0, rect.width() - 180.0)) - cap_rect = QRectF(cx - cap_w * 0.5 + 24.0, rect.bottom() - 44, cap_w, 32) - else: - cap_w = max(160.0, rect.width() - 24.0) - cap_rect = QRectF(rect.left() + 12.0, rect.bottom() - 42, cap_w, 30) + footer_left = rect.left() + (120.0 if show_legend else 12.0) + footer_right = self.style_button.x() - 8.0 + cap_w = min(380.0, footer_right - footer_left) + cap_rect = QRectF((footer_left + footer_right - cap_w) / 2, rect.bottom() - 44, cap_w, 32) self._bottom_capsule_rect = cap_rect self._active_popover = None wpath = QPainterPath() diff --git a/app/src/doctor_workstation/ui/visuals/twin_stage_styles.py b/app/src/doctor_workstation/ui/visuals/twin_stage_styles.py new file mode 100644 index 000000000..883a4b964 --- /dev/null +++ b/app/src/doctor_workstation/ui/visuals/twin_stage_styles.py @@ -0,0 +1,141 @@ +"""Illustration presets for the workstation's clinical evidence map.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from functools import lru_cache + +from PySide6.QtCore import QPointF, QRectF, Qt +from PySide6.QtGui import ( + QColor, + QIcon, + QImage, + QLinearGradient, + QPainter, + QPainterPath, + QPen, + QPixmap, +) + +from .twin_material_styles import draw_facets, draw_glass, draw_papercut, draw_pixel, draw_wireframe +from .twin_print_styles import draw_blueprint, draw_contours, draw_ink, draw_stipple + + +@lru_cache(maxsize=1) +def _body_paths() -> tuple[QPainterPath, tuple[QPainterPath, ...]]: + outline = QPainterPath() + outline.addEllipse(QPointF(0, -126), 25, 30) + outline.moveTo(-11, -96) + outline.quadTo(-14, -84, -58, -74) + outline.cubicTo(-78, -68, -76, -20, -60, 28) + outline.cubicTo(-54, 62, -58, 98, -44, 138) + outline.lineTo(-14, 138) + outline.quadTo(0, 108, 14, 138) + outline.lineTo(44, 138) + outline.cubicTo(58, 98, 54, 62, 60, 28) + outline.cubicTo(76, -20, 78, -68, 58, -74) + outline.quadTo(14, -84, 11, -96) + outline.closeSubpath() + + organs = [] + for side in (-1, 1): + lung = QPainterPath(QPointF(side * 6, -66)) + lung.cubicTo(side * 38, -70, side * 46, -34, side * 40, -12) + lung.quadTo(side * 18, -8, side * 6, -22) + lung.closeSubpath() + organs.append(lung) + + liver = QPainterPath(QPointF(-42, -2)) + liver.cubicTo(-18, -6, 6, 2, 8, 14) + liver.cubicTo(-12, 26, -38, 28, -42, -2) + pancreas = QPainterPath(QPointF(-14, 22)) + pancreas.cubicTo(6, 14, 28, 18, 36, 26) + pancreas.cubicTo(24, 36, 2, 36, -14, 22) + organs.extend((liver, pancreas)) + for side in (-1, 1): + kidney = QPainterPath() + kidney.addRoundedRect(QRectF(side * 22 - 9, 42, 18, 28), 9, 9) + organs.append(kidney) + return outline, tuple(organs) + + +def _draw_jade(p: QPainter, outline: QPainterPath, organs: tuple[QPainterPath, ...]) -> None: + gradient = QLinearGradient(0, -155, 0, 140) + gradient.setColorAt(0, QColor(216, 240, 234, 185)) + gradient.setColorAt(.5, QColor(132, 198, 184, 128)) + gradient.setColorAt(1, QColor(64, 142, 128, 145)) + p.fillPath(outline, gradient) + p.strokePath(outline, QPen(QColor(255, 255, 255, 210), 2)) + p.strokePath(outline, QPen(QColor(16, 106, 90, 95), 1.1)) + p.setPen(QPen(QColor(255, 255, 255, 150), 2.2)) + p.drawLine(0, -94, 0, 92) + p.setPen(QPen(QColor(14, 111, 92, 95), 1, Qt.PenStyle.DashLine)) + p.drawLine(0, -135, 0, 115) + pancreas = QLinearGradient(-14, 16, 36, 34) + pancreas.setColorAt(0, QColor(223, 199, 147, 195)) + pancreas.setColorAt(1, QColor(14, 111, 92, 155)) + lung = QColor(255, 255, 255, 76) + kidney = QColor(20, 112, 96, 120) + fills = (lung, lung, QColor(22, 124, 104, 115), pancreas, kidney, kidney) + for index, (path, fill) in enumerate(zip(organs, fills, strict=True)): + p.fillPath(path, fill) + edge = QColor(14, 111, 92, 78) if index < 2 else QColor(255, 255, 255, 165) + p.strokePath(path, QPen(edge, 1)) + p.setPen(QPen(QColor(14, 111, 92, 95), 1.2)) + for side in (-1, 1): + p.drawLine(side * 22, 70, side * 28, 128) + + +@dataclass(frozen=True) +class TwinStyle: + title: str + draw: Callable[[QPainter, QPainterPath, tuple[QPainterPath, ...]], None] + center: str + edge: str + guide: str + caption: str + backdrop: str + card_radius: int + + +TWIN_STYLES = { + "jade": TwinStyle("玉色透视", _draw_jade, "#FAFCFB", "#ECF2F0", "#B6CCC5", "#5C726F", "rings", 15), + "ink": TwinStyle("本草墨线", draw_ink, "#FFFCF2", "#F2EBDC", "#C7B99F", "#655B49", "plate", 4), + "blueprint": TwinStyle("靛蓝晒图", draw_blueprint, "#234E70", "#14344F", "#7698B0", "#D3E3EB", "grid", 4), + "stipple": TwinStyle("铜版点描", draw_stipple, "#FFFBF3", "#EEE4D5", "#C4AF95", "#6A5947", "plate", 7), + "contours": TwinStyle("等高线描", draw_contours, "#F7FBF4", "#E2EEE0", "#A9C2AC", "#405F51", "plain", 14), + "facets": TwinStyle("晶面折纸", draw_facets, "#FAF8FF", "#EAE5F3", "#C5B8D6", "#625575", "plain", 5), + "glass": TwinStyle("彩窗拼片", draw_glass, "#FFFDF4", "#EFE9D6", "#BBAC85", "#645B43", "rings", 12), + "wireframe": TwinStyle("空间线框", draw_wireframe, "#19494B", "#0E3438", "#6A9D9C", "#D3EBE6", "grid", 7), + "papercut": TwinStyle("层叠剪纸", draw_papercut, "#FFF7EA", "#F0DDC7", "#C9A98E", "#725942", "plain", 12), + "pixel": TwinStyle("像素拼图", draw_pixel, "#F7FAFF", "#E0E7EE", "#A8B6C5", "#475D70", "grid", 2), +} + + +# Render each static illustration once at high resolution. Live evidence and hover +# feedback are drawn on a separate pass and never enter this cache. +BODY_BOUNDS = QRectF(-88, -162, 176, 308) + + +@lru_cache(maxsize=len(TWIN_STYLES)) +def body_image(key: str) -> QImage: + scale = 3 + image = QImage(BODY_BOUNDS.size().toSize() * scale, QImage.Format.Format_ARGB32_Premultiplied) + image.fill(Qt.GlobalColor.transparent) + with QPainter(image) as painter: + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + painter.scale(scale, scale) + painter.translate(-BODY_BOUNDS.topLeft()) + TWIN_STYLES[key].draw(painter, *_body_paths()) + return image + + +def style_icon(key: str) -> QIcon: + # A torso detail stays recognizable at the menu's small icon size. + swatch = QPixmap(72, 72) + swatch.fill(QColor(TWIN_STYLES[key].center)) + with QPainter(swatch) as painter: + painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) + painter.drawImage(QRectF(0, 0, 72, 72), body_image(key), QRectF(72, 290, 384, 384)) + return QIcon(swatch) diff --git a/app/tests/test_cockpit_layout_v5.py b/app/tests/test_cockpit_layout_v5.py new file mode 100644 index 000000000..eaecacda4 --- /dev/null +++ b/app/tests/test_cockpit_layout_v5.py @@ -0,0 +1,259 @@ +"""Automated verification of Clinical OS 5.0 Modular Cockpit (Remove, 4 Layouts, Reorder & Persist).""" + +from __future__ import annotations + +import os +from pathlib import Path + +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.services.demo_repository import DemoDoctorRepository +from doctor_workstation.ui.shell_spatial import SpatialShellWindow +from doctor_workstation.ui.theme import apply_theme +from doctor_workstation.ui.visuals.cockpit_layout import ( + ALL_CARD_KEYS, + COCKPIT_CARD_SPECS, + COCKPIT_PRESET_SUITES, + DEFAULT_CARD_ORDER, +) +from doctor_workstation.ui.visuals.reception_cockpit import ReceptionDigitalTwinCockpit + + +def _settle(app: QApplication, rounds: int = 12) -> None: + for _ in range(rounds): + app.processEvents() + QTest.qWait(6) + + +@pytest.fixture(scope="module") +def application() -> QApplication: + app = QApplication.instance() or QApplication([]) + apply_theme(app) + return app + + +def test_cockpit_card_remove_restore_guard_and_persistence( + application: QApplication, + tmp_path: Path, +) -> None: + store_file = tmp_path / "cockpit_layout.json" + cockpit = ReceptionDigitalTwinCockpit( + layout_storage_path=store_file, + persist_layout=True, + ) + cockpit.resize(1380, 760) + cockpit.show() + _settle(application, 6) + + try: + assert cockpit.layout_state.visible_cards == list(DEFAULT_CARD_ORDER) + + # 1. Remove 2 cards ('care_team' and 'fasting') + assert cockpit.remove_card("care_team") is True + assert cockpit.remove_card("fasting") is True + _settle(application, 4) + + assert not cockpit._card_tiles["care_team"].isVisible() + assert not cockpit._card_tiles["fasting"].isVisible() + assert set(cockpit.layout_state.removed_cards) == {"care_team", "fasting"} + + # 2. Removing down to 1 card succeeds, but removing the VERY LAST card is blocked! + assert cockpit.remove_card("diurnal") is True + assert cockpit.remove_card("queue") is True + assert cockpit.remove_card("journey") is True + assert cockpit.layout_state.visible_cards == ["twin_stage"] + assert cockpit.remove_card("twin_stage") is False + assert cockpit.layout_state.visible_cards == ["twin_stage"] + + # 3. Restore cards and customize order + layout mode + span + assert cockpit.restore_card("queue") is True + assert cockpit.restore_card("fasting") is True + assert cockpit.restore_card("journey") is True + assert cockpit.reorder_card("queue", "fasting") is True + assert cockpit.set_layout_mode("bento_flow") is True + assert cockpit.set_card_span("queue", 6) is True + assert store_file.exists() + + # 4. Reload a brand-new Cockpit from disk and verify exact state restoration + reloaded = ReceptionDigitalTwinCockpit( + layout_storage_path=store_file, + persist_layout=True, + ) + try: + assert reloaded.layout_state.layout_mode == "bento_flow" + assert reloaded.layout_state.span_for("queue") == 6 + assert reloaded.layout_state.visible_cards[0] == "queue" + assert set(reloaded.layout_state.removed_cards) == {"care_team", "diurnal"} + + reloaded.reset_layout_defaults() + assert reloaded.layout_state.layout_mode == "classic" + assert reloaded.layout_state.visible_cards == list(DEFAULT_CARD_ORDER) + assert reloaded.layout_state.removed_cards == [] + finally: + reloaded.close() + reloaded.deleteLater() + finally: + cockpit.close() + cockpit.deleteLater() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + application.processEvents() + + +def test_spatial_shell_cockpit_four_layouts_and_reordering(application: QApplication) -> None: + repo = DemoDoctorRepository() + session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) + shell = SpatialShellWindow( + repo, + {"session": session, "demo_mode": True}, + session.permissions, + ) + shell.resize(1536, 864) + shell.show() + _settle(application, 20) + + try: + rec = shell.pages["reception"] + cockpit = rec.cockpit_view + + # Sub-hero layout studio toggle button works cleanly + assert shell.cockpit_layout_button.isVisible() + shell.cockpit_layout_button.click() + _settle(application, 6) + assert cockpit.is_layout_edit_mode is True + assert cockpit.layout_studio_bar.isVisible() + assert all(cockpit._card_tiles[k].edit_bar.isVisible() for k in cockpit.layout_state.visible_cards) + + # Reorder in Classic mode: move 'queue' to slot 0 and 'care_team' to slot 1 -> Queue moves to LEFT! + cockpit.reorder_card("queue", "fasting") + cockpit.reorder_card("care_team", "fasting") + _settle(application, 8) + q_tile = cockpit._card_tiles["queue"] + f_tile = cockpit._card_tiles["fasting"] + q_x = q_tile.mapTo(cockpit.grid_canvas, q_tile.rect().topLeft()).x() + f_x = f_tile.mapTo(cockpit.grid_canvas, f_tile.rect().topLeft()).x() + assert q_x < f_x, f"Expected queue ({q_x}) to sit left of fasting ({f_x}) after reordering!" + + # Move 'journey' to slot 0 -> Journey calendar moves to TOP above columns! + cockpit.reorder_card("journey", "queue") + _settle(application, 8) + j_tile = cockpit._card_tiles["journey"] + t_tile = cockpit._card_tiles["twin_stage"] + j_y = j_tile.mapTo(cockpit.grid_canvas, j_tile.rect().topLeft()).y() + t_y = t_tile.mapTo(cockpit.grid_canvas, t_tile.rect().topLeft()).y() + assert j_y < t_y, f"Expected journey ({j_y}) above twin_stage ({t_y})!" + + # Exercise all 4 layout modes and verify every visible card renders with valid geometry + for mode_key in ("stage_focus", "dual_grid", "bento_flow", "classic"): + assert cockpit.set_layout_mode(mode_key) is True + _settle(application, 6) + snap = shell.grab() + assert not snap.isNull() + for k in cockpit.layout_state.visible_cards: + tile = cockpit._card_tiles[k] + assert tile.isVisible() + assert tile.width() >= 180 + assert tile.height() >= 120 + + # Remove 1 card -> Sub-Hero button displays hidden badge once exiting edit mode + cockpit.remove_card("care_team") + cockpit.set_layout_edit_mode(False) + _settle(application, 4) + assert "已隐1" in shell.cockpit_layout_button.text() + + cockpit.reset_layout_defaults() + _settle(application, 4) + assert shell.cockpit_layout_button.text() == "布局编排" + finally: + for page in shell.pages.values(): + if hasattr(page, "poll_timer"): + page.poll_timer.stop() + shell.chat_notifications.stop() + shell.close() + shell.deleteLater() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + application.processEvents() + + +def test_four_curated_suites_14_card_library_swap_and_custom_save( + application: QApplication, + tmp_path: Path, +) -> None: + assert len(COCKPIT_CARD_SPECS) >= 14 + assert len(COCKPIT_PRESET_SUITES) >= 4 + + # Verify the 4 preset suites have genuinely distinct card combinations + suite_card_sets = [frozenset(s.card_keys) for s in COCKPIT_PRESET_SUITES] + assert len(set(suite_card_sets)) == len(COCKPIT_PRESET_SUITES) + + store_file = tmp_path / "cockpit_suites_v51.json" + repo = DemoDoctorRepository() + session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) + shell = SpatialShellWindow( + repo, + {"session": session, "demo_mode": True}, + session.permissions, + ) + shell.resize(1536, 864) + shell.show() + _settle(application, 20) + + try: + cockpit = shell.pages["reception"].cockpit_view + cockpit._layout_store._path = store_file + cockpit._layout_store._persist = True + + # Sub-Hero 1-click Suite Island is visible with all 4 presets + assert shell.cockpit_suite_island.isVisible() + for spec in COCKPIT_PRESET_SUITES: + shell._subhero_suite_buttons[spec.key].click() + _settle(application, 8) + assert cockpit.layout_state.active_suite == spec.key + assert cockpit.layout_state.visible_cards == list(spec.card_keys) + for ck in spec.card_keys: + tile = cockpit._card_tiles[ck] + assert tile.isVisible() + assert tile.width() >= 180 + + # Free Card Library: add new cards, swap a card in-place, and save as Custom Suite + assert cockpit.apply_suite("tcm_rx") is True + assert cockpit.swap_card("notes_media", "metabolic_panel") is True + assert "metabolic_panel" in cockpit.layout_state.visible_cards + assert "notes_media" not in cockpit.layout_state.visible_cards + + assert cockpit.add_card("ai_brief_card") is True + assert "ai_brief_card" in cockpit.layout_state.visible_cards + + cockpit.save_custom_suite() + _settle(application, 4) + assert cockpit.layout_state.active_suite == "custom" + assert shell._subhero_custom_suite_btn.isVisible() + saved_custom_cards = list(cockpit.layout_state.visible_cards) + + # Switch back to 'metabolic', then restore 'custom' in 1 click! + assert cockpit.apply_suite("metabolic") is True + assert cockpit.layout_state.visible_cards != saved_custom_cards + assert cockpit.apply_suite("custom") is True + assert cockpit.layout_state.visible_cards == saved_custom_cards + + # Verify every single one of the 14 cards can be rendered without error + cockpit.set_layout_mode("bento_flow") + for ck in ALL_CARD_KEYS: + cockpit.add_card(ck) + _settle(application, 8) + assert len(cockpit.layout_state.visible_cards) == len(ALL_CARD_KEYS) + full_snap = shell.grab() + assert not full_snap.isNull() + finally: + for page in shell.pages.values(): + if hasattr(page, "poll_timer"): + page.poll_timer.stop() + shell.chat_notifications.stop() + shell.close() + shell.deleteLater() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + application.processEvents() diff --git a/app/tests/test_diagnosis_drawer_visual.py b/app/tests/test_diagnosis_drawer_visual.py index 8d8693307..b64dc8f0f 100755 --- a/app/tests/test_diagnosis_drawer_visual.py +++ b/app/tests/test_diagnosis_drawer_visual.py @@ -1412,7 +1412,6 @@ def test_drawer_tab_bar_is_horizontal_and_scrollable(application: QApplication) dialog = _open_dialog(application, (1024, 640), mode="edit") tab_bar = dialog.tabs.tabBar() assert tab_bar.shape().name.startswith("RoundedNorth") - assert tab_bar.usesScrollButtons() assert not tab_bar.expanding() assert tab_bar.elideMode() == Qt.TextElideMode.ElideNone assert dialog.tabs.tab_scrollbar.height() == 4 diff --git a/app/tests/test_dialog_detail_layout.py b/app/tests/test_dialog_detail_layout.py index a49ee6a6d..f375b221f 100755 --- a/app/tests/test_dialog_detail_layout.py +++ b/app/tests/test_dialog_detail_layout.py @@ -6,8 +6,9 @@ from types import SimpleNamespace os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") import pytest -from PySide6.QtCore import QPoint -from PySide6.QtGui import QPalette +from PySide6.QtCore import QPoint, Qt +from PySide6.QtGui import QPalette, QWheelEvent +from PySide6.QtTest import QTest from PySide6.QtWidgets import QApplication, QDialog, QLabel, QVBoxLayout, QWidget from doctor_workstation.core import PermissionSet @@ -75,7 +76,8 @@ def test_prescription_form_keeps_date_gender_and_controls_readable( host.close() -def test_diagnosis_overflow_rail_leaves_selected_tab_underline_visible(application: QApplication) -> None: +@pytest.fixture +def diagnosis_tabs(application: QApplication): tabs = DiagnosisTabWidget() tabs.setObjectName("DiagnosisDrawerTabs") tabs.setStyleSheet(DIAGNOSIS_QSS) @@ -85,16 +87,90 @@ def test_diagnosis_overflow_rail_leaves_selected_tab_underline_visible(applicati tabs.show() settle(application) try: - selected = tabs.tabBar().tabRect(tabs.currentIndex()) - selected.moveTopLeft(tabs.tabBar().pos() + selected.topLeft()) - assert tabs.tab_scrollbar.isVisible() - assert not selected.intersects(tabs.tab_scrollbar.geometry()) - tabs.tab_scrollbar.setValue(tabs.count() - 1) - assert tabs.currentIndex() == tabs.count() - 1 + yield tabs finally: tabs.close() +def test_diagnosis_overflow_rail_pans_without_switching_pages(diagnosis_tabs: DiagnosisTabWidget) -> None: + tabs = diagnosis_tabs + bar = tabs.tabBar() + rail = tabs.tab_scrollbar + first = bar.tabRect(0) + first.moveTopLeft(bar.mapTo(tabs, first.topLeft())) + assert rail.isVisible() + assert not first.intersects(rail.rect().translated(rail.mapTo(tabs, QPoint()))) + changes = [] + tabs.currentChanged.connect(changes.append) + + # Grab the leading edge of the thumb at its initial, leftmost position. + start = QPoint(10, rail.height() // 2) + QTest.mousePress(rail, Qt.MouseButton.LeftButton, pos=start) + QTest.mouseMove(rail, start + QPoint(24, 0)) + assert 0 < rail.value() < rail.maximum() + assert bar.mapTo(tabs, bar.tabRect(0).topLeft()).x() == first.left() - rail.value() + QTest.mouseRelease(rail, Qt.MouseButton.LeftButton, pos=start + QPoint(24, 0)) + + rail.setValue(rail.maximum()) + last = tabs.count() - 1 + assert bar.visibleRegion().boundingRect().contains(bar.tabRect(last)) + assert changes == [] + QTest.mouseClick(bar, Qt.MouseButton.LeftButton, pos=bar.tabRect(last).center()) + assert changes == [last] + rail.setValue(0) + QTest.keyClick(bar, Qt.Key.Key_Left) + assert changes == [last, last - 1] + assert bar.visibleRegion().boundingRect().contains(bar.tabRect(last - 1)) + + +@pytest.mark.parametrize( + ("pixels", "angle"), + [(QPoint(-7, 0), QPoint()), (QPoint(), QPoint(0, -120))], + ids=["horizontal-touchpad", "vertical-mouse-wheel"], +) +def test_diagnosis_wheel_pans_the_tab_strip( + diagnosis_tabs: DiagnosisTabWidget, pixels: QPoint, angle: QPoint, +) -> None: + tabs = diagnosis_tabs + bar = tabs.tabBar() + rail = tabs.tab_scrollbar + pos = bar.tabRect(0).center() + wheel = QWheelEvent( + pos, bar.mapToGlobal(pos), pixels, angle, Qt.MouseButton.NoButton, + Qt.KeyboardModifier.NoModifier, Qt.ScrollPhase.NoScrollPhase, False, + ) + changes = [] + tabs.currentChanged.connect(changes.append) + QApplication.sendEvent(bar, wheel) + if pixels.isNull(): + QTest.qWait(100) + assert rail.value() > 0 + else: + assert rail.value() == -pixels.x() + assert changes == [] + + +def test_rebuilding_allowed_tabs_reveals_selection_with_signals_blocked( + diagnosis_tabs: DiagnosisTabWidget, application: QApplication, +) -> None: + tabs = diagnosis_tabs + titles = [tabs.tabText(index) for index in range(tabs.count())] + changes = [] + tabs.currentChanged.connect(changes.append) + tabs.blockSignals(True) + try: + tabs.clear() + for title in titles: + tabs.addTab(QWidget(), title) + tabs.setCurrentIndex(tabs.count() - 1) + finally: + tabs.blockSignals(False) + settle(application) + bar = tabs.tabBar() + assert bar.visibleRegion().boundingRect().contains(bar.tabRect(tabs.currentIndex())) + assert changes == [] + + def test_appointment_slot_labels_follow_checked_and_disabled_states(application: QApplication) -> None: dialog = QDialog() dialog.setObjectName("AppointmentDrawerOverlay") diff --git a/app/tests/test_issued_prescription_ai.py b/app/tests/test_issued_prescription_ai.py index c61f87a97..95fe752e0 100755 --- a/app/tests/test_issued_prescription_ai.py +++ b/app/tests/test_issued_prescription_ai.py @@ -5,6 +5,7 @@ from __future__ import annotations import os import socket from copy import deepcopy +from datetime import datetime from typing import Any from uuid import UUID @@ -12,6 +13,8 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") import pytest from PySide6.QtCore import QEvent, QObject, QRect, Qt +from PySide6.QtGui import QAction +from PySide6.QtTest import QTest from PySide6.QtWidgets import QApplication, QPushButton, QWidget from doctor_workstation.services import DemoDoctorRepository @@ -118,6 +121,16 @@ def test_percentage_never_turns_missing_into_zero(value: Any, expected: str) -> assert ai.percentage(value) == expected +@pytest.mark.parametrize(("models", "expected"), [ + ({"qwen": {"score": None}, "openai": {}}, ""), + ({"qwen": {"score": False}, "openai": {"score": 101}}, ""), + ({"qwen": {"score": 84, "comparison_status": "not_comparable"}, "openai": {"score": 0}}, "OpenAI 0%"), + ({"qwen": {"score": 0}, "openai": {"score": 84}}, "千问 0%\nOpenAI 84%"), +]) +def test_list_agreement_only_formats_available_model_scores(models: dict, expected: str) -> None: + assert ai.agreement_text({"validity": "current", "models": models}) == expected + + def test_shared_report_reads_only_and_renders_each_model_independently(application: QApplication, immediate: None) -> None: repository = Repository() dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) @@ -310,9 +323,106 @@ def test_exhausted_manual_retries_point_at_regeneration_instead_of_retry(applica text = dialog.model_views["openai"]["failure_text"].text() assert "手动重试次数已用完" in text and "重新分析" in text assert not dialog.model_views["openai"]["retry"].isVisible() + dialog._retry("openai") + assert not any(call[0] == "retry" for call in repository.calls) dialog.close() +def test_revoked_snapshot_requires_new_analysis(application: QApplication, immediate: None) -> None: + repository = Repository() + value = repository.batches[0] + value.update(status="partial") + value["models"]["openai"].update(status="failed", error_code="ACCESS_REVOKED") + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + views = dialog.model_views["openai"] + assert "核对资料访问权限" in views["failure_text"].text() and "重新分析" in views["failure_text"].text() + assert views["retry"].isHidden() and not views["retry"].isEnabled() + assert dialog.regenerate_button.isEnabled() + dialog._retry("openai") + assert not any(call[0] == "retry" for call in repository.calls) + dialog.close() + + +def test_retry_acknowledgment_and_polls_show_when_the_model_can_run( + application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, +) -> None: + repository = Repository() + value = repository.batches[0] + value.update(status="partial") + model = value["models"]["openai"] + model.update(status="failed", error_code="UPSTREAM_TIMEOUT", manual_retries=2, max_manual_retries=3) + deadline = int(datetime(2026, 12, 3).timestamp()) + wait = {"status": "retry_wait", "error_code": "BUDGET_PAUSED", "last_error_code": "UPSTREAM_TIMEOUT", + "manual_retries": 3, "max_manual_retries": 3, + "progress": {"stage": "retry_wait", "next_run_at": deadline, "server_time": deadline - 15, + "wait_remaining_seconds": 15}} + + def submit(batch_id: int, model_key: str) -> dict[str, Any]: + repository.calls.append(("retry", (batch_id, model_key))) + value.update(status="running") + model.update(wait) + return {"batch_id": batch_id, "model_key": model_key, **wait} + + monkeypatch.setattr(repository, "retry_prescription_ai", submit) + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.resize(1024, 700) + dialog.show() + views = dialog.model_views["openai"] + assert views["retry"].isEnabled() + pending = [] + with monkeypatch.context() as patch: + patch.setattr(ai, "run_async", lambda operation, **callbacks: pending.append((operation, callbacks))) + dialog._retry("openai") + dialog._retry("openai") + assert len(pending) == 1 and not views["retry"].isEnabled() + operation, callbacks = pending.pop() + callbacks["on_success"](operation()) + assert "等待重试" in dialog.message.text() and "预算" in dialog.message.text() + callbacks["on_finished"]() + dialog._retry("openai") + assert len(pending) == 1 and not views["retry"].isEnabled() + read_history, callbacks = pending.pop() + callbacks["on_success"](read_history()) + read_detail, callbacks = pending.pop() + callbacks["on_success"](read_detail()) + callbacks["on_finished"]() + application.processEvents() + stage = views["stage"] + assert stage.isVisible() and "额度恢复" in stage.text() and "上次失败:模型响应超时" in stage.text() + assert "2026-12-03 00:00:00" in stage.text() and "距下次重试 15 秒" in stage.text() + badge = views["status_chip"] + assert stage.parentWidget().layout().indexOf(stage) >= 0 + assert stage.geometry().top() > badge.geometry().bottom() + assert views["progress_bar"].isHidden() and views["retry"].isHidden() and dialog._timer.isActive() + assert repository.calls.count(("retry", (40, "openai"))) == 1 + + model["progress"].update(stage="completed", notice="结果已保存,可查看报告。", + server_time=deadline + 30, wait_remaining_seconds=0) + dialog._poll() + assert "等待后台领取" in stage.text() and "2026-12-03 00:00:00" in stage.text() + assert "已完成" not in views["progress_title"].text() and "已保存" not in views["progress_detail"].text() + assert dialog._timer.isActive() and not views["retry"].isEnabled() + model.update(status="running", progress={"stage": "final", "phase": "running"}) + dialog._poll() + assert stage.text() == "生成完整报告" + value.update(status="success") + model.update(status="success", progress={"stage": "completed", "phase": "completed"}) + dialog._poll() + assert badge.text() == "已完成" and stage.isHidden() and not dialog._timer.isActive() + dialog.close() + + +def test_legacy_retry_wait_does_not_invent_an_overdue_timestamp() -> None: + progress = {"stage": "retry_wait", "server_time": int(datetime(2026, 12, 2, 23, 59, 45).timestamp()), + "wait_remaining_seconds": 15} + model = {"status": "retry_wait", "progress": progress} + assert "2026-12-03 00:00:00" in ai.progress_view(model).retry_summary + progress["wait_remaining_seconds"] = 0 + text = ai.progress_view(model).retry_summary + assert "等待后台领取" in text and "最早可执行时间" not in text + + def test_inline_review_keeps_model_drafts_and_saves_selected_model(application: QApplication, immediate: None) -> None: repository = Repository() repository.batches[0]["models"]["openai"].update(report_id=92, report={"summary": "已保存报告"}) @@ -441,8 +551,35 @@ def test_view_permission_cannot_mutate(application: QApplication, immediate: Non dialog.close() -def test_list_batches_visible_ids_and_stops_on_hide(application: QApplication, immediate: None) -> None: +def assert_empty_ai_columns(page: page_module.PrescriptionsPage, columns: tuple[int, ...] = (11, 12)) -> None: + assert page.table.rowCount() > 0 + for column in columns: + assert not page.table.isColumnHidden(column) + for index in range(page.table.rowCount()): + item = page.table.item(index, column) + assert item.text() == item.toolTip() == "" + assert not item.data(Qt.ItemDataRole.AccessibleTextRole) + + +def click_ai_cell(page: page_module.PrescriptionsPage, column: int, row: int = 0) -> None: + item = page.table.item(row, column) + page.table.scrollToItem(item) + QTest.mouseClick(page.table.viewport(), Qt.MouseButton.LeftButton, pos=page.table.visualItemRect(item).center()) + + +def ai_context_action(page: page_module.PrescriptionsPage, row: int = 0) -> QAction: + item = page.table.item(row, page.table.horizontalHeader().logicalIndex(1)) + page.table.scrollToItem(item) + page.table.customContextMenuRequested.emit(page.table.visualItemRect(item).center()) + action, = (a for a in page._ai_context_menu.actions() if a.text() == "AI 分析") + assert action.isVisible() + return action + + +def test_list_batches_visible_ids_and_stops_on_hide(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: repository = Repository() + opened = [] + monkeypatch.setattr(page_module, "present_issued_prescription_ai", lambda *_args, **kwargs: opened.append(kwargs)) page = page_module.PrescriptionsPage(repository, ["*"]) page.resize(1366, 800) page.show() @@ -452,8 +589,15 @@ def test_list_batches_visible_ids_and_stops_on_hide(application: QApplication, i assert len(statuses[-1][1]) <= 100 assert not page.table.isColumnHidden(11) assert not page.table.isColumnHidden(12) - assert "千问 0%" in page.table.item(0, 12).text() - assert "OpenAI —" in page.table.item(0, 12).text() + header = page.table.horizontalHeader() + assert [page.table.horizontalHeaderItem(header.logicalIndex(i)).text() for i in range(header.count())] == [ + "", "患者信息", "处方编号", "处方类型", "来源", "审核状态", "作废", "医生信息", + "医助", "创建时间", "AI 分析", "与 AI 一致度", "操作", + ] + assert page.table.item(0, 12).text() == "千问 0%" + page.table.selectRow(1) + click_ai_cell(page, 12) + assert opened == [{"prescription_id": 801}] assert any(button.accessibleName() == "AI 报告" for button in page.table.findChildren(QPushButton)) assert page._ai_timer.isActive() page.hide() @@ -463,7 +607,7 @@ def test_list_batches_visible_ids_and_stops_on_hide(application: QApplication, i assert repository.calls == calls -def test_blank_list_row_has_no_ai_display_or_entry_points(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: +def test_blank_list_row_has_empty_ai_cells_and_disabled_context_action(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: repository = Repository() opened = [] monkeypatch.setattr(page_module, "present_issued_prescription_ai", lambda *args, **kwargs: opened.append(kwargs)) @@ -483,10 +627,10 @@ def test_blank_list_row_has_no_ai_display_or_entry_points(application: QApplicat page.table.selectRow(1) assert page.ai_report_button.isHidden() and not page.ai_report_button.isEnabled() page._open_ai_report() - page.table.itemClicked.emit(page.table.item(1, 11)) - page.table.itemClicked.emit(page.table.item(1, 12)) - page._open_ai_context_menu(page.table.visualItemRect(page.table.item(1, 1)).center()) - assert not hasattr(page, "_ai_context_menu") + click_ai_cell(page, 11, 1) + click_ai_cell(page, 12, 1) + assert not ai_context_action(page, 1).isEnabled() + page._ai_context_menu.close() assert opened == [] page.table.selectRow(0) assert page.ai_report_button.isVisible() and page.ai_report_button.isEnabled() @@ -495,13 +639,81 @@ def test_blank_list_row_has_no_ai_display_or_entry_points(application: QApplicat page.close() +@pytest.mark.parametrize(("status", "expected"), [ + (None, ""), ("not_generated", ""), ("failed", "需重试"), ("retry_wait", "等待重试"), +]) +def test_prescription_without_scores_uses_reported_status_and_keeps_context_entry( + application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, status: str | None, expected: str, +) -> None: + repository = Repository() + opened = [] + monkeypatch.setattr(page_module, "present_issued_prescription_ai", lambda *_args, **kwargs: opened.append(kwargs)) + + def statuses(ids: list[int]) -> dict[str, Any]: + items = [{"prescription_id": value, "agreement_visible": True, "status": status, + "batch_id": None if status == "not_generated" else 40, "models": {}} for value in ids if status] + return {"enabled": True, "agreement_visible": True, "items": items} + + monkeypatch.setattr(repository, "list_prescription_ai_statuses", statuses) + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + application.processEvents() + assert_empty_ai_columns(page, (12,) if expected else (11, 12)) + assert page.table.item(0, 11).text() == expected + click_ai_cell(page, 12) + assert opened == [] + click_ai_cell(page, 11) + assert opened == ([{"prescription_id": 801}] if expected else []) + action = ai_context_action(page) + assert action.isEnabled() + opened.clear() + action.trigger() + assert opened == [{"prescription_id": 801}] + page._ai_context_menu.close() + page.close() + + +@pytest.mark.parametrize("row_visible", [True, False], ids=["no-scores", "row-denied"]) +def test_nonblank_prescription_without_visible_scores_keeps_empty_agreement_cell( + application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, row_visible: bool, +) -> None: + repository = Repository() + original = repository.list_prescription_ai_statuses + opened = [] + monkeypatch.setattr(page_module, "present_issued_prescription_ai", lambda *_args, **kwargs: opened.append(kwargs)) + + def statuses(ids: list[int]) -> dict[str, Any]: + response = original(ids) + for row in response["items"]: + row["agreement_visible"] = row_visible + if row_visible: + row["models"]["qwen"]["score"] = None + return response + + monkeypatch.setattr(repository, "list_prescription_ai_statuses", statuses) + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + application.processEvents() + assert ("statuses", [801]) in repository.calls + assert not page.table.isColumnHidden(11) + assert_empty_ai_columns(page, (12,)) + click_ai_cell(page, 12) + assert opened == [] + assert page.table.item(0, 11).text() == "已完成 1/2" + click_ai_cell(page, 11) + assert opened == [{"prescription_id": 801}] + page.close() + + @pytest.mark.parametrize("blank_fields", [ {"is_system_auto": "1", "herbs": []}, {"is_system_auto": True, "herbs": [{"name": "黄芪"}]}, {"is_system_auto": 0, "herbs": [{}, {"name": " "}]}, {"is_system_auto": 0, "herbs": None}, ]) -def test_all_blank_list_hides_ai_until_prescription_is_saved(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, blank_fields: dict[str, Any]) -> None: +def test_all_blank_list_keeps_ai_cells_empty_until_prescription_is_saved(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, blank_fields: dict[str, Any]) -> None: repository = Repository() row = {"id": 803, "sn": "RX-BLANK", "patient_name": "测试患者", **blank_fields} monkeypatch.setattr(repository, "list_prescriptions", lambda **_filters: {"lists": [row], "count": 1}) @@ -509,7 +721,7 @@ def test_all_blank_list_hides_ai_until_prescription_is_saved(application: QAppli page.resize(1366, 800) page.show() application.processEvents() - assert page.table.isColumnHidden(11) and page.table.isColumnHidden(12) + assert_empty_ai_columns(page) assert page.ai_report_button.isHidden() and page.ai_status_notice.isHidden() assert not page._ai_timer.isActive() assert not any(call[0] == "statuses" for call in repository.calls) @@ -528,14 +740,18 @@ def test_all_blank_list_hides_ai_until_prescription_is_saved(application: QAppli def test_list_disabled_explains_availability_and_keeps_history(application: QApplication, immediate: None) -> None: repository = Repository() - repository.enabled = False page = page_module.PrescriptionsPage(repository, ["*"]) page.resize(1366, 800) page.show() application.processEvents() - assert page.table.isColumnHidden(11) and page.table.isColumnHidden(12) + assert page.table.item(0, 12).text() == "千问 0%" + repository.enabled = False + page._load_ai_statuses() + assert_empty_ai_columns(page) assert not page._ai_timer.isActive() assert page.ai_report_button.isVisible() + assert ai_context_action(page).isEnabled() + page._ai_context_menu.close() assert page.ai_status_notice.isVisible() assert "未启用" in page.ai_status_notice.text() page.close() @@ -554,7 +770,7 @@ def test_list_service_error_is_visible_and_clears_after_recovery(application: QA application.processEvents() assert page.ai_status_notice.isVisible() assert "暂不可用" in page.ai_status_notice.text() - assert page.table.isColumnHidden(12) + assert_empty_ai_columns(page) assert not page._ai_timer.isActive() monkeypatch.setattr(repository, "list_prescription_ai_statuses", Repository.list_prescription_ai_statuses.__get__(repository)) page.refresh() @@ -562,18 +778,26 @@ def test_list_service_error_is_visible_and_clears_after_recovery(application: QA assert "已启用" in page.ai_status_notice.text() assert not page.ai_status_notice.toolTip() assert not page.table.isColumnHidden(12) + assert page.table.item(0, 12).text() == "千问 0%" page.close() -def test_list_missing_permission_explains_without_loading_ai(application: QApplication, immediate: None) -> None: +def test_list_missing_permission_explains_without_loading_ai(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: repository = Repository() + opened = [] + monkeypatch.setattr(page_module, "present_issued_prescription_ai", lambda *_args, **kwargs: opened.append(kwargs)) page = page_module.PrescriptionsPage(repository, ["cf.prescription/read"]) page.resize(1366, 800) page.show() application.processEvents() assert page.ai_status_notice.isVisible() assert "权限" in page.ai_status_notice.text() - assert page.table.isColumnHidden(11) and page.table.isColumnHidden(12) + assert_empty_ai_columns(page) + click_ai_cell(page, 11) + click_ai_cell(page, 12) + assert not ai_context_action(page).isEnabled() + page._ai_context_menu.close() + assert opened == [] assert not page.ai_report_button.isVisible() assert not any(call[0] in {"statuses", "reports", "detail"} for call in repository.calls) page.close() @@ -795,7 +1019,7 @@ def test_revoked_agreement_cache_discards_flat_comparison_metadata() -> None: @pytest.mark.parametrize("flag", [False, None, 1, "true"]) -def test_unlisted_account_hides_ai_analysis_column_and_keeps_reports( +def test_unlisted_account_sees_empty_ai_cells_and_keeps_reports( application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, flag: Any, ) -> None: repository = Repository() @@ -808,10 +1032,13 @@ def test_unlisted_account_hides_ai_analysis_column_and_keeps_reports( page.show() application.processEvents() page.table.selectRow(0) - assert page.table.isColumnHidden(11) and page.table.isColumnHidden(12) - # Later status refreshes must not re-expose the analysis column. - page._set_ai_columns(True) - assert page.table.isColumnHidden(11) and page.table.isColumnHidden(12) + assert_empty_ai_columns(page) + # Enabling the service again cannot reveal restricted values. + page._set_ai_enabled(True) + assert_empty_ai_columns(page) + click_ai_cell(page, 11) + click_ai_cell(page, 12) + assert opened == [] assert page.ai_report_button.isVisible() and page.ai_report_button.isEnabled() assert any(button.accessibleName() == "AI 报告" for button in page.table.cellWidget(0, 2).findChildren(QPushButton)) @@ -821,30 +1048,35 @@ def test_unlisted_account_hides_ai_analysis_column_and_keeps_reports( page.close() +@pytest.mark.parametrize("failed_read", [False, True], ids=["revoked", "unavailable"]) def test_list_capability_failure_revocation_and_late_status_cannot_restore_scores( - application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, + application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, failed_read: bool, ) -> None: repository = Repository() page = page_module.PrescriptionsPage(repository, ["*"], {"root": 1}) page.resize(1366, 800) page.show() application.processEvents() - assert not page.table.isColumnHidden(12) + assert page.table.item(0, 12).text() == "千问 0%" old_statuses = repository.list_prescription_ai_statuses([801, 802]) old_token = page._ai_request_token old_capability_token = page._ai_capability_token - monkeypatch.setattr(repository, "get_prescription_ai_capabilities", lambda: (_ for _ in ()).throw(RuntimeError("offline"))) - page._load_ai_capabilities() + with monkeypatch.context() as patch: + if failed_read: + patch.setattr(repository, "get_prescription_ai_capabilities", lambda: (_ for _ in ()).throw(RuntimeError("offline"))) + else: + patch.setattr(repository, "agreement_visible", False) + page._load_ai_capabilities() page._ai_statuses_ready(old_statuses, [801, 802], old_token, page._generation) page._ai_capabilities_ready({"agreement_visible": True}, old_capability_token, page._generation) - assert page.table.isColumnHidden(12) and page.table.isColumnHidden(11) + assert_empty_ai_columns(page) assert page.ai_statistics_button.isHidden() assert page.ai_report_button.isVisible() assert page._ai_statuses - for index in range(page.table.rowCount()): - item = page.table.item(index, 12) - assert not item.text() and not item.toolTip() and not item.data(Qt.ItemDataRole.AccessibleTextRole) assert all("score" not in model for row in page._ai_statuses.values() for model in row.get("models", {}).values()) + page._load_ai_capabilities() + assert not page.table.isColumnHidden(11) + assert page.table.item(0, 12).text() == "千问 0%" page.close() @@ -909,7 +1141,7 @@ def test_statistics_failed_capability_clears_old_charts_and_ignores_late_result( def test_stale_list_score_is_not_attached_to_current_prescription() -> None: value = {"validity": "superseded", "models": {"qwen": {"score": 100}, "openai": {"score": 90}}} - assert ai.agreement_text(value) == "千问 —\nOpenAI —" + assert ai.agreement_text(value) == "" assert ai.state_text(value) == "处方已变更" assert not ai.batch_running({**value, "status": "running"}) @@ -967,10 +1199,10 @@ def test_context_menu_targets_clicked_prescription(application: QApplication, im page.show() application.processEvents() page.table.selectRow(1) - item = page.table.item(0, 1) expected_id = page.table.item(0, 0).data(Qt.ItemDataRole.UserRole).id - page._open_ai_context_menu(page.table.visualItemRect(item).center()) - page._ai_context_menu.actions()[0].trigger() + action = ai_context_action(page) + assert action.isEnabled() + action.trigger() assert opened == [{"prescription_id": expected_id}] page._ai_context_menu.close() page.close() @@ -1037,7 +1269,7 @@ def test_actual_history_pagination_contract(application: QApplication, immediate def test_server_empty_batch_statuses_are_not_fake_scores(status: str, expected: str) -> None: data = {"status": status, "models": {}, "coverage_status": "pending"} assert ai.state_text(data) == expected - assert ai.agreement_text(data) == "千问 —\nOpenAI —" + assert ai.agreement_text(data) == "" def test_statistics_displays_actual_version_strata_without_filling_null_mean(application: QApplication, immediate: None) -> None: @@ -1488,7 +1720,7 @@ def test_progress_notice_and_source_references_remain_plain_and_escaped(applicat def test_list_shows_compact_two_model_progress_with_full_detail_in_tooltip(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: repository = Repository() - monkeypatch.setattr(repository, "list_prescription_ai_statuses", lambda ids: {"enabled": True, "items": [dict(progress_batch(), prescription_id=value) for value in ids]}) + monkeypatch.setattr(repository, "list_prescription_ai_statuses", lambda ids: {"enabled": True, "agreement_visible": True, "items": [dict(progress_batch(), prescription_id=value) for value in ids]}) page = page_module.PrescriptionsPage(repository, ["*"]) page.resize(1366, 800) page.show() diff --git a/app/tests/test_prescription_esign.py b/app/tests/test_prescription_esign.py index a8d703635..785e59b85 100644 --- a/app/tests/test_prescription_esign.py +++ b/app/tests/test_prescription_esign.py @@ -16,9 +16,9 @@ import pytest from PySide6.QtCore import QBuffer, QIODevice, Qt, Signal from PySide6.QtGui import QColor, QDesktopServices, QImage from PySide6.QtTest import QTest -from PySide6.QtWidgets import QApplication, QDialog, QFileDialog, QLineEdit, QWidget +from PySide6.QtWidgets import QApplication, QDialog, QFileDialog, QLineEdit, QStackedLayout, QWidget -from doctor_workstation.core.errors import ApiBusinessError, ApiProtocolError +from doctor_workstation.core.errors import ApiBusinessError, ApiProtocolError, ApiTimeoutError from doctor_workstation.core.esign import ( authentication_url, esign_identity_status, @@ -285,6 +285,72 @@ def test_doctor_enrollment_and_prescription_sms_have_separate_wire_contracts() - ] +@pytest.mark.parametrize("resume", ["first_open", "before_reply", "after_reply", "closed"]) +def test_doctor_status_in_prewarmed_panel( + application: QApplication, monkeypatch: pytest.MonkeyPatch, resume: str, +) -> None: + pending = [] + monkeypatch.setattr(doctor_module, "run_async", lambda work, **callbacks: pending.append(callbacks)) + # The wing already contains a prewarmed page when it embeds the signing dialog. + host = QWidget() + stack = QStackedLayout(host) + stack.addWidget(QWidget()) + host.show() + dialog = doctor_module.EsignDoctorDialog(SimpleNamespace(), parent=host) + dialog.setWindowFlags(Qt.WindowType.Widget) + stack.addWidget(dialog) + try: + assert not pending + stack.setCurrentWidget(dialog) + assert len(pending) == 1 + first = pending.pop() + if resume == "first_open": + first["on_success"]({"enabled": True, "status": "ready"}) + first["on_finished"]() + assert "已就绪" in dialog.banner.label.text() and not pending + return + if resume == "closed": + dialog.reject() + else: + stack.setCurrentIndex(0) + if resume == "before_reply": + stack.setCurrentWidget(dialog) + assert not pending + first["on_success"]({"enabled": True, "status": "ready"}) + first["on_finished"]() + assert not dialog.state + if resume == "closed": + assert not pending + return + if resume == "after_reply": + assert not pending + stack.setCurrentWidget(dialog) + assert len(pending) == 1 + second = pending.pop() + second["on_success"]({"enabled": True, "status": "unbound"}) + second["on_finished"]() + assert dialog.mobile_form.isVisible() and dialog.start_button.isEnabled() + assert "正在查询" not in dialog.banner.label.text() and not pending + finally: + host.close() + + +def test_doctor_status_timeout_can_be_retried(immediate: None) -> None: + def timed_out(): + raise ApiTimeoutError("timeout") + + repository = SimpleNamespace(get_esign_doctor_status=timed_out) + dialog = doctor_module.EsignDoctorDialog(repository) + try: + dialog.show() + assert "超时" in dialog.banner.label.text() and dialog.refresh_button.isEnabled() + repository.get_esign_doctor_status = lambda: {"enabled": True, "status": "ready"} + dialog.refresh_button.click() + assert dialog.state["status"] == "ready" and "已就绪" in dialog.banner.label.text() + finally: + dialog.close() + + @pytest.mark.parametrize("details_required", [False, True]) def test_doctor_enrollment_binds_explicitly_after_provider_confirmation( immediate: None, details_required: bool, diff --git a/app/tests/test_prescription_patient_ai_sheet.py b/app/tests/test_prescription_patient_ai_sheet.py new file mode 100644 index 000000000..1be433d5c --- /dev/null +++ b/app/tests/test_prescription_patient_ai_sheet.py @@ -0,0 +1,310 @@ +"""Cross-page routing of the AI sheet in the real spatial shell, with offline data.""" + +from __future__ import annotations + +import os +from collections.abc import Callable, Iterator +from threading import Event + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +import pytest +from PySide6.QtCore import QDeadlineTimer, QEvent, Qt, QThreadPool +from PySide6.QtTest import QTest +from PySide6.QtWidgets import QApplication, QLabel + +from doctor_workstation.core.models import Prescription +from doctor_workstation.services.demo_repository import DemoDoctorRepository +from doctor_workstation.ui.dialogs.ai_consult import AiConsultDialog +from doctor_workstation.ui.shell_spatial import SpatialShellWindow +from doctor_workstation.ui.visuals.ai_report_wing import ClinicalAiReportWingPanel + + +class SheetRepository(DemoDoctorRepository): + def __init__(self) -> None: + super().__init__() + self.blocked_reads: dict[int, tuple[Event, Event]] = {} + self.report_reads: list[int] = [] + self._prescriptions = [ + Prescription.from_dict( + { + "id": 851, + "patient_name": "陈一诺", + "patient_id": 304, + "diagnosis_id": 504, + } + ), + Prescription.from_dict( + { + "id": 852, + "patient_name": "赵明远", + "patient_id": 302, + "diagnosis_id": 502, + } + ), + # Historical rows may only supply the diagnosis as their link. + Prescription.from_dict({"id": 853, "patient_name": "吴诗雨", "diagnosis_id": 503}), + Prescription.from_dict({"id": 854, "patient_name": "无关联患者"}), + ] + + def list_patient_ai_reports(self, patient_id: int) -> dict: + self.report_reads.append(patient_id) + suffix = "" + if patient_id in self.blocked_reads: + started, release = self.blocked_reads[patient_id] + started.set() + assert release.wait(15), f"Timed out releasing report for {patient_id}" + suffix = "(刷新后)" + return { + "patient_id": patient_id, + "reports": [ + { + "id": patient_id * 10 + index, + "patient_id": patient_id, + "diagnosis_id": patient_id + 200, + "version": 1, + "model_key": model, + "generated_at": "2026-08-12 09:18:00", + "report": { + "diagnosis": f"病历摘要 {patient_id}-{model}{suffix}", + "treatment_advice": f"随访记录 {patient_id}-{model}", + }, + } + for index, model in enumerate(("qwen", "openai", "doubao"), start=1) + ], + } + + +def _wait_for(check: Callable[[], bool], message: str) -> None: + deadline = QDeadlineTimer(4000) + while not check() and not deadline.hasExpired(): + QTest.qWait(10) + assert check(), message + + +def _header(shell: SpatialShellWindow) -> str: + sheet = shell.ai_bottom_sheet + return " ".join(label.text() for label in sheet.findChildren(QLabel) if label.isVisible()) + + +def _body(shell: SpatialShellWindow) -> str: + return " ".join(card.toolTip() for card in shell.ai_bottom_sheet.aurora_cards) + + +@pytest.fixture(scope="module") +def application() -> QApplication: + return QApplication.instance() or QApplication([]) + + +@pytest.fixture +def workstation(application: QApplication) -> Iterator[tuple[SpatialShellWindow, SheetRepository]]: + repository = SheetRepository() + session = repository.login(repository.DEMO_ACCOUNT, repository.DEMO_PASSWORD) + shell = SpatialShellWindow( + repository, {"session": session, "demo_mode": True}, session.permissions + ) + shell.resize(1536, 900) + try: + shell.show() + assert shell.navigate("reception") + _wait_for(lambda: "301-qwen" in _body(shell), "Reception did not load its own report") + yield shell, repository + finally: + for _, release in repository.blocked_reads.values(): + release.set() + for page in shell.pages.values(): + if hasattr(page, "poll_timer"): + page.poll_timer.stop() + shell.close() + QThreadPool.globalInstance().waitForDone(4000) + application.processEvents() + shell.deleteLater() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + application.processEvents() + + +def _open_prescriptions(shell: SpatialShellWindow) -> None: + shell.nav_buttons["prescriptions"].click() + table = shell.pages["prescriptions"].table + _wait_for(lambda: table.rowCount() == 4 and table.isVisible(), "Missing prescription rows") + + +def _click_patient(shell: SpatialShellWindow, name: str) -> None: + table = shell.pages["prescriptions"].table + column = next( + i for i in range(table.columnCount()) if table.horizontalHeaderItem(i).text() == "患者信息" + ) + item = next( + table.item(i, column) + for i in range(table.rowCount()) + if name in table.item(i, column).text() + ) + table.scrollToItem(item) + QTest.mouseClick( + table.viewport(), Qt.MouseButton.LeftButton, pos=table.visualItemRect(item).center() + ) + + +def test_selected_prescription_drives_sheet_report_and_conversation( + workstation, monkeypatch +) -> None: + shell, _ = workstation + _open_prescriptions(shell) + _click_patient(shell, "赵明远") + _wait_for( + lambda: "302-qwen" in _body(shell), "Selected prescription did not load its patient report" + ) + assert "赵明远" in _header(shell) + assert "林晓岚" not in _header(shell) + + sheet = shell.ai_bottom_sheet + for key in ("openai", "doubao"): + sheet._model_buttons[key].click() + _wait_for( + lambda key=key: f"302-{key}" in _body(shell), "Model switch lost the selected patient" + ) + assert "赵明远" in _header(shell) + + sheet.report_button.click() + panel = shell.wing_manager.active_widget + assert isinstance(panel, ClinicalAiReportWingPanel) + wing_text = " ".join( + label.text() for label in shell.wing_manager.card.findChildren(QLabel) if label.isVisible() + ) + assert "赵明远" in wing_text + assert "302-doubao" in wing_text + shell.wing_manager.close_wing() + + opened = [] + monkeypatch.setattr( + AiConsultDialog, "exec", lambda self: opened.append((self.diagnosis_id, self.patient_id)) + ) + sheet.consult_button.click() + assert opened == [(502, 302)] + + +def test_late_reception_and_previous_row_reads_cannot_replace_selected_report(workstation) -> None: + shell, repository = workstation + for patient_id in (301, 302): + repository.blocked_reads[patient_id] = Event(), Event() + reception = shell.pages["reception"] + reception_updates = [] + reception.cockpit_snapshot_updated.connect( + lambda snapshot: reception_updates.append(snapshot.aurora.cards[0].body_text) + ) + reception.refresh_button.click() + _wait_for(repository.blocked_reads[301][0].is_set, "Reception refresh did not start") + + _open_prescriptions(shell) + _click_patient(shell, "赵明远") + _wait_for(repository.blocked_reads[302][0].is_set, "First prescription read did not start") + _click_patient(shell, "吴诗雨") + _wait_for( + lambda: "303-qwen" in _body(shell), + "Diagnosis-only prescription did not resolve its patient", + ) + + repository.blocked_reads[301][1].set() + _wait_for( + lambda: any("301-qwen(刷新后)" in text for text in reception_updates), + "Hidden reception did not finish its pending refresh", + ) + assert "303-qwen" in _body(shell) + + repository.blocked_reads[302][1].set() + assert QThreadPool.globalInstance().waitForDone(4000) + QApplication.processEvents() + assert "吴诗雨" in _header(shell) + assert "303-qwen" in _body(shell) + assert "302-qwen" not in _body(shell) + assert "301-qwen" not in _body(shell) + + shell.nav_buttons["reception"].click() + _wait_for( + lambda: "301-qwen" in _body(shell), "Returning to reception did not restore its report" + ) + + +def test_unlinked_and_filtered_out_prescriptions_clear_previous_context(workstation) -> None: + shell, repository = workstation + _open_prescriptions(shell) + _click_patient(shell, "赵明远") + _wait_for(lambda: "302-qwen" in _body(shell), "Baseline report did not load") + previous_reads = list(repository.report_reads) + + _click_patient(shell, "无关联患者") + _wait_for( + lambda: "无关联患者" in _header(shell), + "Unlinked prescription retained another patient's name", + ) + assert "302-qwen" not in _body(shell) + assert not shell.ai_bottom_sheet.consult_button.isEnabled() + assert repository.report_reads == previous_reads + empty_message = _header(shell).replace("无关联患者", "") + _body(shell) + assert any(word in empty_message for word in ("关联", "绑定", "缺少", "无法", "未提供")) + + page = shell.pages["prescriptions"] + page.patient_filter.setText("查无此人") + QTest.keyClick(page.patient_filter, Qt.Key.Key_Return) + _wait_for(lambda: page.table.rowCount() == 0, "Patient filter did not clear the table") + assert "无关联患者" not in _header(shell) + assert "赵明远" not in _header(shell) + assert "302-qwen" not in _body(shell) + assert "选择" in _header(shell) + _body(shell) + assert not shell.ai_bottom_sheet.consult_button.isEnabled() + + +def test_open_report_tracks_highlight_and_rejects_foreign_patient(workstation, monkeypatch) -> None: + shell, repository = workstation + _open_prescriptions(shell) + _click_patient(shell, "赵明远") + _wait_for(lambda: "302-qwen" in _body(shell), "Initial report did not arrive") + shell.ai_bottom_sheet.report_button.click() + panel = shell.wing_manager.active_widget + assert isinstance(panel, ClinicalAiReportWingPanel) + original_read = repository.list_patient_ai_reports + monkeypatch.setattr(repository, "list_patient_ai_reports", lambda _: original_read(302)) + _click_patient(shell, "吴诗雨") + assert "吴诗雨" in _header(shell) + assert "302-qwen" not in _body(shell) + _wait_for(lambda: "读取失败" in shell.ai_bottom_sheet._vm.params[1], "Foreign report accepted") + assert shell.wing_manager.active_widget is panel + assert panel._patient_name == "吴诗雨" + assert not panel._histories["qwen"] + assert not panel.copy_btn.isEnabled() + + +def test_visit_report_is_shown_when_patient_history_is_empty(workstation, monkeypatch) -> None: + shell, repository = workstation + monkeypatch.setattr( + repository, "list_patient_ai_reports", lambda pid: {"patient_id": pid, "reports": []} + ) + visits = [] + + def visit_reports(visit_id): + visits.append(visit_id) + return { + "diagnosis_id": visit_id, + "reports": [ + { + "model_key": "qwen", + "report": { + "summary": "本次诊单摘要", + "main_indications": "本次诊单治法", + "cautions": ["本次诊单复核提醒"], + }, + } + ], + } + + monkeypatch.setattr(repository, "list_diagnosis_ai_reports", visit_reports) + _open_prescriptions(shell) + _click_patient(shell, "吴诗雨") + _wait_for(lambda: "本次诊单摘要" in _body(shell), "Saved visit report was not displayed") + assert 503 in visits + assert "本次诊单治法" in _body(shell) + assert "本次诊单复核提醒" in _body(shell) + shell.ai_bottom_sheet._model_buttons["openai"].click() + assert "吴诗雨" in _header(shell) + assert "暂无" in _body(shell) + assert "本次诊单摘要" not in _body(shell) diff --git a/app/tests/test_prescription_ui.py b/app/tests/test_prescription_ui.py index 92f2be5f3..e14f599a2 100755 --- a/app/tests/test_prescription_ui.py +++ b/app/tests/test_prescription_ui.py @@ -306,7 +306,9 @@ def test_issued_page_sends_exact_filter_dto_and_row_guards( page._selection_changed() assert page.table.columnCount() == 13 - assert page.table.isColumnHidden(11) and page.table.isColumnHidden(12) + for column in (11, 12): + assert not page.table.isColumnHidden(column) + assert page.table.item(0, column).text() == "" assert page.table.horizontalHeaderItem(2).text() == "操作" assert page.table.cellWidget(0, 2) is not None # 处方类型与审核状态由 _RowDecorationDelegate 绘制标签,不再为每行每列 diff --git a/app/tests/test_prescriptions_infinite.py b/app/tests/test_prescriptions_infinite.py index 56d0c53b1..9e0d1a41c 100755 --- a/app/tests/test_prescriptions_infinite.py +++ b/app/tests/test_prescriptions_infinite.py @@ -8,8 +8,9 @@ from types import SimpleNamespace import pytest from PySide6.QtCore import Qt from PySide6.QtTest import QTest -from PySide6.QtWidgets import QApplication +from PySide6.QtWidgets import QApplication, QPushButton +from doctor_workstation.core.models import Prescription from doctor_workstation.ui.pages import prescription_library, prescriptions @@ -119,8 +120,6 @@ def test_local_effect_filter_continues_until_matching_rows_are_visible(app, monk def test_audit_status_sort_keeps_actions_on_the_visible_prescription(app, monkeypatch): - from PySide6.QtWidgets import QPushButton - monkeypatch.setattr(prescriptions, "run_async", inline) class AuditRepository(Repository): @@ -154,3 +153,86 @@ def test_audit_status_sort_keeps_actions_on_the_visible_prescription(app, monkey next(button for button in buttons if button.accessibleName() == "查看处方").click() assert opened[-1] == expected page.close() + + +def test_highlighted_prescription_follows_selection_and_silent_list_refresh(app, monkeypatch): + monkeypatch.setattr(prescriptions, "run_async", inline) + rows = [ + {"id": 10, "patient_id": 750, "patient_name": "A", "diagnosis_id": 95}, + {"id": 11, "patient_id": 0, "patient_name": "B", "diagnosis_id": 96, "sn": ""}, + ] + + def list_prescriptions(*, patient_name="", **_filters): + records = [Prescription.from_dict(row) for row in rows if patient_name in row["patient_name"]] + return {"lists": records, "count": len(records)} + + page = prescriptions.PrescriptionsPage( + SimpleNamespace(list_prescriptions=list_prescriptions), {"*"} + ) + events = [] + page.selected_prescription_changed.connect(events.append) + page.resize(1250, 760) + page.show() + try: + app.processEvents() + table = page.table + table.sortItems(5, Qt.SortOrder.AscendingOrder) + QTest.mouseClick( + table.viewport(), Qt.MouseButton.LeftButton, + pos=table.visualItemRect(table.item(1, 0)).center(), + ) + assert page.selected_prescription() == events[-1] == rows[1] + QTest.mouseClick( + table.viewport(), Qt.MouseButton.LeftButton, + pos=table.visualItemRect(table.item(0, 5)).center(), + ) + assert page.selected_prescription() == events[-1] == rows[0] + QTest.keyClick(table.copy_text, Qt.Key.Key_Down) + assert page.selected_prescription() == events[-1] == rows[1] + QTest.keyClick(table, Qt.Key.Key_Up) + assert page.selected_prescription() == events[-1] == rows[0] + + viewed = [] + monkeypatch.setattr(page, "_view_selected", lambda: viewed.append(page.selected_prescription())) + buttons = table.cellWidget(1, 2).findChildren(QPushButton) + next(button for button in buttons if button.accessibleName() == "查看处方").click() + assert viewed == [rows[1]] + assert events[-1] == rows[1] + + events.clear() + rows.reverse() # A different server order must preserve the highlighted prescription. + page.refresh() + page.hide() + page.show() + assert page.selected_prescription()["id"] == 11 + assert events == [] + rows[0]["diagnosis_id"] = 106 + page.refresh() + assert events == [rows[0]] + + table.clearSelection() + assert page.selected_prescription() == events[-1] == {} + events.clear() + page.refresh() + assert page.selected_prescription() == {} + assert events == [] + page.patient_filter.setText("A") + page._search() + assert events == [rows[1]] + page.patient_filter.clear() + page._search() + table.selectRow(1) + assert page.selected_prescription()["id"] == 11 + rows.pop(0) + events.clear() + page.refresh() + assert table.rowCount() == 1 + assert page.selected_prescription() == {} + assert events == [{}] + + table.selectRow(0) + page.patient_filter.setText("missing") + page._search() + assert page.selected_prescription() == events[-1] == {} + finally: + page.close() diff --git a/app/tests/test_prescriptions_tech_blue.py b/app/tests/test_prescriptions_tech_blue.py index a931b5c04..18baa0b53 100755 --- a/app/tests/test_prescriptions_tech_blue.py +++ b/app/tests/test_prescriptions_tech_blue.py @@ -125,10 +125,17 @@ def test_shell_preserves_all_columns_filters_and_reachable_pager( "patient_name", "audit_status", "void_status", "doctor_name", "assistant_name", "create_time", "__ai_status__", "__ai_agreement__", ] - assert [table.horizontalHeader().logicalIndex(index) for index in range(11)] == [ - 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 2, + header = table.horizontalHeader() + columns = [header.logicalIndex(index) for index in range(header.count())] + visible = [column for column in columns if not table.isColumnHidden(column)] + assert [table.columns[column].key for column in visible] == [ + "__selected__", "patient_name", "sn", "prescription_type", "is_system_auto", "audit_status", + "void_status", "doctor_name", "assistant_name", "create_time", + "__ai_status__", "__ai_agreement__", "__actions__", + ] + assert [table.horizontalHeaderItem(column).text() for column in visible[-3:]] == [ + "AI 分析", "与 AI 一致度", "操作", ] - assert table.horizontalHeaderItem(2).text() == "操作" assert page.filter_card.height() == filter_height for name in ("quick_date", "start_time", "end_time", "audit_filter", "source_filter", "sn_filter", "patient_filter", "doctor_filter", "query_button", "reset_button"): @@ -148,17 +155,17 @@ def test_shell_preserves_all_columns_filters_and_reachable_pager( if width == 1536: assert table.horizontalScrollBar().maximum() == 0 for row in range(table.rowCount()): - for column in range(11): + for column in visible: assert table.viewport().rect().contains(table.visualItemRect(table.item(row, column))), (row, column) _assert_visible_within(page.pager, shell) - # Every logical column remains reachable in the native table at every width. + # Every visible column remains reachable in the native table at every width. outer_scroll.setValue(outer_scroll.maximum()) - for column in range(11): + for column in visible: table.scrollToItem(table.item(0, column), QAbstractItemView.ScrollHint.EnsureVisible) _settle(application) assert table.viewport().rect().contains(table.visualItemRect(table.item(0, column))), column - table.horizontalScrollBar().setValue(table.horizontalScrollBar().maximum()) + table.scrollToItem(table.item(0, 2), QAbstractItemView.ScrollHint.EnsureVisible) _settle(application) action_host = table.cellWidget(0, 2) assert action_host is not None @@ -197,6 +204,19 @@ def test_native_checkbox_center_clicks_and_space_keep_row_binding(shell_factory, assert selector.data(Qt.ItemDataRole.UserRole).id == 802 +def test_refresh_in_wide_window_preserves_table_fit_after_resize(shell_factory, application): + shell, page = shell_factory(1920, 960) + page.refresh() + _settle(application) + shell.resize(1536, 960) + _settle(application) + table = page.table + assert table.horizontalScrollBar().maximum() == 0 + for row in range(table.rowCount()): + for button in table.cellWidget(row, 2).findChildren(QPushButton): + _assert_visible_within(button, table.viewport()) + + @pytest.mark.parametrize("order", [Qt.SortOrder.AscendingOrder, Qt.SortOrder.DescendingOrder]) def test_sorted_native_row_view_button_targets_visible_record( shell_factory, application, monkeypatch, order @@ -311,13 +331,15 @@ def test_copy_context_menu_and_refresh_follow_the_visible_row(shell_factory, app item = table.item(0, 1) page._open_ai_context_menu(table.visualItemRect(item).center()) menu = page._ai_context_menu - actions = {action.text(): action for action in menu.actions()} - assert set(actions) == {"复制单元格", "复制整行"} + actions = {action.text(): action for action in menu.actions() if not action.isSeparator()} + assert set(actions) == {"复制单元格", "复制整行", "AI 分析"} + assert not actions["AI 分析"].isEnabled() actions["复制单元格"].trigger() assert item.text() in application.clipboard().text() assert f"ID: {_record_id(table, 0)}" in application.clipboard().text() actions["复制整行"].trigger() copied = application.clipboard().text() + assert copied.split("\t")[0] == table.item(0, 5).text().replace("\n", " ") for column in range(3, 11): assert table.item(0, column).text() in copied assert "\t" in copied and "复制" not in copied diff --git a/app/tests/test_spatial_cockpit_v3.py b/app/tests/test_spatial_cockpit_v3.py index 4762aa01c..fb8720ac4 100644 --- a/app/tests/test_spatial_cockpit_v3.py +++ b/app/tests/test_spatial_cockpit_v3.py @@ -9,9 +9,9 @@ from typing import Any os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") import pytest -from PySide6.QtCore import QEvent +from PySide6.QtCore import QEvent, Qt from PySide6.QtTest import QTest -from PySide6.QtWidgets import QApplication +from PySide6.QtWidgets import QApplication, QPushButton from doctor_workstation.core.permissions import PermissionSet from doctor_workstation.services.demo_repository import DEMO_PERMISSIONS, DemoDoctorRepository @@ -19,6 +19,7 @@ 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 +from doctor_workstation.ui.visuals.aurora_sheet import CollapsibleObsidianSheet def _settle(app: QApplication, rounds: int = 16) -> None: @@ -73,6 +74,7 @@ def test_empty_cockpit_snapshot_contains_zero_fabricated_metrics() -> None: assert all(vital.value == "—" for vital in empty_vm.diurnal.vitals) assert empty_vm.journey.primary_metric_text == "—" assert empty_vm.aurora.active_model_key == "doubao" + assert empty_vm.aurora.patient_name == "" assert empty_vm.aurora.gauge_value in {"0", "0/6", "—"} # Ensure zero legacy fake texts leak into empty state @@ -170,6 +172,7 @@ def test_cockpit_viewmodel_maps_real_clinical_records_and_ai_payload() -> None: assert vm.has_patient is True assert vm.patient_name == "张建国" + assert vm.aurora.patient_name == vm.patient_name assert vm.progression.primary_value == "6.6" assert vm.progression.unit == "mmol/L" recorded_bars = [b for b in vm.progression.bars if b.recorded] @@ -203,6 +206,86 @@ def test_cockpit_viewmodel_maps_real_clinical_records_and_ai_payload() -> None: assert len(vm.aurora.cards[2].risk_items) == 2 +@pytest.mark.parametrize( + ("state", "status", "message"), + [ + ("reading", "正在读取", "正在读取"), + ("error", "读取失败", "读取失败"), + ("permission", "无查看权限", "无权查看"), + ("missing", "暂无报告", "暂无已保存"), + ], +) +def test_saved_report_status_covers_every_analysis_card(state: str, status: str, message: str) -> None: + vm = derive_cockpit_snapshot( + diagnosis={"id": 17, "patient_name": "孙芳"}, + ai_state=state, + active_ai_model="openai", + ai_payload={ + "diagnosis_advice": "此前缓存的诊断建议", + "risk_assessment": ["此前缓存的风险"], + "generated_at": "2026-11-12", + }, + ).aurora + assert "孙芳" in vm.ai_summary_line and "OpenAI" in vm.ai_summary_line + assert message in vm.ai_summary_line + assert dict(vm.params)["报告状态"] == status + assert dict(vm.params)["快照时间"] == "—" + for card, section in zip(vm.cards, ("诊断建议", "治疗建议", "风险评估"), strict=True): + assert card.badge_text == status + assert message in card.body_text and section in card.body_text + assert card.foot_right == "" + assert not card.risk_items + assert "此前缓存" not in repr(vm) + + +def test_report_read_failure_reason_reaches_cards_when_summary_is_hidden() -> None: + reason = "读取病历报告失败,请检查网络连接。" + vm = derive_cockpit_snapshot( + patient={"id": 32, "name": "孙芳"}, ai_state="error", ai_message=reason + ).aurora + assert vm.ai_summary_line == reason + assert all(card.body_text == reason for card in vm.cards) + + +@pytest.mark.parametrize("width", [610, 1250]) +def test_analysis_sheet_heading_tracks_patient_in_both_states(application: QApplication, width: int) -> None: + sheet = CollapsibleObsidianSheet() + sheet.resize(width, sheet.height()) + sheet.show() + try: + saved = derive_cockpit_snapshot( + appointment={"patient_name": "—"}, + diagnosis={"id": 702, "patient_name": "阿依古丽·买买提"}, + ai_payload={"diagnosis_advice": "已保存的报告正文"}, + ).aurora + sheet.set_view_model(saved) + assert saved.patient_name == "阿依古丽·买买提" + for expanded in (False, True): + sheet.set_expanded(expanded) + application.processEvents() + assert sheet.width() == width + assert sheet.title_label.isVisible() + assert saved.patient_name in sheet.title_label.text() + assert sheet.title_label.width() >= sheet.title_label.sizeHint().width() + assert sheet.summary_label.text() == "已保存的报告正文" + + second = derive_cockpit_snapshot(patient={"id": 33, "name": "孙芳"}).aurora + sheet.set_view_model(second) + assert "孙芳" in sheet.title_label.text() + assert saved.patient_name not in sheet.title_label.text() + assert "已保存的报告正文" not in sheet.summary_label.text() + + unnamed = derive_cockpit_snapshot(patient={"id": 33}).aurora + assert unnamed.has_patient and not unnamed.patient_name + sheet.set_view_model(unnamed) + assert "姓名未记录" in sheet.title_label.text() + sheet.set_view_model(derive_cockpit_snapshot().aurora) + assert "未选择患者" in sheet.title_label.text() + assert "孙芳" not in sheet.title_label.text() + finally: + sheet.close() + + def test_spatial_shell_auto_fallback_to_consultations_when_appointments_empty( application: QApplication, ) -> None: @@ -292,14 +375,37 @@ def test_spatial_shell_zero_sidebar_cockpit_and_cross_page_flow( shell.wing_manager.close_wing() _settle(application, 2) - # Explicit legacy chart mode round-trip still works cleanly when invoked directly - rec_page.set_workspace_mode("chart") + # Switch patients first so a reset to the default queue row cannot pass. + patient_store = shell.patient_context_store + initial_patient = patient_store.current_patient + second_row = rec_page.cockpit_view.timeline_layout.itemAt(1).widget() + QTest.mouseClick(second_row, Qt.MouseButton.LeftButton) + _settle(application, 8) + selected_patient = patient_store.current_patient + assert selected_patient.has_patient + assert selected_patient.patient_id != initial_patient.patient_id + + classic_button = shell.classic_reception_button + assert classic_button.isVisible() + assert classic_button.text() == "原版接诊台" + QTest.mouseClick(classic_button, Qt.MouseButton.LeftButton) _settle(application, 4) assert rec_page._workspace_mode == "chart" - assert rec_page._return_to_cockpit_bar.isVisible() - rec_page.set_workspace_mode("cockpit") + assert rec_page.queue_list.isVisible() + assert rec_page.queue_list.currentRow() == 1 + assert rec_page.detail_tabs.isVisible() + assert rec_page.patient_name_label.isVisible() + assert rec_page.patient_name_label.text() == selected_patient.patient_name + assert patient_store.current_patient.appointment_id == selected_patient.appointment_id + + back_button = rec_page._return_to_cockpit_bar.findChild(QPushButton) + assert back_button is not None and back_button.isVisible() + assert back_button.text() == "← 返回临床接诊总览" + QTest.mouseClick(back_button, Qt.MouseButton.LeftButton) _settle(application, 4) - assert rec_page._workspace_mode == "cockpit" + assert rec_page.cockpit_view.isVisible() + assert classic_button.isVisible() + assert patient_store.current_patient.appointment_id == selected_patient.appointment_id # Expand Obsidian Aurora-Glass Bottom Sheet assert not shell.ai_bottom_sheet.is_expanded @@ -318,6 +424,7 @@ def test_spatial_shell_zero_sidebar_cockpit_and_cross_page_flow( _settle(application, 14) appt_page = shell.pages["appointments"] assert appt_page.spatial_week_card.isVisible() + assert not classic_button.isVisible() for route_key in ("patients", "prescription_library", "prescriptions", "consultations"): assert shell.navigate(route_key) @@ -325,6 +432,11 @@ def test_spatial_shell_zero_sidebar_cockpit_and_cross_page_flow( page = shell.pages[route_key] assert hasattr(page, "spatial_bridge") assert page.spatial_bridge.isVisible() + assert not classic_button.isVisible() + + assert shell.navigate("reception") + _settle(application, 4) + assert classic_button.isVisible() finally: for page in shell.pages.values(): poll = getattr(page, "poll_timer", None) diff --git a/app/tests/test_spatial_nav_order.py b/app/tests/test_spatial_nav_order.py new file mode 100644 index 000000000..06094fee7 --- /dev/null +++ b/app/tests/test_spatial_nav_order.py @@ -0,0 +1,251 @@ +from __future__ import annotations + +import os +from contextlib import contextmanager +from dataclasses import replace + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +import pytest +from PySide6.QtCore import QEvent, QPoint, QSettings, Qt +from PySide6.QtGui import QContextMenuEvent +from PySide6.QtTest import QSignalSpy, QTest +from PySide6.QtWidgets import QApplication, QMenu, QWidget + +from doctor_workstation.ui import shell, shell_spatial + +AI = "ai_assistant" +DEFAULT = ["reception", "appointments", "patients", AI] +PERMISSIONS = { + "doctor.appointment/lists", + "firstvisit.myPatient/lists", + "tcm.diagnosis/aiAssistant", +} + + +class _Page(QWidget): + def __init__(self, repository, *, permissions, current_user, parent): + super().__init__(parent) + + +@pytest.fixture +def open_shell(monkeypatch, tmp_path): + app = QApplication.instance() or QApplication([]) + monkeypatch.setattr( + shell, "NAVIGATION", [replace(item, page_type=_Page) for item in shell.NAVIGATION] + ) + monkeypatch.setattr( + shell_spatial, + "QSettings", + lambda *_: QSettings(str(tmp_path / "settings.ini"), QSettings.Format.IniFormat), + ) + monkeypatch.setattr( + shell_spatial.SpatialShellWindow, "_prewarm_wing_surfaces", lambda self: None + ) + + @contextmanager + def open_window(user_id=1, permissions=PERMISSIONS): + user = {"id": user_id, "account": f"test-{user_id}"} + window = shell_spatial.SpatialShellWindow( + object(), {"user": user, "demo_mode": True}, permissions + ) + window.resize(1440, 900) + window.show() + window.activateWindow() + app.processEvents() + try: + yield window + finally: + window.close() + window.deleteLater() + app.sendPostedEvents(None, QEvent.Type.DeferredDelete) + app.processEvents() + + return open_window + + +def _visual_order(window): + keys = {button: key for key, button in window.nav_buttons.items()} + if hasattr(window, "ai_nav_button"): + keys[window.ai_nav_button] = AI + return [keys[window.nav_layout.itemAt(i).widget()] for i in range(window.nav_layout.count())] + + +def _drag(source, end): + QTest.mousePress(source, Qt.MouseButton.LeftButton, pos=source.rect().center()) + QTest.mouseMove(source, end) + QTest.mouseRelease(source, Qt.MouseButton.LeftButton, pos=end) + QApplication.processEvents() + + +def _visible_feedback(name): + return [ + widget for widget in QApplication.allWidgets() + if widget.objectName() == name and widget.isVisible() + ] + + +@pytest.mark.parametrize("key", ["patients", AI]) +@pytest.mark.parametrize("hold", [False, True], ids=["short-click", "hold-and-release"]) +def test_press_without_drag_activates_once_and_leaves_no_preview(open_shell, key, hold): + with open_shell() as window: + button = window.ai_nav_button if key == AI else window.nav_buttons[key] + clicked = QSignalSpy(button.clicked) + pos = button.rect().center() + QTest.mousePress(button, Qt.MouseButton.LeftButton, pos=pos) + if hold: + QTest.qWait(300) + preview, = _visible_feedback("NavDragPreview") + assert preview.width() > 0 and preview.height() > 0 + else: + assert not _visible_feedback("NavDragPreview") + assert clicked.count() == 0 + assert window.stack.currentWidget() is window.pages["reception"] + assert not window.ai_bottom_sheet.is_expanded + + QTest.mouseRelease(button, Qt.MouseButton.LeftButton, pos=pos) + QTest.qWait(300) + assert clicked.count() == 1 + assert _visual_order(window) == DEFAULT + assert not _visible_feedback("NavDragPreview") + assert not _visible_feedback("NavDragOrigin") + if key == AI: + assert window.ai_bottom_sheet.is_expanded + else: + assert window.stack.currentWidget() is window.pages[key] + + +@pytest.mark.parametrize("key", ["reception", AI], ids=["selected-page", "ai"]) +@pytest.mark.parametrize("cancel", ["outside", "escape"]) +def test_preview_tracks_drag_origin_stays_put_and_cancel_discards_move(open_shell, key, cancel): + with open_shell() as window: + button = window.ai_nav_button if key == AI else window.nav_buttons[key] + clicked = QSignalSpy(button.clicked) + press = button.rect().center() + original_center = button.mapToGlobal(press) + cursor_before = button.cursor().shape() + QTest.mousePress(button, Qt.MouseButton.LeftButton, pos=press) + if cancel == "outside": + QTest.qWait(300) + assert _visible_feedback("NavDragPreview") + targets = [window.nav_buttons[target_key] for target_key in ("appointments", "patients")] + if key == AI: + targets.reverse() + first, second = [target.mapToGlobal(target.rect().center()) for target in targets] + QTest.mouseMove(button, button.mapFromGlobal(first)) + preview, = _visible_feedback("NavDragPreview") + origin, = _visible_feedback("NavDragOrigin") + assert preview.rect().contains(preview.mapFromGlobal(first)) + assert origin.rect().contains(origin.mapFromGlobal(original_center)) + preview_start = preview.mapToGlobal(QPoint()) + origin_start = origin.mapToGlobal(QPoint()) + QTest.mouseMove(button, button.mapFromGlobal(second)) + assert preview.mapToGlobal(QPoint()) - preview_start == second - first + assert origin.mapToGlobal(QPoint()) == origin_start + + if cancel == "escape": + QTest.keyClick(window.focusWidget() or button, Qt.Key.Key_Escape) + assert not _visible_feedback("NavDragPreview") + assert not _visible_feedback("NavDragOrigin") + release = second + else: + bar = window.nav_island + release = bar.mapToGlobal(QPoint(bar.rect().center().x(), bar.height() + 20)) + QTest.mouseMove(button, button.mapFromGlobal(release)) + QTest.mouseRelease(button, Qt.MouseButton.LeftButton, pos=button.mapFromGlobal(release)) + QTest.qWait(300) + assert not _visible_feedback("NavDragPreview") + assert not _visible_feedback("NavDragOrigin") + assert button.isVisible() and not button.isDown() + assert button.cursor().shape() == cursor_before + assert _visual_order(window) == DEFAULT + assert window.nav_buttons["reception"].isChecked() + assert window.stack.currentWidget() is window.pages["reception"] + assert not window.ai_bottom_sheet.is_expanded + assert clicked.count() == 0 + QTest.mouseClick(button, Qt.MouseButton.LeftButton) + assert clicked.count() == 1 + + +def test_drag_reorders_without_activating_and_preserves_buttons_and_shortcuts(open_shell): + with open_shell() as window: + assert _visual_order(window) == DEFAULT + ai = window.ai_nav_button + first = window.nav_buttons["reception"] + before_first = first.mapToGlobal(QPoint(2, first.height() // 2)) + _drag(ai, ai.mapFromGlobal(before_first)) + assert _visual_order(window) == [AI, "reception", "appointments", "patients"] + assert not _visible_feedback("NavDragPreview") + assert not _visible_feedback("NavDragOrigin") + assert window.nav_island.order == _visual_order(window) + assert window.stack.currentWidget() is window.pages["reception"] + assert not window.ai_bottom_sheet.is_expanded + + patients = window.nav_buttons["patients"] + outside = window.nav_island.mapToGlobal(QPoint(2, window.nav_island.height() + 22)) + _drag(patients, patients.mapFromGlobal(outside)) + assert _visual_order(window) == [AI, "reception", "appointments", "patients"] + assert window.stack.currentWidget() is window.pages["reception"] + + QTest.mouseClick(patients, Qt.MouseButton.LeftButton) + assert window.stack.currentWidget() is window.pages["patients"] + QTest.keyClick(window, Qt.Key.Key_2, Qt.KeyboardModifier.AltModifier) + assert window.stack.currentWidget() is window.pages["reception"] + assert first.isChecked() + QTest.mouseClick(ai, Qt.MouseButton.LeftButton) + assert window.ai_bottom_sheet.is_expanded + QTest.keyClick(window, Qt.Key.Key_BracketRight, Qt.KeyboardModifier.ControlModifier) + assert not window.ai_bottom_sheet.is_expanded + QTest.keyClick(window, Qt.Key.Key_1, Qt.KeyboardModifier.AltModifier) + assert window.ai_bottom_sheet.is_expanded + assert window.stack.currentWidget() is window.pages["reception"] + + +def test_context_menu_moves_the_button_and_restores_order(open_shell): + with open_shell() as window: + + def context_actions(): + button = window.ai_nav_button + pos = button.rect().center() + event = QContextMenuEvent(QContextMenuEvent.Reason.Mouse, pos, button.mapToGlobal(pos)) + QApplication.sendEvent(button, event) + menu = QApplication.activePopupWidget() + assert isinstance(menu, QMenu) + return menu, {action.text(): action for action in menu.actions()} + + menu, actions = context_actions() + assert not actions["向右移动"].isEnabled() + QTest.mouseClick( + menu, Qt.MouseButton.LeftButton, pos=menu.actionGeometry(actions["向左移动"]).center() + ) + assert _visual_order(window) == ["reception", "appointments", AI, "patients"] + menu, actions = context_actions() + QTest.mouseClick( + menu, + Qt.MouseButton.LeftButton, + pos=menu.actionGeometry(actions["恢复默认顺序"]).center(), + ) + assert _visual_order(window) == DEFAULT + assert not window.ai_bottom_sheet.is_expanded + + +def test_order_persists_per_user_and_respects_permissions(open_shell): + reordered = ["patients", AI, "reception", "appointments"] + with open_shell() as window: + window.nav_island.move_button("patients", 0) + window.nav_island.move_button(AI, 1) + assert _visual_order(window) == reordered + + with open_shell(2) as other_user: + assert _visual_order(other_user) == DEFAULT + with open_shell(permissions={"doctor.appointment/lists"}) as limited: + assert _visual_order(limited) == ["reception", "appointments"] + assert not hasattr(limited, "ai_nav_button") + limited.nav_island.move_button("appointments", 0) + assert _visual_order(limited) == ["appointments", "reception"] + with open_shell() as restored: + assert _visual_order(restored) == ["patients", AI, "appointments", "reception"] + restored.nav_island.reset_order() + assert _visual_order(restored) == DEFAULT + with open_shell() as reset: + assert _visual_order(reset) == DEFAULT diff --git a/app/tests/test_spatial_wings_v4.py b/app/tests/test_spatial_wings_v4.py index e7a179a7c..4bf5012f6 100644 --- a/app/tests/test_spatial_wings_v4.py +++ b/app/tests/test_spatial_wings_v4.py @@ -7,12 +7,13 @@ import os os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") import pytest -from PySide6.QtCore import QEvent, Qt, QTimer +from PySide6.QtCore import QDeadlineTimer, QEvent, QObject, Qt, QTimer from PySide6.QtTest import QTest -from PySide6.QtWidgets import QApplication, QDialog +from PySide6.QtWidgets import QApplication, QDialog, QLabel, QWidget from doctor_workstation.core.permissions import PermissionSet from doctor_workstation.services.demo_repository import DEMO_PERMISSIONS, DemoDoctorRepository +from doctor_workstation.ui.dialogs.ai_consult import AiConsultDialog from doctor_workstation.ui.dialogs.appointment_complete import AppointmentCompleteDialog from doctor_workstation.ui.dialogs.prescription import PrescriptionEditorDialog from doctor_workstation.ui.shell_spatial import SpatialShellWindow @@ -145,6 +146,73 @@ def test_spatial_wing_ai_report_left_right_dock_and_magnetic_sidecar( application.processEvents() +def test_deep_chat_opens_without_flashing_a_top_level_window(application: QApplication) -> None: + repo = DemoDoctorRepository() + session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) + shell = SpatialShellWindow(repo, {"session": session, "demo_mode": True}, session.permissions) + shell.resize(1536, 864) + shell.show() + manager = shell.wing_manager + windows_shown = [] + inline_timestamps = [] + painted_in_wing = [] + + class OpeningEvents(QObject): + def eventFilter(self, widget, event): + if event.type() == QEvent.Type.Show and isinstance(widget, QWidget): + if widget.isWindow(): + windows_shown.append((type(widget).__name__, widget.objectName())) + elif ( + isinstance(widget, QLabel) + and widget.objectName() == "AiConsultTime" + and manager.card.body_host.isAncestorOf(widget) + and widget.text() + ): + inline_timestamps.append(widget.text()) + elif ( + event.type() == QEvent.Type.Paint + and isinstance(widget, AiConsultDialog) + and not painted_in_wing + ): + painted_in_wing.append(manager.card.body_host.isAncestorOf(widget)) + return False + + def close_after_history_is_painted(): + # The button runs QDialog.exec(). Observe the real nested event loop until demo history arrives. + deadline = QDeadlineTimer(3000) + while not (inline_timestamps and painted_in_wing) and not deadline.hasExpired(): + QTest.qWait(10) + if manager.is_open: + manager.close_wing() + elif isinstance(modal := application.activeModalWidget(), QDialog): + modal.reject() + + observer = OpeningEvents() + try: + deadline = QDeadlineTimer(3000) + while ( + not shell.patient_context_store.current_patient.diagnosis_id + and not deadline.hasExpired() + ): + QTest.qWait(10) + assert shell.patient_context_store.current_patient.diagnosis_id > 0 + application.installEventFilter(observer) + for _ in range(2): + inline_timestamps.clear() + painted_in_wing.clear() + QTimer.singleShot(0, close_after_history_is_painted) + QTest.mouseClick(shell.ai_bottom_sheet.consult_button, Qt.MouseButton.LeftButton) + assert painted_in_wing == [True] + assert inline_timestamps + assert not windows_shown, f"Transient top-level widgets shown: {windows_shown}" + finally: + application.removeEventFilter(observer) + shell.close() + shell.deleteLater() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + application.processEvents() + + def test_qdialogs_and_exec_callers_mount_non_modally_in_spatial_wing( application: QApplication, ) -> None: diff --git a/app/tests/test_twin_stage_styles.py b/app/tests/test_twin_stage_styles.py new file mode 100644 index 000000000..7428b8971 --- /dev/null +++ b/app/tests/test_twin_stage_styles.py @@ -0,0 +1,184 @@ +"""Offscreen regressions for the cockpit's body style selector and patient evidence map.""" + +from __future__ import annotations + +import os +from collections.abc import Iterator +from dataclasses import replace +from itertools import combinations +from pathlib import Path + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +import pytest +from PySide6.QtCore import QRect, QRectF, QSettings, Qt +from PySide6.QtTest import QTest +from PySide6.QtWidgets import QApplication, QToolButton + +from doctor_workstation.ui.viewmodels import derive_cockpit_snapshot +from doctor_workstation.ui.viewmodels.cockpit_vm import CockpitSnapshotVM +from doctor_workstation.ui.visuals.twin_stage import TWIN_STYLES, ClinicalTwinStageWidget + +STYLE_KEYS = tuple(TWIN_STYLES) + + +@pytest.fixture(scope="module") +def application() -> QApplication: + return QApplication.instance() or QApplication([]) + + +@pytest.fixture +def settings(tmp_path: Path) -> QSettings: + return QSettings(str(tmp_path / "cockpit.ini"), QSettings.Format.IniFormat) + + +@pytest.fixture +def patient() -> CockpitSnapshotVM: + return derive_cockpit_snapshot( + {"id": 1, "patient_name": "样例患者"}, + {"id": 2}, + {"id": 3, "chief_complaint": "口渴", "past_history_text": "样例病史", "tongue": "样例舌象"}, + ) + + +@pytest.fixture +def stage( + application: QApplication, settings: QSettings, monkeypatch: pytest.MonkeyPatch +) -> Iterator[ClinicalTwinStageWidget]: + monkeypatch.setenv("DOCTOR_MOTION", "off") + widget = ClinicalTwinStageWidget(settings=settings) + widget.resize(780, 500) + widget.show() + application.processEvents() + yield widget + widget.close() + + +def test_menu_actions_select_and_restore_local_style( + stage: ClinicalTwinStageWidget, settings: QSettings +) -> None: + assert stage.style_key == "jade" + assert len(STYLE_KEYS) >= 10 + assert isinstance(stage.style_button, QToolButton) + actions = stage.style_button.menu().actions() + assert tuple(action.data() for action in actions) == STYLE_KEYS + assert len({action.text().strip() for action in actions if action.text().strip()}) == len(actions) + for action in actions: + action.trigger() + assert stage.style_key == action.data() + assert [item.data() for item in actions if item.isChecked()] == [action.data()] + + settings.sync() + assert settings.allKeys() + reopened = ClinicalTwinStageWidget( + settings=QSettings(settings.fileName(), QSettings.Format.IniFormat) + ) + try: + assert reopened.style_key == STYLE_KEYS[-1] + assert [a.data() for a in reopened.style_button.menu().actions() if a.isChecked()] == [STYLE_KEYS[-1]] + finally: + reopened.close() + + +def test_ten_styles_render_distinct_bodies( + stage: ClinicalTwinStageWidget, patient: CockpitSnapshotVM +) -> None: + stage.set_snapshot(patient) + # Only sample the figure, away from the menu, patient cards, and footer. + crop = QRect(stage.width() // 2 - 70, stage.height() // 2 - 164, 140, 328) + samples = {} + for key in STYLE_KEYS: + stage.set_style(key) + image = stage.grab(crop).toImage().scaled( + 50, 100, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation + ) + assert not image.isNull(), key + samples[key] = [ + image.pixelColor(x, y).getRgb()[:3] + for y in range(image.height()) for x in range(image.width()) + ] + + for (first, left), (second, right) in combinations(samples.items(), 2): + # Ignore tiny anti-aliasing differences. A substantial part of the actual figure must change. + changed = sum( + max(abs(a - b) for a, b in zip(p, q, strict=True)) >= 16 + for p, q in zip(left, right, strict=True) + ) + assert changed > len(left) * 0.10, (first, second, changed) + + +@pytest.mark.parametrize("key", STYLE_KEYS) +def test_style_preserves_mode_links_and_patient_selection( + key: str, stage: ClinicalTwinStageWidget, patient: CockpitSnapshotVM +) -> None: + stage.set_style(key) + stage.set_snapshot(patient) + loci, charts = [], [] + stage.locus_clicked.connect(loci.append) + stage.open_chart_requested.connect(lambda: charts.append(True)) + + def click(rect: QRectF) -> None: + QTest.mouseClick(stage, Qt.MouseButton.LeftButton, pos=rect.center().toPoint()) + + stage.grab() + assert [mode for mode, _ in stage._mode_rects] == ["sanjiao", "organ", "tcm"] + for mode, mode_rect in list(stage._mode_rects): + click(mode_rect) + stage.set_style("jade" if key != "jade" else "ink") + stage.set_style(key) + stage.grab() + expected = patient.twin_for_mode(mode) + assert [(locus, tip) for locus, _, tip in stage._callout_rects] == [ + (node.locus_id, node.full_tooltip) for node in expected.nodes + ] + loci.clear() + charts.clear() + for _, rect, _ in stage._callout_rects: + click(rect) + click(stage._scan_badge_rect) + click(stage._bottom_capsule_rect) + click(stage._open_chart_rect) + details = {"sanjiao": [], "organ": ["past_history"], "tcm": ["rx_summary"]} + assert loci == [ + *(n.locus_id for n in expected.nodes), "local_diagnosis", "summary_capsule", *details[mode] + ] + assert len(charts) == int(mode == "sanjiao") + assert stage.style_key == key + + stage.set_snapshot(derive_cockpit_snapshot()) + stage.grab() + assert stage._callout_rects == [] + assert stage.style_key == key + + +def test_recorded_findings_remain_visible_in_every_style( + stage: ClinicalTwinStageWidget, patient: CockpitSnapshotVM +) -> None: + def with_head_finding(heat: float) -> CockpitSnapshotVM: + twin = replace(patient.twin_sanjiao, recorded_Zone_flags=(heat, 0.0, 0.0, 0.0)) + return replace(patient, twin_sanjiao=twin) + + clear, positive = with_head_finding(0.0), with_head_finding(1.0) + head = QRect(stage.width() // 2 - 40, 68, 80, 90) + for key in STYLE_KEYS: + stage.set_style(key) + stage.set_snapshot(clear) + baseline = stage.grab(head).toImage() + stage.set_snapshot(positive) + assert stage.grab(head).toImage() != baseline, key + + +@pytest.mark.parametrize("width", [244, 320, 440, 580, 780]) +def test_style_selector_stays_clear_of_click_targets( + width: int, stage: ClinicalTwinStageWidget, patient: CockpitSnapshotVM +) -> None: + stage.set_snapshot(patient) + stage.resize(width, 400) + stage.grab() + button = QRectF(stage.style_button.geometry()) + assert stage.style_button.isVisible() and not button.isEmpty() + assert QRectF(stage.rect()).contains(button) + targets = [stage._open_chart_rect, stage._scan_badge_rect, stage._bottom_capsule_rect] + targets.extend(rect for _, rect in stage._mode_rects) + targets.extend(rect for _, rect, _ in stage._callout_rects) + assert all(not button.intersects(target) for target in targets), (width, button, targets) diff --git a/docs/plans/prescription-ai-deployment.md b/docs/plans/prescription-ai-deployment.md index 032a2925c..41a18d3ee 100755 --- a/docs/plans/prescription-ai-deployment.md +++ b/docs/plans/prescription-ai-deployment.md @@ -67,7 +67,15 @@ ENABLED = false START_AT = 0 ``` -在 `server` 目录运行三个独立进程,并交给现有进程守护器管理: +### 后台定时任务 + +先部署包含 `prescription-ai:dispatch` 的服务端代码。已有站点执行 `server/database/migrations/2026_12_02_prescription_ai_crontab.sql`,采用版本 SQL 的站点执行等价的 `server/sql/1.9.20261202/01_prescription_ai_crontab.sql`。按实际部署替换 `zyt_` 前缀。首次安装会登记同一条任务,仍需按前述步骤初始化处方分析表与配置。升级可重复执行,并保留已有任务的暂停状态和运行周期。 + +管理后台「系统维护 → 定时任务」的「处方 AI 分析队列」默认每分钟巡检,命令为 `prescription-ai:dispatch`,参数留空。服务器须已每分钟从 `server` 目录执行 `php think crontab`。将巡检配置在常驻消费者所在主机和 PID 命名空间,使用相同的系统账号(生产为 `www`),该账号需能读写项目 `runtime/lock`。多节点部署由这台主机执行本条巡检。Linux 会核对 `/proc` 中实际运行的 `think` 入口路径、命令和队列名,兼容升级前已经启动的进程。在其他平台上,已有常驻消费者需在本次代码升级后重启一次,以登记进程锁。 + +开关关闭时定时任务直接返回。启用后只对缺失的队列通过 PHP CLI 的 `proc_open` 启动一个 `--once --scheduled` 消费者。进程在整个单轮处理期间持有队列独占锁,重叠巡检不会重复消费。准备队列接管期间空闲时按游标继续补扫。模型执行可以跨分钟,后台的定时任务时长只记录巡检和派发耗时。用同一账号运行 `php think prescription-ai:dispatch --check` 可以只读查看三条队列状态:`resident` 表示发现常驻进程,`single_run` 表示已有单轮处理,`busy` 表示队列锁正被占用,`missing` 表示未发现消费者。实际常驻进程的任务进度和失败原因可在处方详情查看。 + +保留已有进程守护器。下列命令在 `server` 目录持续消费,对模型的并发上限和每日额度继续由数据库统一控制: ```sh php think prescription-ai:work --lane=prepare @@ -75,7 +83,7 @@ php think prescription-ai:work --lane=qwen php think prescription-ai:work --lane=openai ``` -`--once` 只处理一轮,适合诊断或已有定时执行方式。只启动 prepare 不会调用模型。默认每模型并发 1,每次任务最多自动尝试 3 次、手动重新尝试 2 轮,每模型每日最多领取 200 次任务。一次模型任务可能包含多次分片调用;实际调用次数及供应商可用的 token 使用量保存在加密进度和结果中,不能把任务数当成 token 数或费用金额。 +`--once` 只处理一轮,也可用于单独诊断各队列。只启动 prepare 不会调用模型。默认每模型并发上限为 4,每次任务最多自动尝试 3 次、手动重新尝试 2 轮,每模型每日最多领取 200 次任务。一次模型任务可能包含多次分片调用;实际调用次数及供应商可用的 token 使用量保存在加密进度和结果中,不能把任务数当成 token 数或费用金额。 `prescription_ai.manual_analysis` 控制输入预算和每模型任务最大调用次数;`prescription_analysis` 控制等待、租约、并发、补偿范围与任务预算。长请求超时应小于任务租约。调整后需重启常驻消费者。 @@ -89,7 +97,7 @@ php think prescription-ai:backfill --from=2026-09-01 --to=2026-09-09 --limit=50 确认预览范围后同命令追加 `--apply` 才登记任务;用返回的 `last_id` 继续传入 `--after-id` 翻页。日期筛选使用处方 `update_time`,不是处方笺日期。命令本身不调用模型,消费者随后执行。既有同版本任务不会重复创建;已失败的单模型从报告窗口重试。 -回退时先停止三个消费者,再关闭功能开关并重启 Web 服务;保留新增表和密钥,旧处方流程继续工作。再次启用后从既定起始时间补偿缺失事件。不要删除历史报告表或密钥来暂停任务。 +回退时在后台暂停「处方 AI 分析队列」,停止现有常驻消费者,再关闭功能开关并重启 Web 服务。暂停派发后,已经领取任务的单轮消费者会完成当前工作。保留新增表和密钥,旧处方流程继续工作。再次启用后从既定起始时间补偿缺失事件。 ## 当前数据与供应商能力限制 diff --git a/server/app/adminapi/lists/tcm/PrescriptionOrderLists.php b/server/app/adminapi/lists/tcm/PrescriptionOrderLists.php index 9b543ff92..d1233d0e8 100755 --- a/server/app/adminapi/lists/tcm/PrescriptionOrderLists.php +++ b/server/app/adminapi/lists/tcm/PrescriptionOrderLists.php @@ -885,8 +885,8 @@ class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchIn 'export_supply_mode' => '供货方式', 'export_gancao_prescription_cost' => '处方成本', 'export_first_visit_assistant' => '初诊医助', - 'export_rx_audit_time' => '审核时间', - 'export_rx_auditor' => '审核人', + 'export_payment_audit_time' => '审核时间', + 'export_payment_auditor' => '审核人', ]; } diff --git a/server/app/adminapi/logic/tcm/PrescriptionAiLogic.php b/server/app/adminapi/logic/tcm/PrescriptionAiLogic.php index 97e888d64..11e728a2c 100755 --- a/server/app/adminapi/logic/tcm/PrescriptionAiLogic.php +++ b/server/app/adminapi/logic/tcm/PrescriptionAiLogic.php @@ -17,6 +17,7 @@ use app\common\service\prescriptionai\PrescriptionAiStore as Store; use app\common\service\prescriptionai\PrescriptionAiVisibility as Visibility; use DomainException; use think\facade\Db; +use think\facade\Log; final class PrescriptionAiLogic { @@ -169,23 +170,30 @@ final class PrescriptionAiLogic if (!$task) { throw new DomainException('资料尚未准备完成,请查看分析状态'); } - if ($task['status'] === 'success' || in_array($task['status'], Policy::ACTIVE_TASKS, true)) { - return ['batch_id' => $batchId, 'status' => $task['status']]; - } - if ($task['status'] !== 'failed') { + $now = time(); + $newRetry = $task['status'] === 'failed'; + if ($newRetry) { + if ((int) $task['manual_retries'] >= (int) config('prescription_analysis.max_manual_retries', 2)) { + throw new DomainException('该模型已达手动重试上限,请检查失败原因'); + } + $changes = [ + 'status' => 'retry_wait', 'attempts' => 0, 'next_run_at' => $now, + 'manual_retries' => (int) $task['manual_retries'] + 1, + 'lock_token' => '', 'lock_until' => 0, 'error_code' => '', 'updated_at' => $now, + ]; + $task = array_replace($task, $changes); + } elseif ($task['status'] !== 'success' && !in_array($task['status'], Policy::ACTIVE_TASKS, true)) { throw new DomainException('该任务不能重试'); } - if ((int) $task['manual_retries'] >= (int) config('prescription_analysis.max_manual_retries', 2)) { - throw new DomainException('该模型已达手动重试上限,请检查失败原因'); + $state = self::taskStates([$task], $now)[0]; + if ($newRetry) { + // Keep audit history and the encrypted resume checkpoint across retry rounds. + $changes['next_run_at'] = $state['progress']['next_run_at']; + $changes['error_code'] = $state['error_code']; + Db::name('prescription_ai_task')->where('id', $task['id'])->update($changes); + Store::refreshBatch($batchId); } - // Attempt history and lifetime counter remain immutable across retry rounds. - Db::name('prescription_ai_task')->where('id', $task['id'])->update([ - 'status' => 'retry_wait', 'attempts' => 0, 'next_run_at' => time(), 'lock_token' => '', - 'manual_retries' => (int) $task['manual_retries'] + 1, - 'lock_until' => 0, 'error_code' => '', 'updated_at' => time(), - ]); - Store::refreshBatch($batchId); - return ['batch_id' => $batchId, 'status' => 'retry_wait']; + return ['batch_id' => $batchId, 'model_key' => $model] + $state; }); } @@ -280,12 +288,54 @@ final class PrescriptionAiLogic 'metric_label' => '药味与剂量一致度(不代表临床准确率)']; } + /** Project the retry response and polled model states from the same task, ledger and attempt history. */ + private static function taskStates(array $tasks, int $now): array + { + $budgetModels = []; + $attemptTaskIds = []; + foreach ($tasks as $task) { + if ($task['status'] !== 'retry_wait') { continue; } + if ($task['error_code'] !== 'BUDGET_PAUSED' || (int) $task['next_run_at'] <= $now) { + $budgetModels[] = $task['model_key']; + } + if ((int) $task['total_attempts'] > 0) { + $attemptTaskIds[] = $task['id']; + } + } + $exhausted = Store::exhaustedModels($budgetModels, $now); + $lastErrors = $attemptTaskIds ? Db::name('prescription_ai_attempt')->alias('a') + ->join('prescription_ai_task t', 't.id = a.task_id AND t.total_attempts = a.attempt_no') + ->whereIn('a.task_id', $attemptTaskIds)->whereIn('a.status', ['failed', 'expired']) + ->column('a.error_code', 'task_id') : []; + $maxRetries = (int) config('prescription_analysis.max_manual_retries', 2); + $states = []; + foreach ($tasks as $task) { + $code = $task['error_code']; + $lastError = $task['status'] === 'failed' ? $code : ($lastErrors[$task['id']] ?? ''); + if ($task['status'] === 'retry_wait') { + if (in_array($task['model_key'], $exhausted, true)) { + $code = 'BUDGET_PAUSED'; + $task['next_run_at'] = max((int) $task['next_run_at'], strtotime('tomorrow', $now)); + } elseif ($code === 'BUDGET_PAUSED' && (int) $task['next_run_at'] <= $now) { + $code = ''; // Yesterday's pause has expired; eligibility still awaits a real claim. + } + } + $task['error_code'] = $code; + $states[] = ['status' => $task['status'], 'error_code' => $code, + 'error_message' => $code !== '' ? Policy::errorMessage($code) : '', + 'last_error_code' => $lastError, 'last_error_message' => $lastError !== '' ? Policy::errorMessage($lastError) : '', + 'manual_retries' => (int) $task['manual_retries'], 'max_manual_retries' => $maxRetries, + 'progress' => Progress::task($task, $now)]; + } + return $states; + } + private static function models(array $batchIds, bool $full, bool $agreementVisible = true): array { if ($batchIds === []) { return []; } - $taskFields = ['batch_id', 'model_key', 'status', 'error_code', 'attempts', 'total_attempts', 'result_id', + $taskFields = ['id', 'batch_id', 'model_key', 'status', 'error_code', 'attempts', 'total_attempts', 'manual_retries', 'result_id', 'started_at', 'finished_at', 'updated_at', 'next_run_at']; if (Store::supportsProgress()) { $taskFields[] = 'progress_json'; @@ -298,14 +348,11 @@ final class PrescriptionAiLogic } $results = Db::name('prescription_ai_result')->whereIn('batch_id', $batchIds)->field($fields)->select()->toArray(); $map = []; - foreach ($tasks as $task) { - $map[(int) $task['batch_id']][$task['model_key']] = [ - 'status' => $task['status'], 'score' => null, 'herb_score' => null, - 'error_code' => $task['error_code'], 'error_message' => $task['error_code'] !== '' ? Policy::errorMessage($task['error_code']) : '', - 'reason' => $task['error_code'] !== '' ? Policy::errorMessage($task['error_code']) : '', - 'report_id' => (int) $task['result_id'], - 'progress' => Progress::task($task), - ]; + $taskStates = self::taskStates($tasks, time()); + foreach ($tasks as $index => $task) { + $state = $taskStates[$index]; + $map[(int) $task['batch_id']][$task['model_key']] = $state + ['score' => null, 'herb_score' => null, + 'reason' => $state['error_message'], 'report_id' => (int) $task['result_id']]; } foreach ($results as $result) { $body = $full ? (new Cipher())->decrypt($result['body_cipher'], 'result:' . $result['batch_id'] . ':' . $result['model_key']) : []; @@ -387,7 +434,17 @@ final class PrescriptionAiLogic if (!Access::sourceIds($ids, $actor, $info) || empty($batch['access_cipher'])) { return false; } - $access = (new Cipher())->decrypt($batch['access_cipher'], 'access:' . $batch['id']); + try { + $access = (new Cipher())->decrypt($batch['access_cipher'], 'access:' . $batch['id']); + } catch (\RuntimeException $e) { + if ($e->getMessage() !== Cipher::INVALID_PAYLOAD) { + throw $e; + } + // An unreadable authorization snapshot cannot establish access to this batch. + Log::warning('Unreadable prescription AI access snapshot: {code} (batch_id={batch_id})', + ['code' => Cipher::INVALID_PAYLOAD, 'batch_id' => (int) $batch['id']]); + return false; + } return \app\common\service\prescriptionai\PrescriptionAiContext::assertSnapshotAccess($access, $actor, $info); } diff --git a/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php b/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php index a8407fcff..7043b62a2 100755 --- a/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php +++ b/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php @@ -3015,7 +3015,8 @@ class PrescriptionOrderLogic $logSummary = $summary; if ($changeParts !== []) { - $logSummary .= '(' . implode(';', $changeParts) . ')'; + $changeSummary = '(' . implode(';', $changeParts) . ')'; + $logSummary = mb_substr($summary, 0, 500 - mb_strlen($changeSummary)) . $changeSummary; } self::writeLog($id, $adminId, $adminInfo, 'manual_log', $logSummary); @@ -4482,26 +4483,30 @@ class PrescriptionOrderLogic } } + $paymentAuditActions = ['audit_pay_approve', 'audit_pay_reject']; + $paymentAuditResetActions = [ + 'revoke_pay_audit', 'audit_rx_reject', 'revoke_rx_audit', 'add_pay_order', 'link_pay_order', 'completion_request', + ]; $logRows = PrescriptionOrderLog::whereIn('prescription_order_id', $poIds) - ->whereIn('action', ['audit_rx_approve', 'audit_rx_reject', 'revoke_rx_audit']) - ->field(['prescription_order_id', 'id', 'action', 'admin_name', 'create_time']) + ->whereIn('action', [...$paymentAuditActions, ...$paymentAuditResetActions, 'manual_log']) + ->field(['prescription_order_id', 'action', 'admin_name', 'create_time', 'summary']) ->order('id', 'asc') ->select() ->toArray(); - $auditEffectiveByPo = []; + $paymentAuditByPo = []; foreach ($logRows as $lg) { - $pid = (int) ($lg['prescription_order_id'] ?? 0); - if ($pid <= 0) { + $pid = (int) $lg['prescription_order_id']; + $action = $lg['action']; + if (in_array($action, $paymentAuditActions, true)) { + $paymentAuditByPo[$pid] = $lg; continue; } - $act = (string) ($lg['action'] ?? ''); - if ($act === 'revoke_rx_audit') { - $auditEffectiveByPo[$pid] = null; + // 手工调整支付审核状态会追加固定格式的变更说明,普通备注不影响已有审核记录。 + if ($action === 'manual_log' + && !preg_match('/[(;]支付单审核:(待审核|已通过|已驳回) → (待审核|已通过|已驳回))$/u', (string) $lg['summary'])) { continue; } - if ($act === 'audit_rx_approve' || $act === 'audit_rx_reject') { - $auditEffectiveByPo[$pid] = $lg; - } + unset($paymentAuditByPo[$pid]); } // 服务套餐字典:与前端 formatServicePackage 同口径(dict_data type_value=server_order;只取启用项做兜底取原值) @@ -4703,16 +4708,18 @@ class PrescriptionOrderLogic $item['export_center_label'] = '一中心'; } - $paSt = (int) ($item['prescription_audit_status'] ?? 0); - $aud = $auditEffectiveByPo[$poId] ?? null; - if (($paSt === 1 || $paSt === 2) && \is_array($aud)) { - $at = (int) ($aud['create_time'] ?? 0); - $item['export_rx_audit_time'] = $at > 0 ? date('Y-m-d H:i:s', $at) : ''; - $item['export_rx_auditor'] = (string) ($aud['admin_name'] ?? ''); - } else { - $item['export_rx_audit_time'] = ''; - $item['export_rx_auditor'] = ''; + $paymentAudit = $paymentAuditByPo[$poId] ?? []; + $expectedAction = match ((int) ($item['payment_slip_audit_status'] ?? 0)) { + 1 => 'audit_pay_approve', + 2 => 'audit_pay_reject', + default => null, + }; + if ($expectedAction === null || ($paymentAudit['action'] ?? null) !== $expectedAction) { + $paymentAudit = []; } + $auditTime = (int) ($paymentAudit['create_time'] ?? 0); + $item['export_payment_audit_time'] = $auditTime > 0 ? date('Y-m-d H:i:s', $auditTime) : ''; + $item['export_payment_auditor'] = (string) ($paymentAudit['admin_name'] ?? ''); } unset($item); } diff --git a/server/app/command/PrescriptionAiDispatch.php b/server/app/command/PrescriptionAiDispatch.php new file mode 100644 index 000000000..af623dd81 --- /dev/null +++ b/server/app/command/PrescriptionAiDispatch.php @@ -0,0 +1,71 @@ +setName('prescription-ai:dispatch')->setDescription('巡检处方 AI 消费者,对缺失的队列派发一轮处理') + ->addOption('check', null, Option::VALUE_NONE, '只输出巡检状态'); + } + + protected function execute(Input $input, Output $output): int + { + $enabled = PrescriptionAiStore::enabled(); + $checkOnly = (bool) $input->getOption('check'); + if (!$enabled && !$checkOnly) { + $output->writeln('PRESCRIPTION_AI_DISPATCH {"enabled":false}'); + return 0; + } + $root = $this->app->getRootPath(); + $think = $root . 'think'; + if (PHP_SAPI !== 'cli' || !is_readable($think)) { + throw new RuntimeException('处方 AI 巡检需要 PHP CLI 和可读的 think 入口'); + } + $present = PHP_OS_FAMILY === 'Linux' ? PrescriptionAiLaneGuard::linuxWorkers($think) : []; + $null = PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null'; + $streams = [['file', $null, 'r'], ['file', $null, 'w'], ['file', $null, 'w']]; + $states = []; + foreach (PrescriptionAiLaneGuard::LANES as $lane) { + if (isset($present[$lane])) { + $states[$lane] = $present[$lane]; + continue; + } + if ($checkOnly) { + $states[$lane] = PrescriptionAiLaneGuard::busy($this->app->getRuntimePath(), $lane) ? 'busy' : 'missing'; + continue; + } + // Surface runtime permission errors in the admin schedule before detaching the worker. + $probe = PrescriptionAiLaneGuard::acquire($this->app->getRuntimePath(), $lane, LOCK_EX | LOCK_NB); + if ($probe === null) { + $states[$lane] = 'busy'; + continue; + } + fclose($probe); + if (!function_exists('proc_open')) { + throw new RuntimeException('处方 AI 单轮接管需要启用 proc_open'); + } + $process = proc_open([PHP_BINARY, $think, 'prescription-ai:work', '--lane=' . $lane, '--once', '--scheduled'], + $streams, $pipes, $root); + if (!is_resource($process)) { + throw new RuntimeException('无法启动处方 AI 消费者 ' . $lane); + } + // proc_close waits for the model. Releasing a pipe-free handle lets the cron runner continue immediately. + unset($process); + $states[$lane] = 'dispatched'; + } + $output->writeln('PRESCRIPTION_AI_DISPATCH ' . json_encode(['enabled' => $enabled, 'lanes' => $states])); + return 0; + } +} diff --git a/server/app/command/PrescriptionAiWork.php b/server/app/command/PrescriptionAiWork.php index a55206399..4600a0613 100755 --- a/server/app/command/PrescriptionAiWork.php +++ b/server/app/command/PrescriptionAiWork.php @@ -4,11 +4,13 @@ declare(strict_types=1); namespace app\command; +use app\common\service\prescriptionai\PrescriptionAiLaneGuard; use app\common\service\prescriptionai\PrescriptionAiStore; use app\common\service\prescriptionai\PrescriptionAiWorker; use think\console\Command; use think\facade\Config; use think\facade\Db; +use think\facade\Log; use think\console\Input; use think\console\input\Option; use think\console\Output; @@ -19,16 +21,26 @@ final class PrescriptionAiWork extends Command { $this->setName('prescription-ai:work')->setDescription('处方AI独立后台任务;分别运行prepare/qwen/openai') ->addOption('lane', null, Option::VALUE_REQUIRED, 'prepare、qwen、openai', 'prepare') - ->addOption('once', null, Option::VALUE_NONE, '只处理一轮'); + ->addOption('once', null, Option::VALUE_NONE, '只处理一轮') + ->addOption('scheduled', null, Option::VALUE_NONE, '定时任务单轮接管,当前队列已占用时跳过'); } protected function execute(Input $input, Output $output): int { $lane = (string) $input->getOption('lane'); - if (!in_array($lane, ['prepare', 'qwen', 'openai'], true)) { + if (!in_array($lane, PrescriptionAiLaneGuard::LANES, true)) { $output->writeln('Invalid lane'); return 1; } + $scheduled = $input->getOption('scheduled'); + if ($scheduled && !$input->getOption('once')) { + $output->writeln('--scheduled requires --once'); + return 1; + } + // This handle stays open until execute() returns. Process exit also releases it after a crash. + $laneLock = PrescriptionAiLaneGuard::acquire($this->app->getRuntimePath(), $lane, + $scheduled ? LOCK_EX | LOCK_NB : LOCK_SH); + if ($laneLock === null) { return 0; } $running = true; if (function_exists('pcntl_async_signals')) { pcntl_async_signals(true); @@ -48,6 +60,11 @@ final class PrescriptionAiWork extends Command $sweepAt = 0; $sourceCursor = 0; $rxCursor = 0; + if ($scheduled && $lane === 'prepare') { + $saved = json_decode((string) stream_get_contents($laneLock), true); + $sourceCursor = (int) ($saved['source'] ?? 0); + $rxCursor = (int) ($saved['prescription'] ?? 0); + } do { $worked = false; try { @@ -60,6 +77,12 @@ final class PrescriptionAiWork extends Command $sourceCursor = $sweep['selected'] > 0 ? $sweep['last_id'] : 0; $rx = $worker->reconcile($rxCursor); $rxCursor = $rx['selected'] > 0 ? $rx['last_id'] : 0; + if ($scheduled) { + rewind($laneLock); + ftruncate($laneLock, 0); + fwrite($laneLock, json_encode(['source' => $sourceCursor, 'prescription' => $rxCursor])); + fflush($laneLock); + } $sweepAt = time() + 60; } } @@ -73,6 +96,9 @@ final class PrescriptionAiWork extends Command $detail .= ' ' . $sqlState[0]; } $output->writeln('PRESCRIPTION_AI storage_or_configuration_error ' . $detail); + if ($scheduled) { + Log::write('PRESCRIPTION_AI ' . $lane . ' storage_or_configuration_error ' . $detail, 'error'); + } // Drop a possibly dead connection so the next round reconnects instead of looping. try { Db::connect()->close(); diff --git a/server/app/common/service/prescriptionai/PrescriptionAiCipher.php b/server/app/common/service/prescriptionai/PrescriptionAiCipher.php index 38d26594b..4b9cfb717 100755 --- a/server/app/common/service/prescriptionai/PrescriptionAiCipher.php +++ b/server/app/common/service/prescriptionai/PrescriptionAiCipher.php @@ -9,6 +9,8 @@ use RuntimeException; /** Authenticated at-rest encryption; key is never stored in the database. */ final class PrescriptionAiCipher { + public const INVALID_PAYLOAD = 'AI_ANALYSIS_CIPHER_INVALID'; + private ?string $secret; public function __construct(?string $secret = null) @@ -32,16 +34,20 @@ final class PrescriptionAiCipher { $bytes = str_starts_with($value, 'v1:') ? base64_decode(substr($value, 3), true) : false; if ($bytes === false || strlen($bytes) < 30) { - throw new RuntimeException('AI_ANALYSIS_CIPHER_INVALID'); + throw new RuntimeException(self::INVALID_PAYLOAD); } $plain = openssl_decrypt(substr($bytes, 28), 'aes-256-gcm', $this->key(), OPENSSL_RAW_DATA, substr($bytes, 0, 12), substr($bytes, 12, 16), $purpose); if ($plain === false) { - throw new RuntimeException('AI_ANALYSIS_CIPHER_INVALID'); + throw new RuntimeException(self::INVALID_PAYLOAD); + } + try { + $decoded = json_decode($plain, true, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new RuntimeException(self::INVALID_PAYLOAD, 0, $e); } - $decoded = json_decode($plain, true, 512, JSON_THROW_ON_ERROR); if (!is_array($decoded)) { - throw new RuntimeException('AI_ANALYSIS_CIPHER_INVALID'); + throw new RuntimeException(self::INVALID_PAYLOAD); } return $decoded; } diff --git a/server/app/common/service/prescriptionai/PrescriptionAiLaneGuard.php b/server/app/common/service/prescriptionai/PrescriptionAiLaneGuard.php new file mode 100644 index 000000000..bb604a133 --- /dev/null +++ b/server/app/common/service/prescriptionai/PrescriptionAiLaneGuard.php @@ -0,0 +1,106 @@ + $argument) { + if (str_starts_with($argument, '--lane=')) { + $lane = substr($argument, 7); + } elseif ($argument === '--lane') { + $lane = $arguments[$index + $offset + 2] ?? ''; + } + } + if (in_array($lane, self::LANES, true)) { + if (!in_array('--once', $arguments, true)) { + $found[$lane] = 'resident'; + } elseif (!isset($found[$lane])) { + $found[$lane] = 'single_run'; + } + if (count(array_keys($found, 'resident', true)) === count(self::LANES)) { break; } + } + } + return $found; + } +} diff --git a/server/app/common/service/prescriptionai/PrescriptionAiProgress.php b/server/app/common/service/prescriptionai/PrescriptionAiProgress.php index 067035a84..867145838 100755 --- a/server/app/common/service/prescriptionai/PrescriptionAiProgress.php +++ b/server/app/common/service/prescriptionai/PrescriptionAiProgress.php @@ -70,9 +70,15 @@ final class PrescriptionAiProgress $result = self::present($meta, $now, self::number($task['started_at'] ?? null), $end); $result['attempt'] = self::number($task['total_attempts'] ?? $task['attempts'] ?? null, 1000000) ?? 0; if ($status === 'retry_wait') { - $result['wait_remaining_seconds'] = self::remaining($task['next_run_at'] ?? null, $now); - $result['notice'] = ($task['error_code'] ?? '') === 'BUDGET_PAUSED' - ? '今日模型任务额度已用完,到时间后自动继续。' : '本次未完成,已安排自动重试。'; + $result['next_run_at'] = self::number($task['next_run_at'] ?? null); + $result['wait_remaining_seconds'] = self::remaining($result['next_run_at'], $now); + if ($result['wait_remaining_seconds'] === 0) { + $result['notice'] = '已到可重试时间,等待后台领取任务。'; + } elseif (($task['error_code'] ?? '') === 'BUDGET_PAUSED' && $result['next_run_at'] > 0) { + $result['notice'] = '今日模型任务额度已用完,最早可于 ' . date('Y-m-d H:i:s', $result['next_run_at']) . '(服务器时间)领取重试。'; + } else { + $result['notice'] = '本次未完成,已安排自动重试。'; + } } if (in_array($status, ['failed', 'retry_wait'], true) && in_array($lastStage, ['text', 'files', 'reduce', 'final', 'validating', 'comparing'], true)) { diff --git a/server/app/common/service/prescriptionai/PrescriptionAiStore.php b/server/app/common/service/prescriptionai/PrescriptionAiStore.php index af806266a..d2617a885 100755 --- a/server/app/common/service/prescriptionai/PrescriptionAiStore.php +++ b/server/app/common/service/prescriptionai/PrescriptionAiStore.php @@ -234,6 +234,24 @@ final class PrescriptionAiStore ]); } + /** Read-only snapshot for retry scheduling. Only a successful claim reserves a daily slot. */ + public static function exhaustedModels(array $models, int $now): array + { + if (!$models) { return []; } + $keys = []; + foreach ($models as $model) { + $keys[date('Y-m-d', $now) . ':' . $model] = $model; + } + $exhausted = Db::name('prescription_ai_limit')->whereIn('limit_key', array_keys($keys)) + ->where('used_count', '>=', self::dailyModelTaskLimit())->column('limit_key'); + return array_map(static fn ($key): string => $keys[$key], $exhausted); + } + + private static function dailyModelTaskLimit(): int + { + return max(1, (int) config('prescription_analysis.daily_model_tasks', 200)); + } + public static function claimTask(string $model): ?array { if (!in_array($model, PrescriptionAiPolicy::MODELS, true)) { @@ -272,7 +290,7 @@ final class PrescriptionAiStore self::refreshBatch((int) $row['batch_id']); return null; } - if ((int) $budget['used_count'] >= max(1, (int) config('prescription_analysis.daily_model_tasks', 200))) { + if ((int) $budget['used_count'] >= self::dailyModelTaskLimit()) { Db::name('prescription_ai_task')->where('id', $id)->update([ 'status' => 'retry_wait', 'error_code' => 'BUDGET_PAUSED', 'next_run_at' => strtotime('tomorrow', $now), 'updated_at' => $now, diff --git a/server/config/console.php b/server/config/console.php index a0c22d588..c0b1c475e 100755 --- a/server/config/console.php +++ b/server/config/console.php @@ -19,6 +19,7 @@ return [ 'followup-audio:probe' => 'app\\command\\FollowupAudioProbe', 'followup-audio:cleanup' => 'app\\command\\FollowupAudioCleanup', 'prescription-ai:work' => 'app\\command\\PrescriptionAiWork', + 'prescription-ai:dispatch' => 'app\\command\\PrescriptionAiDispatch', 'prescription-ai:backfill' => 'app\\command\\PrescriptionAiBackfill', // 定时任务 'crontab' => 'app\common\command\Crontab', diff --git a/server/database/migrations/2026_12_02_prescription_ai_crontab.sql b/server/database/migrations/2026_12_02_prescription_ai_crontab.sql new file mode 100644 index 000000000..ce46baa15 --- /dev/null +++ b/server/database/migrations/2026_12_02_prescription_ai_crontab.sql @@ -0,0 +1,4 @@ +-- 非默认表前缀需替换 zyt_。保留管理员已有的暂停状态和运行周期。 +INSERT INTO `zyt_dev_crontab` (`name`, `type`, `system`, `remark`, `command`, `params`, `status`, `expression`, `last_time`, `create_time`, `update_time`) +SELECT '处方 AI 分析队列', 1, 0, '每分钟巡检资料准备、通义千问和 OpenAI 消费者,只对缺失的队列派发单轮处理', 'prescription-ai:dispatch', '', 1, '* * * * *', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), UNIX_TIMESTAMP() +WHERE NOT EXISTS (SELECT 1 FROM `zyt_dev_crontab` WHERE `command` = 'prescription-ai:dispatch' AND `delete_time` IS NULL); diff --git a/server/public/install/db/like.sql b/server/public/install/db/like.sql index c91d6fc14..40f7bafaf 100755 --- a/server/public/install/db/like.sql +++ b/server/public/install/db/like.sql @@ -243,6 +243,9 @@ CREATE TABLE `la_dev_crontab` ( PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '计划任务表'; +INSERT INTO `la_dev_crontab` (`name`, `type`, `system`, `remark`, `command`, `params`, `status`, `expression`, `last_time`, `create_time`, `update_time`) +VALUES ('处方 AI 分析队列', 1, 0, '每分钟巡检资料准备、通义千问和 OpenAI 消费者,只对缺失的队列派发单轮处理', 'prescription-ai:dispatch', '', 1, '* * * * *', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), UNIX_TIMESTAMP()); + -- ---------------------------- -- Table structure for la_dev_pay_config -- ---------------------------- diff --git a/server/sql/1.9.20261202/01_prescription_ai_crontab.sql b/server/sql/1.9.20261202/01_prescription_ai_crontab.sql new file mode 100644 index 000000000..ce46baa15 --- /dev/null +++ b/server/sql/1.9.20261202/01_prescription_ai_crontab.sql @@ -0,0 +1,4 @@ +-- 非默认表前缀需替换 zyt_。保留管理员已有的暂停状态和运行周期。 +INSERT INTO `zyt_dev_crontab` (`name`, `type`, `system`, `remark`, `command`, `params`, `status`, `expression`, `last_time`, `create_time`, `update_time`) +SELECT '处方 AI 分析队列', 1, 0, '每分钟巡检资料准备、通义千问和 OpenAI 消费者,只对缺失的队列派发单轮处理', 'prescription-ai:dispatch', '', 1, '* * * * *', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), UNIX_TIMESTAMP() +WHERE NOT EXISTS (SELECT 1 FROM `zyt_dev_crontab` WHERE `command` = 'prescription-ai:dispatch' AND `delete_time` IS NULL); diff --git a/server/tests/PrescriptionAiDispatchTest.php b/server/tests/PrescriptionAiDispatchTest.php new file mode 100644 index 000000000..90f2655cb --- /dev/null +++ b/server/tests/PrescriptionAiDispatchTest.php @@ -0,0 +1,158 @@ +instance('config', $config); +$definition = require $server . '/config/console.php'; +$name = 'prescription-ai:dispatch'; +$command = new $definition['commands'][$name](); +$command->setApp($app); +$run = static fn (): int => $command->run(new Input([]), new Output('buffer')); +$lanes = ['prepare', 'qwen', 'openai']; +try { + $config->set(['enabled' => false], 'prescription_analysis'); + dispatchExpect($run() === 0, 'Disabled dispatch must exit before accessing the CLI entry point'); + $config->set(['enabled' => true], 'prescription_analysis'); + try { + $run(); + throw new LogicException('Missing think entry point was reported as a successful dispatch'); + } catch (RuntimeException $expected) { + dispatchExpect(str_contains($expected->getMessage(), 'think'), 'Launch failure should identify the entry point'); + } + file_put_contents($directory . '/think', <<<'PHP' +run(new Input(['--check']), $inspect); + dispatchExpect(substr_count($inspect->fetch(), 'missing') === 3 && !is_dir($app->getRuntimePath()), + 'Check-only inspection must report missing lanes without creating locks or dispatching work'); + $held = []; + foreach ($lanes as $lane) { + $held[$lane] = Guard::acquire($app->getRuntimePath(), $lane, LOCK_SH); + } + $healthy = new Output('buffer'); + dispatchExpect($command->run(new Input([]), $healthy) === 0 && substr_count($healthy->fetch(), 'busy') === 3, + 'Three supervised workers must satisfy the inspection without spawning children'); + $worker = new $definition['commands']['prescription-ai:work'](); + $worker->setApp($app); + $skipped = new Output('buffer'); + dispatchExpect($worker->run(new Input(['--lane=prepare', '--once', '--scheduled']), $skipped) === 0 + && $skipped->fetch() === '', 'Scheduled worker must exit before a database claim or idle sweep when locked'); + foreach ($lanes as $lane) { + dispatchExpect(!is_file($directory . '/' . $lane), 'A healthy lane was dispatched'); + } + fclose($held['openai']); + dispatchExpect($run() === 0, 'A single missing lane must be dispatched'); + $deadline = microtime(true) + 5; + while (!is_file($directory . '/openai') && microtime(true) < $deadline) { usleep(20000); } + dispatchExpect(is_file($directory . '/openai') && !is_file($directory . '/prepare') && !is_file($directory . '/qwen'), + 'Dispatch should only start the missing lane'); + touch($directory . '/release'); + while (!is_file($directory . '/openai.done') && microtime(true) < $deadline) { usleep(20000); } + dispatchExpect(is_file($directory . '/openai.done'), 'Single fallback did not finish'); + if (PHP_OS_FAMILY === 'Linux') { + while (Guard::linuxWorkers($directory . '/think') && microtime(true) < $deadline) { usleep(20000); } + } + unlink($directory . '/openai'); + unlink($directory . '/openai.done'); + unlink($directory . '/release'); + fclose($held['prepare']); + fclose($held['qwen']); + $single = Guard::acquire($app->getRuntimePath(), 'openai', LOCK_EX | LOCK_NB); + dispatchExpect(Guard::acquire($app->getRuntimePath(), 'openai', LOCK_EX | LOCK_NB) === null, + 'Overlapping scheduled consumers must not process the same lane'); + fclose($single); + dispatchExpect($run() === 0, 'Enabled dispatch must succeed'); + touch($directory . '/release'); + $deadline = microtime(true) + 5; + foreach ($lanes as $lane) { + $result = $directory . '/' . $lane; + while (!is_file($result . '.done') && microtime(true) < $deadline) { usleep(20000); } + dispatchExpect(is_file($result . '.done') && file_get_contents($result . '.done') === 'released', + "Dispatch blocked on the {$lane} worker or did not start it"); + dispatchExpect(json_decode(file_get_contents($result), true) === ['prescription-ai:work', '--lane=' . $lane, '--once', '--scheduled'], + "Unexpected {$lane} worker arguments"); + } + + // A relative think path must resolve against the observed process, never the inspector's cwd. + $proc = $directory . '/proc'; + foreach (['self', '101/cwd', '102/cwd'] as $path) { mkdir($proc . '/' . $path, 0700, true); } + touch($proc . '/self/cmdline'); + foreach (['101', '102'] as $id) { + touch($proc . '/' . $id . '/cwd/think'); + file_put_contents($proc . '/' . $id . '/comm', 'php8.2'); + file_put_contents($proc . '/' . $id . '/cmdline', implode("\0", ['php', 'think', 'prescription-ai:work', '--lane=openai'])); + } + $target = $proc . '/101/cwd/think'; + foreach (['prepare' => [], 'qwen' => ['--lane', 'qwen'], 'openai' => ['--lane=openai']] as $lane => $options) { + file_put_contents($proc . '/101/cmdline', implode("\0", array_merge(['php', './think', 'prescription-ai:work'], $options))); + dispatchExpect(Guard::linuxWorkers($target, $proc) === [$lane => 'resident'], + 'Legacy workers must be scoped to this application and exact lane'); + } + file_put_contents($proc . '/101/cmdline', implode("\0", ['php', 'think', 'prescription-ai:work', '--once'])); + dispatchExpect(Guard::linuxWorkers($target, $proc) === ['prepare' => 'single_run'], 'A running fallback must occupy its lane'); + if (PHP_OS_FAMILY === 'Linux') { + file_put_contents($proc . '/101/cmdline', implode("\0", ['/www/server/php/82/bin/php', $target, 'prescription-ai:work', '--lane=qwen'])); + dispatchExpect(Guard::linuxWorkers($target, $proc) === ['qwen' => 'resident'], 'Absolute think path from a supervised process'); + } + + $db = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); + $db->sqliteCreateFunction('UNIX_TIMESTAMP', 'time'); + $db->exec('CREATE TABLE zyt_dev_crontab (name TEXT, type INTEGER, system INTEGER, remark TEXT, command TEXT, + params TEXT, status INTEGER, expression TEXT, last_time INTEGER, create_time INTEGER, update_time INTEGER, delete_time INTEGER)'); + $migration = file_get_contents($server . '/database/migrations/2026_12_02_prescription_ai_crontab.sql'); + $upgrade = file_get_contents($server . '/sql/1.9.20261202/01_prescription_ai_crontab.sql'); + $db->exec($migration); + $db->exec($upgrade); + $select = static fn (): array => $db->query('SELECT name,command,params,status,expression FROM zyt_dev_crontab')->fetchAll(PDO::FETCH_ASSOC); + $fresh = $select(); + dispatchExpect(count($fresh) === 1 && $fresh[0]['command'] === $name && $fresh[0]['params'] === '' + && (int) $fresh[0]['status'] === 1 && $fresh[0]['expression'] === '* * * * *', 'Upgrading must enable one per-minute dispatch'); + $db->exec("UPDATE zyt_dev_crontab SET status = 2, expression = '*/5 * * * *'"); + $edited = $select(); + $db->exec($migration); + $db->exec($upgrade); + dispatchExpect($select() === $edited, 'Repeated upgrades must retain administrator edits'); + $db->exec('DELETE FROM zyt_dev_crontab'); + $install = file_get_contents($server . '/public/install/db/like.sql'); + preg_match('/^INSERT INTO `la_dev_crontab`[^;]+;/m', $install, $match); + dispatchExpect(isset($match[0]), 'Installer must seed the schedule with its configurable prefix'); + $db->exec(str_replace('`la_', '`zyt_', $match[0])); + dispatchExpect($select() === $fresh, 'Installer and upgrade must register the same task'); + echo "Prescription AI dispatch, upgrade and installer checks passed\n"; +} finally { + $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, + FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST); + foreach ($files as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + rmdir($directory); +} diff --git a/server/tests/PrescriptionAiProgressTest.php b/server/tests/PrescriptionAiProgressTest.php index 055e780fe..61127ad4d 100755 --- a/server/tests/PrescriptionAiProgressTest.php +++ b/server/tests/PrescriptionAiProgressTest.php @@ -45,7 +45,9 @@ foreach ($terminalExpected as $status => [$stage, $phase]) { } } $retry = Progress::task(array_replace($task, ['status' => 'retry_wait', 'next_run_at' => $now + 30, 'error_code' => 'BUDGET_PAUSED']), $now); -$expect($retry['wait_remaining_seconds'] === 30 && str_contains($retry['notice'], '额度'), 'retry waiting explains scheduled budget pause'); +$expect($retry['wait_remaining_seconds'] === 30 && $retry['next_run_at'] === $now + 30 + && str_contains($retry['notice'], '额度') && str_contains($retry['notice'], date('Y-m-d H:i:s', $now + 30)), + 'retry waiting explains the absolute budget eligibility time to both old and new clients'); $expect(str_contains($retry['notice'], '上次进度:整理文字资料') && str_contains($retry['notice'], '本次尝试'), 'waiting retries retain a trusted stage description and identify attempt timing'); $finishedFailure = array_replace($task, ['status' => 'failed', 'finished_at' => $now - 20, 'updated_at' => $now - 1]); @@ -54,8 +56,9 @@ $expect(Progress::task($finishedFailure, $now + 1000)['elapsed_seconds'] === 100 $finishedRetry = array_replace($finishedFailure, ['status' => 'retry_wait', 'next_run_at' => $now + 30]); $expect(Progress::task($finishedRetry, $now + 1000)['elapsed_seconds'] === 100, 'scheduled retry backoff does not inflate the previous model attempt duration'); -$expect(Progress::task(array_replace($task, ['status' => 'retry_wait', 'next_run_at' => $now - 30]), $now)['wait_remaining_seconds'] === 0, - 'elapsed retry deadlines do not become negative'); +$due = Progress::task(array_replace($task, ['status' => 'retry_wait', 'next_run_at' => $now - 30]), $now); +$expect($due['wait_remaining_seconds'] === 0 && $due['next_run_at'] === $now - 30 && str_contains($due['notice'], '等待后台领取'), + 'elapsed retry deadlines retain the measured eligibility time and wait for a real claim'); foreach ([null, '{}', str_repeat('x', 3000), '{invalid', json_encode(['stage' => 'completed', 'phase' => 'completed'])] as $old) { $result = Progress::task(array_replace($task, ['progress_json' => $old]), $now); $expect($result['stage'] === 'unknown' && $result['phase'] === 'running' && $result['stage_elapsed_seconds'] === null, diff --git a/server/tests/PrescriptionAiQueueTest.php b/server/tests/PrescriptionAiQueueTest.php index a03345f59..0fe9865cd 100755 --- a/server/tests/PrescriptionAiQueueTest.php +++ b/server/tests/PrescriptionAiQueueTest.php @@ -41,6 +41,7 @@ $manager->setConfig(['default' => 'mysql', 'auto_timestamp' => true, 'datetime_f 'prefix' => 'zyt_', 'fields_strict' => true]]]); Container::getInstance()->instance('think\DbManager', $manager); $config = new think\Config(); +$config->set(['default' => 'file', 'channels' => ['file' => ['type' => 'File', 'close' => true]]], 'log'); $config->set(['enabled' => true, 'encryption_key' => str_repeat('isolated-test-', 4), 'debounce_seconds' => 0, 'lease_seconds' => 600, 'max_attempts' => 3, 'max_manual_retries' => 2, 'max_parallel_per_model' => 1, 'daily_model_tasks' => 200, 'transcript_wait_seconds' => 300], 'prescription_analysis'); @@ -299,6 +300,31 @@ try { $statuses = Api::statuses([$rx['id']], 1, $root); $expect($statuses['items'][0]['models']['qwen']['score'] === 80.0, 'list returns persisted numeric score'); $expect($statuses['items'][0]['models']['openai']['score'] === null, 'failed score is null rather than zero'); + Db::startTrans(); + $testKey = $config->get('prescription_analysis.encryption_key'); + try { + $damagedRx = $fixture(); + $damagedBatch = $save($damagedRx); + // A valid ciphertext authenticated for a different batch must fail verification. + Db::name('prescription_ai_batch')->where('id', $damagedBatch)->update([ + 'source_diagnosis_ids_json' => '[1]', 'access_cipher' => $stored['access_cipher'], + ]); + $mixed = Api::statuses([$damagedRx['id'], $rx['id']], 1, $root); + $expect(array_column($mixed['items'], 'prescription_id') === [(int) $rx['id']] + && $mixed['items'][0]['models']['qwen']['score'] === 80.0, + 'unreadable access snapshot is omitted and the healthy score is preserved'); + + $config->set(['encryption_key' => 'too-short'], 'prescription_analysis'); + try { + Api::statuses([$rx['id']], 1, $root); + $expect(false, 'invalid installation key must surface'); + } catch (RuntimeException $e) { + $expect($e->getMessage() === 'AI_ANALYSIS_KEY_INVALID', 'systemic key failure propagates from statuses'); + } + } finally { + $config->set(['encryption_key' => $testKey], 'prescription_analysis'); + Db::rollback(); + } $detail = Api::detail($batchId, 1, $root); $expect($detail['models']['qwen']['report']['summary'] === 'synthetic report', 'authorized detail decrypts'); $expect($detail['models']['qwen']['progress']['stage'] === 'completed' @@ -344,6 +370,45 @@ try { && $hiddenDetail['models']['openai']['reason'] !== '', 'hidden metric preserves report, candidate, original, review and failure explanation'); $denied(static fn () => Api::statistics([], 1, $root), 'root without selected grant cannot read agreement statistics'); Api::review($batchId, 'qwen', 'not_adopted', 'test comment', 1, $root); + Db::startTrans(); + try { + $dailyKey = date('Y-m-d') . ':openai'; + $budget = static fn () => Db::name('prescription_ai_limit')->where('limit_key', $dailyKey); + $retryTask = static fn () => Db::name('prescription_ai_task')->where('id', $o['id']); + $budget()->update(['used_count' => 200]); + $paused = Api::retry($batchId, 'openai', 1, $root); + $deadline = strtotime('tomorrow', $paused['progress']['server_time']); + $expect($paused['status'] === 'retry_wait' && $paused['error_code'] === 'BUDGET_PAUSED' + && $paused['progress']['next_run_at'] === $deadline && $paused['progress']['wait_remaining_seconds'] > 0 + && $paused['manual_retries'] === 1 && $paused['max_manual_retries'] === 2 + && $paused['last_error_code'] === 'UPSTREAM_TIMEOUT' && $paused['last_error_message'] !== '', + 'manual retry acknowledges the real daily budget and preserves the previous attempt cause before any worker poll'); + $expect((int) $retryTask()->value('next_run_at') === $deadline && (int) $budget()->value('used_count') === 200 + && Store::claimTask('openai') === null && Api::retry($batchId, 'openai', 1, $root)['manual_retries'] === 1, + 'deferred manual round is persisted once without reserving or bypassing a model slot'); + // This is the shape already stored by older versions before their first post-retry worker scan. + $retryTask()->update(['next_run_at' => time() - 5, 'error_code' => '']); + $beforePoll = Api::detail($batchId, 1, $root); + $waiting = $beforePoll['models']['openai']; + $expect($waiting['error_code'] === 'BUDGET_PAUSED' && $waiting['progress']['next_run_at'] === $deadline + && $waiting['last_error_code'] === 'UPSTREAM_TIMEOUT' && $beforePoll['models']['qwen']['status'] === 'success' + && !isset($beforePoll['models']['qwen']['score']) && $retryTask()->value('error_code') === '', + 'polled legacy retry shows the current budget without writes, has independent model states and preserves metric visibility'); + $expect(Store::claimTask('openai') === null && $retryTask()->value('error_code') === 'BUDGET_PAUSED' + && (int) $retryTask()->value('total_attempts') === 1, 'worker enforces the same ledger even for legacy due retries'); + // Simulate the next budget window with an elapsed deadline. + $budget()->update(['used_count' => 0]); + $retryTask()->update(['next_run_at' => time() - 10]); + $eligible = Api::detail($batchId, 1, $root)['models']['openai']; + $expect($eligible['error_code'] === '' && $eligible['progress']['wait_remaining_seconds'] === 0 + && str_contains($eligible['progress']['notice'], '等待后台领取') && $eligible['last_error_code'] === 'UPSTREAM_TIMEOUT', + 'past budget pause waits for a real claim without continuing to report yesterday\'s exhaustion'); + $resumed = Store::claimTask('openai'); + $expect((int) $resumed['total_attempts'] === 2 && (int) $budget()->value('used_count') === 1, + 'worker resumes after reset and charges one attempt'); + } finally { + Db::rollback(); + } $expect(Api::retry($batchId, 'openai', 1, $root)['status'] === 'retry_wait', 'agreement restriction does not remove independent report review/retry permission'); Visibility::setConfig(['role_ids' => [], 'admin_ids' => [1]], 1);