From ebc77dce0b22ca90061c0506c655027fa1c5a267 Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 4 Dec 2026 13:33:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/src/doctor_workstation/ui/fullscreen.py | 153 + .../ui/pages/prescriptions.py | 163 +- .../doctor_workstation/ui/spatial_wings.py | 176 +- app/src/doctor_workstation/ui/theme.py | 65 +- app/src/doctor_workstation/video/window.py | 32 + app/tests/test_issued_prescription_ai.py | 3934 +++++++++-------- app/tests/test_window_fullscreen.py | 245 + 7 files changed, 2807 insertions(+), 1961 deletions(-) create mode 100644 app/src/doctor_workstation/ui/fullscreen.py create mode 100644 app/tests/test_window_fullscreen.py diff --git a/app/src/doctor_workstation/ui/fullscreen.py b/app/src/doctor_workstation/ui/fullscreen.py new file mode 100644 index 000000000..7af777a86 --- /dev/null +++ b/app/src/doctor_workstation/ui/fullscreen.py @@ -0,0 +1,153 @@ +"""独立窗口统一全屏控制器。 + +为所有可从主工作台弹出的独立窗口提供一致的全屏体验: + +* ``F11`` 切换全屏 / 退出全屏; +* 全屏状态下 ``Esc`` 只负责退出全屏(非全屏时不拦截,窗口原有的 Esc 关闭/取消照旧); +* 退出全屏后恢复进入前的几何位置与最大化状态。 + +伴随视窗(左翼 / 右翼 / 独立副窗)的全屏由 ``SpatialWingManager`` 负责, +因为它还要额外恢复停靠方位与停靠模式;其余顶层窗口统一通过 +:func:`install_window_fullscreen` 挂载本控制器。 +""" + +from __future__ import annotations + +from PySide6.QtCore import QEvent, QObject, QRect, Qt, Signal +from PySide6.QtGui import QKeySequence, QShortcut +from PySide6.QtWidgets import QWidget + +FULLSCREEN_ENTER_TEXT = "全屏" +FULLSCREEN_EXIT_TEXT = "退出全屏" +FULLSCREEN_ENTER_TIP = "全屏查看(F11)" +FULLSCREEN_EXIT_TIP = "退出全屏,恢复原窗口位置(F11 / Esc)" + +_CONTROLLER_ATTR = "_doctor_fullscreen_controller" + + +def fullscreen_button_text(active: bool) -> str: + """全屏按钮文案:全屏中显示“退出全屏”,否则显示“全屏”。""" + + return FULLSCREEN_EXIT_TEXT if active else FULLSCREEN_ENTER_TEXT + + +def fullscreen_button_tip(active: bool) -> str: + return FULLSCREEN_EXIT_TIP if active else FULLSCREEN_ENTER_TIP + + +class WindowFullscreenController(QObject): + """为单个顶层窗口提供全屏切换、快捷键与几何恢复。""" + + toggled = Signal(bool) + + def __init__(self, window: QWidget) -> None: + super().__init__(window) + self._window = window + self._saved_geometry: QRect | None = None + self._saved_maximized = False + self._last_state = window.isFullScreen() + + self.toggle_shortcut = QShortcut(QKeySequence(Qt.Key.Key_F11), window) + self.toggle_shortcut.setContext(Qt.ShortcutContext.WindowShortcut) + self.toggle_shortcut.activated.connect(self.toggle) + + # 仅在全屏时启用,避免抢占窗口原有的 Esc 取消/关闭行为。 + self.escape_shortcut = QShortcut(QKeySequence(Qt.Key.Key_Escape), window) + self.escape_shortcut.setContext(Qt.ShortcutContext.WindowShortcut) + self.escape_shortcut.activated.connect(self.exit) + + window.installEventFilter(self) + self._sync_shortcuts() + + @property + def window(self) -> QWidget: + return self._window + + @property + def is_fullscreen(self) -> bool: + return self._window.isFullScreen() + + @property + def saved_geometry(self) -> QRect | None: + return QRect(self._saved_geometry) if self._saved_geometry is not None else None + + def toggle(self) -> None: + if self.is_fullscreen: + self.exit() + else: + self.enter() + + def enter(self) -> None: + window = self._window + # 被嵌入伴随视窗等非顶层场景时,全屏交由宿主处理。 + if not window.isWindow() or window.isFullScreen(): + return + self._saved_maximized = window.isMaximized() + self._saved_geometry = QRect( + window.normalGeometry() if self._saved_maximized else window.geometry() + ) + window.showFullScreen() + window.raise_() + self._emit_if_changed() + + def exit(self) -> None: + window = self._window + if not window.isFullScreen(): + return + if self._saved_maximized: + window.showMaximized() + else: + window.showNormal() + if self._saved_geometry is not None and self._saved_geometry.isValid(): + window.setGeometry(self._saved_geometry) + self._saved_geometry = None + self._saved_maximized = False + self._emit_if_changed() + + def _sync_shortcuts(self) -> None: + is_window = self._window.isWindow() + self.toggle_shortcut.setEnabled(is_window) + self.escape_shortcut.setEnabled(is_window and self._window.isFullScreen()) + + def _emit_if_changed(self) -> None: + self._sync_shortcuts() + state = self._window.isFullScreen() + if state != self._last_state: + self._last_state = state + self.toggled.emit(state) + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt virtual + if watched is self._window and event.type() in { + QEvent.Type.WindowStateChange, + QEvent.Type.ParentChange, + QEvent.Type.Show, + }: + self._emit_if_changed() + return False + + +def install_window_fullscreen(window: QWidget) -> WindowFullscreenController: + """为顶层窗口挂载(幂等)全屏控制器并返回它。""" + + existing = getattr(window, _CONTROLLER_ATTR, None) + if isinstance(existing, WindowFullscreenController): + return existing + controller = WindowFullscreenController(window) + setattr(window, _CONTROLLER_ATTR, controller) + return controller + + +def window_fullscreen_controller(window: QWidget) -> WindowFullscreenController | None: + controller = getattr(window, _CONTROLLER_ATTR, None) + return controller if isinstance(controller, WindowFullscreenController) else None + + +__all__ = [ + "FULLSCREEN_ENTER_TEXT", + "FULLSCREEN_EXIT_TEXT", + "WindowFullscreenController", + "fullscreen_button_text", + "fullscreen_button_tip", + "install_window_fullscreen", + "window_fullscreen_controller", +] diff --git a/app/src/doctor_workstation/ui/pages/prescriptions.py b/app/src/doctor_workstation/ui/pages/prescriptions.py index 88c5011eb..44b74acd0 100755 --- a/app/src/doctor_workstation/ui/pages/prescriptions.py +++ b/app/src/doctor_workstation/ui/pages/prescriptions.py @@ -262,6 +262,8 @@ def _painted_icon(kind: str, color: str = "accent", size: int = 16) -> QIcon: # ``UserRole`` on every column, so the delegate reads its own data from offsets # above it. _ROLE_TAG_KIND = Qt.ItemDataRole.UserRole + 10 +# AI 两列无数据时只绘制的灰色占位提示;DisplayRole 保持为空,点击/复制仍按“无数据”处理。 +_ROLE_AI_PLACEHOLDER = Qt.ItemDataRole.UserRole + 11 _ROLE_AVATAR = Qt.ItemDataRole.UserRole + 11 _ROLE_LEAD_ICON = Qt.ItemDataRole.UserRole + 12 @@ -963,6 +965,11 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate): painter.setPen(QColor(foreground)) painter.drawText(pill, Qt.AlignmentFlag.AlignCenter, label) elif column != 2: + if not text and column in (11, 12): + text = str(index.data(_ROLE_AI_PLACEHOLDER) or "") + font.setPixelSize(13) + painter.setFont(font) + painter.setPen(QColor(PALETTE["disabled"])) 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] @@ -1230,6 +1237,75 @@ class _PrescriptionBlueTable(SortableTable): button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"])) +class _TableHeightGrip(QWidget): + """列表底部的拖拽条:向下拖把处方列表拉高(页面随之滚动),双击恢复自适应高度。""" + + def __init__(self, card: QWidget, scroll: QScrollArea, minimum: int) -> None: + super().__init__(card) + self._card = card + self._scroll = scroll + self._minimum = minimum + self._dragging = False + self.setObjectName("PrescriptionTableHeightGrip") + self.setFixedHeight(10) + self.setCursor(Qt.CursorShape.SizeVerCursor) + self.setToolTip("拖动调整处方列表高度,双击恢复默认") + self.setAccessibleName("调整处方列表高度") + scroll.verticalScrollBar().rangeChanged.connect(self._follow_drag) + + def paintEvent(self, _event: Any) -> None: # noqa: N802 + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(PALETTE["accent"] if self._dragging or self.underMouse() else PALETTE["disabled"])) + painter.drawRoundedRect(QRectF(self.width() / 2 - 20, self.height() / 2 - 1.5, 40, 3), 1.5, 1.5) + + def enterEvent(self, event: Any) -> None: # noqa: N802 + self.update() + super().enterEvent(event) + + def leaveEvent(self, event: Any) -> None: # noqa: N802 + self.update() + super().leaveEvent(event) + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + self._dragging = True + self.update() + event.accept() + return + super().mousePressEvent(event) + + def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if not self._dragging: + super().mouseMoveEvent(event) + return + # 以卡片顶边为基准换算,页面滚动后拖拽条仍跟随鼠标。 + bottom = self._card.mapFromGlobal(event.globalPosition().toPoint()).y() + self.height() // 2 + self._card.setMinimumHeight(max(self._minimum, bottom)) + event.accept() + + def _follow_drag(self, *_args: Any) -> None: + # 卡片变高后滚动范围才会更新,此时把拖拽条滚入视野,鼠标继续向下拖即可持续拉高。 + if self._dragging: + self._scroll.ensureWidgetVisible(self, 0, 4) + + def mouseReleaseEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if self._dragging and event.button() == Qt.MouseButton.LeftButton: + self._dragging = False + self.update() + event.accept() + return + super().mouseReleaseEvent(event) + + def mouseDoubleClickEvent(self, event: QMouseEvent) -> None: # noqa: N802 + if event.button() == Qt.MouseButton.LeftButton: + self._card.setMinimumHeight(self._minimum) + event.accept() + return + super().mouseDoubleClickEvent(event) + + class PrescriptionsPage(QWidget): """Complete issued-prescription route: list, workflow actions, print, and orders.""" @@ -1262,7 +1338,10 @@ class PrescriptionsPage(QWidget): self._mutation_pending = False self._audit_check_pending = False self._ai_statuses: dict[int, dict[str, Any]] = {} + self._ai_stale: set[int] = set() self._ai_enabled = False + self._ai_off_hint = "" # AI 未启用时单元格显示的原因;空串表示尚未查询完成 + self._ai_error_streak = 0 # 状态请求连续失败次数,用于区分偶发失败与服务不可用 self._agreement_visible = False self._capability_agreement_visible = False self._ai_capability_token = 0 @@ -1590,6 +1669,8 @@ class PrescriptionsPage(QWidget): self.stack.widget(1).layout().itemAt(0).setAlignment(Qt.AlignmentFlag.AlignHCenter) layout.addWidget(self.stack, 1) layout.addWidget(self.pager) + self.table_height_grip = _TableHeightGrip(card, self.scroll, card.minimumHeight()) + layout.addWidget(self.table_height_grip) return card def resizeEvent(self, event: Any) -> None: @@ -1725,7 +1806,8 @@ class PrescriptionsPage(QWidget): self._ai_timer.stop() self._ai_request_token += 1 self._ai_pending = False - self._ai_statuses.clear() + # 刷新时不清空 AI 缓存(否则整列先闪空再回来),只标记过期,重新查询后替换。 + self._ai_stale = set(self._ai_statuses) self._loading = True self._refresh_pending = False self._generation += 1 @@ -1876,7 +1958,9 @@ class PrescriptionsPage(QWidget): actions_host, ) ) - if self._ai_enabled and self._can_view_ai_report(row): + # 与工具栏“AI 报告”同一判定:未启用自动分析时仍可查看历史报告, + # 按钮不随状态接口的成败出现/消失。 + if self._can_view_ai_report(row): actions.addWidget( _row_action_button( "eye", "AI 报告", @@ -1946,7 +2030,7 @@ class PrescriptionsPage(QWidget): self._sync_row_mutation_actions() self.table.resizeRowsToContents() - def _visible_ai_ids(self) -> list[int]: + def _visible_ai_ids(self, *, visible_only: bool = True) -> list[int]: if not self.isVisible() or not self.table.isVisible(): return [] ids = [] @@ -1955,7 +2039,7 @@ class PrescriptionsPage(QWidget): item = self.table.item(index, 0) # Column 0 may be horizontally off-screen; use row geometry only. top = self.table.rowViewportPosition(index) - if item is None or top + self.table.rowHeight(index) <= 0 or top >= viewport.height(): + if item is None or (visible_only and (top + self.table.rowHeight(index) <= 0 or top >= viewport.height())): continue row = item.data(Qt.ItemDataRole.UserRole) if _is_blank_prescription(row): @@ -1963,7 +2047,24 @@ class PrescriptionsPage(QWidget): value = _int(first_value(row, "id", "prescription_id"), 0) if value > 0: ids.append(value) - return list(dict.fromkeys(ids))[:100] + ids = list(dict.fromkeys(ids)) + return ids[:100] if visible_only else ids + + def _wanted_ai_ids(self) -> list[int]: + """可见行优先(含仍在分析中的行),其余已加载但从未查询过的行随后补齐。 + + 只查可见行时,快速下拉越过的行和恰好压在视口边缘的行永远拿不到状态, + 看起来就像“一滑动 AI 结果就没了”。 + """ + visible = [value for value in self._visible_ai_ids() + if self._needs_ai_status(value) or batch_running(self._ai_statuses[value])] + rest = [value for value in self._visible_ai_ids(visible_only=False) + if self._needs_ai_status(value) and value not in visible] + return (visible + rest)[:100] + + def _needs_ai_status(self, value: int) -> bool: + # 过期的缓存(刷新或重新授权后)继续显示,直到新结果到达再替换。 + return value not in self._ai_statuses or value in self._ai_stale def _schedule_ai_statuses(self) -> None: if self.isVisible(): @@ -1981,17 +2082,18 @@ class PrescriptionsPage(QWidget): return method = getattr(self.repository, "list_prescription_ai_statuses", None) if not has_permission(self.permissions, "tcm.prescriptionAi/statuses", default=False): + self._ai_off_hint = "无权查看" self._set_ai_enabled(False) self.ai_status_notice.setText("AI 分析:当前账号没有查看分析状态的权限,请联系管理员授权。") return if not callable(method): + self._ai_off_hint = "暂不支持" self._set_ai_enabled(False) self.ai_status_notice.setText("AI 分析:当前数据模式暂不支持此功能。") return if self._ai_pending: return - ids = self._visible_ai_ids() - ids = [value for value in ids if value not in self._ai_statuses or batch_running(self._ai_statuses[value])] + ids = self._wanted_ai_ids() if not ids: self._ai_timer.stop() if self.table.rowCount() == 0: @@ -2012,13 +2114,10 @@ class PrescriptionsPage(QWidget): self._ai_pending = False def _set_ai_enabled(self, enabled: bool) -> None: - changed = enabled != self._ai_enabled self._ai_enabled = enabled 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 @@ -2034,11 +2133,12 @@ class PrescriptionsPage(QWidget): token, generation = self._ai_capability_token, self._generation self._ai_request_token += 1 self._ai_pending = False - self._capability_agreement_visible = False - self._set_agreement_visible(False) + # 不在请求前先隐藏一致度:旧值保留到权限结果返回,拒绝时再统一剥离,避免每次刷新/切回页面整列闪空。 method = getattr(self.repository, "get_prescription_ai_capabilities", None) self._ai_capability_pending = callable(method) if not callable(method): + self._capability_agreement_visible = False + self._set_agreement_visible(False) return run_async(method, on_success=lambda result: self._ai_capabilities_ready(result, token, generation), @@ -2052,8 +2152,9 @@ class PrescriptionsPage(QWidget): self._set_agreement_visible(self._capability_agreement_visible) if self._capability_agreement_visible: # A previous deny discarded scores, including completed cached batches. - # Fetch them again after a fresh grant rather than displaying that cache. - self._ai_statuses.clear() + # Fetch them again after a fresh grant; keep showing the (already + # stripped) cache meanwhile instead of blanking every row. + self._ai_stale = set(self._ai_statuses) if self.isVisible() and not self._loading: self._load_ai_statuses() @@ -2062,6 +2163,8 @@ class PrescriptionsPage(QWidget): return data = _row_mapping(result) self._set_agreement_visible(self._capability_agreement_visible and data.get("agreement_visible") is True) + self._ai_off_hint = "未启用" + self._ai_error_streak = 0 self._set_ai_enabled(data.get("enabled") is True) if not self._ai_enabled: self._ai_timer.stop() @@ -2079,6 +2182,7 @@ class PrescriptionsPage(QWidget): + ("可查看逐味对照。" if self._agreement_visible else "")) for value in ids: self._ai_statuses[value] = {} + self._ai_stale.discard(value) for batch in data.get("items") or []: value = _int(get_value(batch, "prescription_id"), 0) if value in ids: @@ -2088,6 +2192,21 @@ class PrescriptionsPage(QWidget): self._ai_timer.start() else: self._ai_timer.stop() + if any(self._needs_ai_status(value) for value in self._visible_ai_ids(visible_only=False)): + # 单次最多 100 条;请求期间新加载/滚入的行接着补查,不等下一次滚动。 + self._ai_scroll_timer.start() + + def _ai_placeholder(self, row: Any, batch: Any) -> str: + """AI 列无结果时的简短灰色提示,避免空白单元格看起来“飘”。""" + if _is_blank_prescription(row): + return "空白处方" + if not self._ai_enabled: + return self._ai_off_hint or "加载中…" + if not self._agreement_visible: + return "无权查看" + if batch is None: + return "加载中…" + return "暂无分析" def _render_ai_statuses(self) -> None: sorting = self.table.isSortingEnabled() @@ -2099,6 +2218,7 @@ class PrescriptionsPage(QWidget): value = _int(first_value(row, "id", "prescription_id"), 0) batch = self._ai_statuses.get(value) state = agreement = tooltip = "" + hint = self._ai_placeholder(row, batch) 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) @@ -2110,8 +2230,11 @@ class PrescriptionsPage(QWidget): if item.text() != text: item.setText(text) changed = True - item.setToolTip(tooltip if text else "") - item.setData(Qt.ItemDataRole.AccessibleTextRole, text) + # 原因只在“AI 分析”列提示一次;一致度列有状态无分数时说明原因,否则显示灰色破折号。 + placeholder = "" if text else hint if column == 11 else "暂无一致度" if state else "—" + item.setData(_ROLE_AI_PLACEHOLDER, placeholder) + item.setToolTip(tooltip if text else "" if placeholder == "—" else placeholder) + item.setData(Qt.ItemDataRole.AccessibleTextRole, text or ("" if placeholder == "—" else placeholder)) if changed: self.table.resizeRowsToContents() finally: @@ -2120,7 +2243,15 @@ class PrescriptionsPage(QWidget): def _ai_statuses_error(self, error: Exception, token: int, generation: int) -> None: if token == self._ai_request_token and generation == self._generation: self._ai_timer.stop() + self._ai_error_streak += 1 + if self._ai_enabled and self._ai_error_streak <= 3: + # 已有结果时,下拉补查失败只是暂时的:保留已显示的分析与按钮,稍后自动重试, + # 不能因为一次失败就把整列清空。连续失败多次才按“暂不可用”处理。 + self.ai_status_notice.setToolTip("部分处方的 AI 状态加载失败,正在自动重试:" + friendly_error(error)) + self._ai_timer.start() + return self._set_agreement_visible(False) + self._ai_off_hint = "暂不可用" self._set_ai_enabled(False) self.ai_status_notice.setText("AI 分析暂不可用:请稍后刷新;持续无法使用时,请联系管理员检查服务。") self.ai_status_notice.setToolTip(friendly_error(error)) diff --git a/app/src/doctor_workstation/ui/spatial_wings.py b/app/src/doctor_workstation/ui/spatial_wings.py index c585160aa..4ebe17ade 100644 --- a/app/src/doctor_workstation/ui/spatial_wings.py +++ b/app/src/doctor_workstation/ui/spatial_wings.py @@ -63,6 +63,7 @@ from PySide6.QtWidgets import ( ) from . import icons, motion +from .fullscreen import fullscreen_button_text, fullscreen_button_tip from .reception_style import body_family, heading_family SPATIAL_WING_QSS = """ @@ -129,6 +130,28 @@ QPushButton#SpatialWingDetachBtn:hover { border-color: #0E6F5C; color: #FFFFFF; } +QPushButton#SpatialWingFullscreenBtn { + min-width: 40px; + min-height: 26px; + max-height: 26px; + padding: 0 9px; + border-radius: 13px; + border: 1px solid #DCE7E4; + background-color: #FFFFFF; + color: #4D6561; + font-size: 11px; + font-weight: 600; +} +QPushButton#SpatialWingFullscreenBtn:hover { + background-color: #E7F4F0; + border-color: #9ED0C3; + color: #0E6F5C; +} +QPushButton#SpatialWingFullscreenBtn:checked { + background-color: #0E6F5C; + border-color: #0E6F5C; + color: #FFFFFF; +} QPushButton#SpatialWingCloseBtn { min-width: 28px; max-width: 28px; @@ -220,6 +243,7 @@ class _WingHeaderBar(QFrame): side_requested = Signal(str) mode_toggle_requested = Signal() + fullscreen_requested = Signal() close_requested = Signal() manual_drag_started = Signal() @@ -280,6 +304,15 @@ class _WingHeaderBar(QFrame): self.detach_btn.clicked.connect(self.mode_toggle_requested.emit) layout.addWidget(self.detach_btn) + # 全屏查看:铺满当前屏幕,退出后恢复原停靠方位、模式与窗口位置。 + self.fullscreen_btn = QPushButton(fullscreen_button_text(False), self) + self.fullscreen_btn.setObjectName("SpatialWingFullscreenBtn") + self.fullscreen_btn.setCheckable(True) + self.fullscreen_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self.fullscreen_btn.setToolTip(fullscreen_button_tip(False)) + self.fullscreen_btn.clicked.connect(self._on_fullscreen_clicked) + layout.addWidget(self.fullscreen_btn) + self.close_btn = QPushButton("×", self) self.close_btn.setObjectName("SpatialWingCloseBtn") self.close_btn.setCursor(Qt.CursorShape.PointingHandCursor) @@ -287,6 +320,16 @@ class _WingHeaderBar(QFrame): self.close_btn.clicked.connect(self.close_requested.emit) layout.addWidget(self.close_btn) + def _on_fullscreen_clicked(self) -> None: + # 勾选态由管理器回写,避免点击后与真实全屏状态不一致。 + self.fullscreen_btn.setChecked(not self.fullscreen_btn.isChecked()) + self.fullscreen_requested.emit() + + def set_fullscreen(self, active: bool) -> None: + self.fullscreen_btn.setChecked(active) + self.fullscreen_btn.setText(fullscreen_button_text(active)) + self.fullscreen_btn.setToolTip(fullscreen_button_tip(active)) + def set_metadata( self, *, @@ -295,7 +338,9 @@ class _WingHeaderBar(QFrame): icon_kind: str = "ai", side: str = "right", mode: str = "docked", + fullscreen: bool = False, ) -> None: + self.set_fullscreen(fullscreen) self.icon_badge.setPixmap(icons.icon(icon_kind, "#0E6F5C", 15).pixmap(15, 15)) resolved_title = title or "伴随工作视窗" self.title_label.setText(resolved_title) @@ -321,7 +366,11 @@ class _WingHeaderBar(QFrame): def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 if event.button() == Qt.MouseButton.LeftButton: win = self.window() - if win is not None and getattr(win, "_is_companion_sidecar", False): + if ( + win is not None + and getattr(win, "_is_companion_sidecar", False) + and not win.isFullScreen() + ): child = self.childAt(event.position().toPoint()) if child is None or isinstance(child, QLabel): handle = win.windowHandle() @@ -476,7 +525,8 @@ class CompanionSidecarWindow(QWidget): self._arrival_anim.valueChanged.connect(self._on_arrival_tick) self._arrival_anim.finished.connect(self._on_arrival_done) - QShortcut(QKeySequence("Esc"), self, activated=self._emit_escape) + # Esc 由挂载其中的 SpatialWingCard 统一处理(全屏时先退出全屏,否则关闭视窗), + # 这里不再重复注册,避免同一窗口内两个 Esc 快捷键互相冲突而都不触发。 def animate_arrival(self, target_rect: QRect, *, side: str) -> None: self._arrival_anim.stop() @@ -537,7 +587,7 @@ class CompanionSidecarWindow(QWidget): return edges def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - if event.button() == Qt.MouseButton.LeftButton: + if event.button() == Qt.MouseButton.LeftButton and not self.isFullScreen(): edges = self._edges(event.position()) handle = self.windowHandle() if edges and handle is not None and handle.startSystemResize(edges): @@ -600,6 +650,7 @@ class SpatialWingManager(QObject): self._right_layout.addWidget(self.card, 1) self.card.header.side_requested.connect(self.set_side) self.card.header.mode_toggle_requested.connect(self.toggle_mode) + self.card.header.fullscreen_requested.connect(self.toggle_fullscreen) self.card.header.close_requested.connect(self.close_wing) self._side = "right" # "left" | "right" @@ -616,9 +667,22 @@ class SpatialWingManager(QObject): self._sidecar: CompanionSidecarWindow | None = None self._saved_shell_geom: tuple[bool, QRect, QSize] | None = None self._syncing_geometry = False + # 全屏前的停靠模式、方位与独立副窗几何;为 None 表示当前未全屏。 + self._fullscreen_restore: tuple[str, str, QRect | None] | None = None self.shell.installEventFilter(self) - QShortcut(QKeySequence("Esc"), self.card, activated=self.close_wing) + QShortcut(QKeySequence("Esc"), self.card, activated=self._on_escape) + # F11 仅在焦点位于伴随视窗内时生效,不影响主工作台。 + f11 = QShortcut(QKeySequence(Qt.Key.Key_F11), self.card, activated=self.toggle_fullscreen) + f11.setContext(Qt.ShortcutContext.WidgetWithChildrenShortcut) + + @property + def is_fullscreen(self) -> bool: + return self._fullscreen_restore is not None + + @property + def sidecar(self) -> CompanionSidecarWindow | None: + return self._sidecar @property def is_open(self) -> bool: @@ -638,7 +702,10 @@ class SpatialWingManager(QObject): def set_side(self, side: str) -> None: normalized = "left" if str(side).strip().lower() == "left" else "right" + # 全屏时点左翼/右翼:先退出全屏恢复原状,再按新方位停靠。 + self.exit_fullscreen() if normalized == self._side and self.is_open: + self._sync_header() return self._side = normalized if self.is_open: @@ -646,7 +713,9 @@ class SpatialWingManager(QObject): def set_mode(self, mode: str) -> None: normalized = "sidecar" if str(mode).strip().lower() == "sidecar" else "docked" + self.exit_fullscreen() if normalized == self._mode and self.is_open: + self._sync_header() return self._mode = normalized if self.is_open: @@ -655,19 +724,91 @@ class SpatialWingManager(QObject): def toggle_mode(self) -> None: self.set_mode("sidecar" if self._mode == "docked" else "docked") - def update_header(self, *, title: str | None = None, subtitle: str | None = None) -> None: - if title is not None: - self._title = title - if subtitle is not None: - self._subtitle = subtitle + # ── 全屏查看 ────────────────────────────────────────────────────────── + + def toggle_fullscreen(self) -> None: + if self.is_fullscreen: + self.exit_fullscreen() + else: + self.enter_fullscreen() + + def enter_fullscreen(self) -> None: + """把当前伴随视窗铺满主工作台所在屏幕;记录停靠状态以便原样恢复。""" + + if not self.is_open or self.is_fullscreen: + return + sidecar_geom: QRect | None = None + if self._mode == "sidecar" and self._sidecar is not None and self._sidecar.isVisible(): + sidecar_geom = QRect(self._sidecar.geometry()) + self._fullscreen_restore = (self._mode, self._side, sidecar_geom) + + sidecar = self._ensure_sidecar() + if self._mode == "docked": + # 嵌入态:把卡片临时移到独立窗口里全屏,主工作台布局保持不变。 + self.left_dock.hide() + self.right_dock.hide() + self.splitter.setSizes([0, max(800, self.shell.width()), 0]) + sidecar.mount_card(self.card) + # 先放到主工作台所在位置,确保全屏落在同一块屏幕上。 + sidecar.setGeometry(self.shell.geometry()) + self.card.glide_veil.cancel() + sidecar.showFullScreen() + sidecar.raise_() + sidecar.activateWindow() + self.card.setFocus(Qt.FocusReason.OtherFocusReason) + self._sync_header() + + def exit_fullscreen(self) -> None: + """退出全屏并恢复进入前的停靠模式、左/右翼方位与独立副窗位置。""" + + restore = self._fullscreen_restore + if restore is None: + return + self._fullscreen_restore = None + mode, side, sidecar_geom = restore + self._mode = mode + self._side = side + sidecar = self._sidecar + if sidecar is not None and sidecar.isFullScreen(): + sidecar.showNormal() + if not self.is_open: + self._sync_header() + return + if mode == "docked": + self._apply_placement() + return + self._sync_header() + if sidecar is not None: + if sidecar_geom is not None and sidecar_geom.isValid(): + sidecar.setGeometry(sidecar_geom) + else: + self._arrange_shell_and_sidecar(initial=True) + sidecar.show() + sidecar.raise_() + + def _on_escape(self) -> None: + if self.is_fullscreen: + self.exit_fullscreen() + else: + self.close_wing() + + def _sync_header(self) -> None: self.card.header.set_metadata( title=self._title, subtitle=self._subtitle, icon_kind=self._icon_kind, side=self._side, mode=self._mode, + fullscreen=self.is_fullscreen, ) + def update_header(self, *, title: str | None = None, subtitle: str | None = None) -> None: + if title is not None: + self._title = title + if subtitle is not None: + self._subtitle = subtitle + self._sync_header() + def _should_animate_wing(self) -> bool: return ( self.shell.isVisible() @@ -865,13 +1006,10 @@ class SpatialWingManager(QObject): ) def _apply_placement(self) -> None: - self.card.header.set_metadata( - title=self._title, - subtitle=self._subtitle, - icon_kind=self._icon_kind, - side=self._side, - mode=self._mode, - ) + self._sync_header() + if self.is_fullscreen: + # 全屏期间切换内容时保持全屏,停靠位置待退出全屏时再恢复。 + return if self._mode == "sidecar": self._mount_in_sidecar() else: @@ -1043,6 +1181,8 @@ class SpatialWingManager(QObject): def close_wing(self, *, from_dialog: bool = False) -> None: if not self.is_open and (self._sidecar is None or not self._sidecar.isVisible()): return + # 关闭前先退出全屏,下次打开仍回到原来的停靠方位与模式。 + self.exit_fullscreen() self._teardown_active(reject_dialog=not from_dialog) self.left_dock.hide() self.right_dock.hide() @@ -1064,7 +1204,9 @@ class SpatialWingManager(QObject): def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 if watched is self.shell and self._mode == "sidecar" and self.is_open and self._sidecar is not None: et = event.type() - if et in {QEvent.Type.Move, QEvent.Type.Resize} and not self._syncing_geometry: + if et in {QEvent.Type.Move, QEvent.Type.Resize} and self.is_fullscreen: + pass + elif et in {QEvent.Type.Move, QEvent.Type.Resize} and not self._syncing_geometry: if self._sidecar.magnet_locked and not self.shell.isMinimized(): main_g = self.shell.frameGeometry() gap = 10 diff --git a/app/src/doctor_workstation/ui/theme.py b/app/src/doctor_workstation/ui/theme.py index dd68e1211..d328f5368 100755 --- a/app/src/doctor_workstation/ui/theme.py +++ b/app/src/doctor_workstation/ui/theme.py @@ -1021,29 +1021,29 @@ QFrame#LoginCard { QSplitter::handle { background-color: transparent; width: 8px; height: 8px; } QSplitter::handle:hover { background-color: $indigo_pressed; } -QPushButton[variant="secondary"]:disabled, -QPushButton[variant="secondary"]:checked:disabled, -QPushButton[variant="success"]:disabled, -QPushButton[variant="success"]:checked:disabled, -QPushButton[variant="warning"]:disabled, -QPushButton[variant="warning"]:checked:disabled, -QPushButton[variant="danger"]:disabled, -QPushButton[variant="danger"]:checked:disabled, -QPushButton[variant="dangerGhost"]:disabled, -QPushButton[variant="dangerGhost"]:checked:disabled, -QPushButton[variant="ghost"]:disabled, -QPushButton[variant="ghost"]:checked:disabled, -QPushButton[variant="link"]:disabled, -QPushButton[variant="link"]:checked:disabled, -QPushButton[variant="chip"]:disabled, -QPushButton[variant="chip"]:checked:disabled, -QPushButton[variant="nav"]:disabled, -QPushButton[variant="nav"]:checked:disabled { - color: $disabled_text; - background-color: $disabled_surface; - border-color: $line; -} - +QPushButton[variant="secondary"]:disabled, +QPushButton[variant="secondary"]:checked:disabled, +QPushButton[variant="success"]:disabled, +QPushButton[variant="success"]:checked:disabled, +QPushButton[variant="warning"]:disabled, +QPushButton[variant="warning"]:checked:disabled, +QPushButton[variant="danger"]:disabled, +QPushButton[variant="danger"]:checked:disabled, +QPushButton[variant="dangerGhost"]:disabled, +QPushButton[variant="dangerGhost"]:checked:disabled, +QPushButton[variant="ghost"]:disabled, +QPushButton[variant="ghost"]:checked:disabled, +QPushButton[variant="link"]:disabled, +QPushButton[variant="link"]:checked:disabled, +QPushButton[variant="chip"]:disabled, +QPushButton[variant="chip"]:checked:disabled, +QPushButton[variant="nav"]:disabled, +QPushButton[variant="nav"]:checked:disabled { + color: $disabled_text; + background-color: $disabled_surface; + border-color: $line; +} + QToolTip { color: $text; background-color: $raised; @@ -1549,6 +1549,24 @@ def _size_new_window_to_main(window: QWidget) -> None: ) +def _install_dialog_fullscreen(dialog: QDialog) -> None: + """给以独立顶层窗口打开的业务对话框挂载 F11 全屏 / Esc 退出全屏。 + + 嵌入伴随视窗的对话框由伴随视窗标题栏的“全屏”按钮负责;消息框、输入框、 + 确认浮层等临时提示与固定尺寸的小窗不需要全屏。 + """ + + if not dialog.isWindow() or dialog.property("hostedInSpatialWing"): + return + if isinstance(dialog, (QMessageBox, QInputDialog, QFileDialog)): + return + if dialog.property("skipSpatialWing") or dialog.minimumSize() == dialog.maximumSize(): + return + from .fullscreen import install_window_fullscreen + + install_window_fullscreen(dialog) + + class _BusinessDialogStyleFilter(QObject): """Style dynamically-created Qt dialogs just before they become visible.""" @@ -1623,6 +1641,7 @@ class _BusinessDialogStyleFilter(QObject): _polish_dialog_buttons(button_box) if not self._is_native_or_overlay(watched): mark_business_dialog(watched) + _install_dialog_fullscreen(watched) if isinstance(watched, QMessageBox): icon_kinds = { QMessageBox.Icon.Information: "info", diff --git a/app/src/doctor_workstation/video/window.py b/app/src/doctor_workstation/video/window.py index a85cf409f..49e8c10f2 100755 --- a/app/src/doctor_workstation/video/window.py +++ b/app/src/doctor_workstation/video/window.py @@ -527,6 +527,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self._companion_toggle.setCheckable(True) self._companion_toggle.setCursor(Qt.CursorShape.PointingHandCursor) hud_row.addWidget(self._companion_toggle) + self._install_fullscreen_toggle(hud, hud_row) shell_layout.addWidget(hud) stage_row = QHBoxLayout() @@ -582,6 +583,37 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self.web_view.loadFinished.connect(self._on_load_finished) self.web_view.setUrl(QUrl(self.location.url)) + def _install_fullscreen_toggle(self, hud: Any, hud_row: Any) -> None: + """在视频窗顶栏挂载统一的“全屏 / 退出全屏”按钮(F11 切换,Esc 退出)。""" + + from ..ui.fullscreen import ( + fullscreen_button_text, + fullscreen_button_tip, + install_window_fullscreen, + ) + + controller = install_window_fullscreen(self) + button = QPushButton(fullscreen_button_text(False), hud) + button.setObjectName("VideoHudFullscreenBtn") + button.setCheckable(True) + button.setCursor(Qt.CursorShape.PointingHandCursor) + button.setToolTip(fullscreen_button_tip(False)) + + def _sync(active: bool) -> None: + button.setChecked(active) + button.setText(fullscreen_button_text(active)) + button.setToolTip(fullscreen_button_tip(active)) + + def _clicked(_checked: bool = False) -> None: + controller.toggle() + _sync(controller.is_fullscreen) + + button.clicked.connect(_clicked) + controller.toggled.connect(_sync) + hud_row.addWidget(button) + self._fullscreen_controller = controller + self._fullscreen_button = button + def _configure_settings(self, settings: Any) -> None: attributes = getattr(QWebEngineSettings, "WebAttribute", QWebEngineSettings) values = ( diff --git a/app/tests/test_issued_prescription_ai.py b/app/tests/test_issued_prescription_ai.py index 95fe752e0..03c4e2120 100755 --- a/app/tests/test_issued_prescription_ai.py +++ b/app/tests/test_issued_prescription_ai.py @@ -1,1905 +1,2029 @@ -"""Dual-model report and API contracts, exercised offscreen without network access.""" - -from __future__ import annotations - -import os -import socket -from copy import deepcopy -from datetime import datetime -from typing import Any -from uuid import UUID - -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 -from doctor_workstation.services.repository import RemoteDoctorRepository -from doctor_workstation.ui.dialogs import issued_prescription_ai as ai -from doctor_workstation.ui.dialogs import prescription as editor_module -from doctor_workstation.ui.pages import prescriptions as page_module - - -def batch(batch_id: int = 40, prescription_id: int = 801, status: str = "running") -> dict[str, Any]: - return { - "id": batch_id, "prescription_id": prescription_id, "prescription_revision": 2, "agreement_visible": True, - "patient_id": 301, "diagnosis_id": 501, "status": status, - "validity": "current", "comparison_type": "independent_baseline", - "source_summary": {"diagnosis_count": 2, "attachment_count": 4}, - "missing": [{"source": "tongue", "reason": "第4张图片不可读"}], - "cutoff_at": "2026-09-09 10:00:00", "created_at": "2026-09-09 10:01:00", - "models": { - "qwen": { - "status": "succeeded", "report": {"summary": "已保存千问分析 "}, - "candidate": {"status": "available_for_review", "herbs": [{"name": "黄芪", "dosage": 12, "unit": "g", "dose_basis": "每剂", "formula_type": "主方"}]}, - "comparison": {"status": "comparable", "score": 0, "herb_score": 0, "algorithm_version": "v1", "rows": [{"name": "黄芪", "doctor_dose": None, "candidate_dose": 12, "contribution": 0}], "usage_differences": ["疗程需复核"]}, - "coverage": {"status": "incomplete", "manifest": [{"name": "舌象4", "status": "unreadable"}]}, - "review": {"status": "needs_information", "comment": "需补充清晰舌象"}, - }, - "openai": {"status": "running", "report": None, "candidate": None, "comparison": None, "coverage": {"status": "pending"}}, - }, - } - - -class Repository(DemoDoctorRepository): - def __init__(self) -> None: - super().__init__() - self.calls: list[tuple[str, Any]] = [] - self.batches = [batch()] - self.enabled = True - self.agreement_visible = True - - def get_prescription_ai_capabilities(self) -> dict[str, Any]: - return {"agreement_visible": self.agreement_visible, "can_manage_visibility": False} - - def list_prescription_ai_reports(self, **params: Any) -> dict[str, Any]: - self.calls.append(("reports", params)) - return {"agreement_visible": self.agreement_visible, "enabled": self.enabled, "lists": deepcopy(self.batches), "count": len(self.batches), "page_no": 1, "page_size": 20} - - def get_prescription_ai_report(self, batch_id: int) -> dict[str, Any]: - self.calls.append(("detail", batch_id)) - return deepcopy(next(row for row in self.batches if row["id"] == batch_id)) - - def retry_prescription_ai(self, batch_id: int, model_key: str) -> dict[str, Any]: - self.calls.append(("retry", (batch_id, model_key))) - return {"batch_id": batch_id, "status": "queued"} - - def regenerate_prescription_ai(self, prescription_id: int, reason: str) -> dict[str, Any]: - self.calls.append(("regenerate", (prescription_id, reason))) - return {"batch_id": 41, "status": "queued"} - - def review_prescription_ai(self, batch_id: int, model_key: str, status: str, comment: str) -> dict[str, Any]: - self.calls.append(("review", (batch_id, model_key, status, comment))) - return {"saved": True} - - def list_prescription_ai_statuses(self, ids: list[int]) -> dict[str, Any]: - self.calls.append(("statuses", list(ids))) - return {"agreement_visible": self.agreement_visible, "enabled": self.enabled, "items": [{"agreement_visible": self.agreement_visible, "prescription_id": value, "batch_id": 40, "status": "running", "validity": "current", "comparison_type": "independent_baseline", "models": {"qwen": {"status": "succeeded", "score": 0, "comparison_status": "comparable"}, "openai": {"status": "running", "score": None}}} for value in ids] if self.enabled else []} - - -@pytest.fixture(scope="module") -def application() -> QApplication: - return QApplication.instance() or QApplication([]) - - -@pytest.fixture(autouse=True) -def no_network(monkeypatch: pytest.MonkeyPatch) -> None: - def denied(*_args: Any, **_kwargs: Any) -> None: - pytest.fail("These tests must never contact external systems") - monkeypatch.setattr(socket.socket, "connect", denied) - monkeypatch.setattr(socket.socket, "connect_ex", denied) - monkeypatch.setattr(socket, "create_connection", denied) - - -@pytest.fixture -def immediate(monkeypatch: pytest.MonkeyPatch) -> None: - def run(function: Any, *, on_success: Any = None, on_error: Any = None, on_finished: Any = None) -> object: - try: - result = function() - except Exception as error: - if on_error: - on_error(error) - else: - raise - else: - if on_success: - on_success(result) - finally: - if on_finished: - on_finished() - return object() - for module in (ai, page_module, editor_module): - monkeypatch.setattr(module, "run_async", run) - - -@pytest.mark.parametrize(("value", "expected"), [(None, "—"), (0, "0%"), (100, "100%"), (42.3, "42%"), (float("nan"), "—"), (float("inf"), "—"), (False, "—"), (-1, "—")]) -def test_percentage_never_turns_missing_into_zero(value: Any, expected: str) -> None: - 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) - dialog.show() - application.processEvents() - assert [call[0] for call in repository.calls] == ["reports", "detail"] - assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() - assert dialog.model_views["qwen"]["score"].text() == "0.0%" - assert dialog.model_views["openai"]["score"].text() == "—" - assert "资料不全" in dialog.model_views["qwen"]["title"].text() - assert "黄芪" in dialog.model_views["qwen"]["candidate"].toPlainText() - assert "医生剂量" in dialog.model_views["qwen"]["comparison"].toPlainText() - assert "第4张图片不可读" in dialog.model_views["qwen"]["sources"].toPlainText() - assert "<script>" in dialog.model_views["qwen"]["report"].toHtml() - assert dialog._timer.isActive() - assert not dialog.model_views["qwen"]["retry"].isEnabled() - assert not dialog.model_views["openai"]["retry"].isEnabled() - dialog.hide() - assert not dialog._timer.isActive() - calls = list(repository.calls) - dialog._poll() - assert repository.calls == calls - - -def test_report_open_and_poll_never_show_auxiliary_windows(application: QApplication, immediate: None) -> None: - shown_windows = [] - - class WindowObserver(QObject): - def eventFilter(self, watched: QObject, event: QEvent) -> bool: - if event.type() == QEvent.Type.Show and isinstance(watched, QWidget) and watched.isWindow(): - shown_windows.append((watched.metaObject().className(), watched.windowTitle())) - return False - - observer = WindowObserver() - application.installEventFilter(observer) - dialog = None - try: - repository = Repository() - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - application.processEvents() - initial_windows = list(shown_windows) - shown_windows.clear() - dialog.tabs.setCurrentIndex(3) - dialog.model_views["qwen"]["comment"].setPlainText("正在填写的复核意见") - for _ in range(3): - dialog._timer.timeout.emit() - dialog._progress_timer.timeout.emit() - application.processEvents() - assert len([call for call in repository.calls if call[0] == "detail"]) == 4 - assert shown_windows == [], "Polling must not show even transient top-level widgets" - assert initial_windows == [("IssuedPrescriptionAiDialog", dialog.windowTitle())] - assert dialog.tabs.currentIndex() == 3 - assert dialog.model_views["qwen"]["comment"].toPlainText() == "正在填写的复核意见" - assert dialog.chip_row.count() == 2 - assert all(dialog.chip_row.itemAt(index).widget().isVisible() for index in range(2)) - assert dialog._timer.isActive() and dialog._progress_timer.isActive() - finally: - application.removeEventFilter(observer) - if dialog is not None: - dialog.close() - - -def test_navigation_names_every_destination_once(application: QApplication, immediate: None) -> None: - """A duplicated tab name makes the navigation unreadable; the live progress lives in the one tab.""" - dialog = ai.IssuedPrescriptionAiDialog(Repository(), ["*"], prescription_id=801) - dialog.show() - application.processEvents() - names = [dialog.tabs.tabText(index) for index in range(dialog.tabs.count())] - assert len(names) == len(set(names)), names - assert names.count("处理进度") == 1 - # Those pages are hosted in a scroll area, so the tab holds the host, not the page itself. - for key in ("per_herb", "gaps", "history"): - assert dialog.tabs.indexOf(dialog.tab_pages[key]) >= 0 - bar = dialog.model_views["qwen"]["progress_bar"] - assert dialog.pipeline_page.isAncestorOf(bar) - assert dialog.pipeline_page.stage_labels["qwen"].isHidden() - dialog.close() - - -@pytest.mark.parametrize(("width", "height"), [(1280, 860), (1024, 700), (940, 640)]) -def test_prescription_workspace_is_the_primary_view(application: QApplication, immediate: None, width: int, height: int) -> None: - dialog = ai.IssuedPrescriptionAiDialog(Repository(), ["*"], prescription_id=801) - dialog.resize(width, height) - dialog.show() - application.processEvents() - assert (dialog.width(), dialog.height()) == (width, height) - assert dialog.tabs.currentWidget() is dialog.comparison_panel - assert dialog.tabs.tabText(0) == "对比总览" - assert dialog.comparison_panel.isVisible() - assert dialog.tabs.height() > height * 0.28 - assert dialog.model_views["qwen"]["comment"].isVisible() - # The chart strip is on the first screen but must never outgrow its budget, and a model - # without a comparable score shows no filled bar. - assert dialog.model_views["qwen"]["agreement_bar"].value() == 0 - assert dialog.model_views["openai"]["agreement_bar"].isHidden() - assert dialog.model_views["qwen"]["gauge"].accessibleDescription() == "0.0%" - assert dialog.model_views["openai"]["gauge"].accessibleDescription() == "暂无可比结果" - dialog.close() - - -@pytest.mark.parametrize(("width", "height"), [(1440, 940), (1280, 860), (1024, 700), (940, 640)]) -def test_review_controls_remain_inside_the_sidebar(application: QApplication, immediate: None, - width: int, height: int) -> None: - repository = Repository() - model = repository.batches[0]["models"]["qwen"] - herb = model["candidate"]["herbs"][0] - model["comparison"]["rows"][0].update(key="黄芪", doctor={**herb, "dosage": 16}, candidate=herb) - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.resize(width, height) - dialog.show() - panel = dialog.comparison_panel - for _ in range(4): - application.processEvents() - assert dialog.nav_buttons["overview"].isChecked() - for key in ai.MODELS: - dialog.review_model.setCurrentIndex(0 if key == "qwen" else 1) - application.processEvents() - views = dialog.model_views[key] - for control in (dialog.review_model, views["review_state"], views["comment"], views["save"]): - assert control.isVisible() - bounds = QRect(control.mapTo(panel.checklist, control.rect().topLeft()), control.size()) - assert panel.checklist.rect().contains(bounds), (key, control.accessibleName(), bounds) - assert ai.MODELS[key] in dialog.save_review_button.toolTip() - assert panel.checklist.isVisible() - dialog.close() - - -def test_hero_band_carries_the_frozen_identity_and_yields_on_short_windows(application: QApplication, immediate: None) -> None: - repository = Repository() - repository.batches[0]["doctor_snapshot"] = { - "patient": {"name": "测试患者", "gender_label": "女", "age": 58}, - "diagnosis": {"clinical_diagnosis": "消渴病 气阴两虚"}, - "prescription": {"prescription_type": "浓缩水丸", "dose_count": 1, "dose_unit": "剂"}, - } - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.resize(1280, 860) - dialog.show() - application.processEvents() - assert "测试患者 · 女 · 58 岁" in dialog.identity.text() - assert "消渴病 气阴两虚" in dialog.identity.text() - assert "浓缩水丸 · 1 剂" in dialog.identity.text() - assert dialog.fact_values["basis"].text() == "同单位 · 每剂" - assert dialog.fact_values["prescription"].text() == "801 / 501" - dialog.resize(1024, 700) - application.processEvents() - assert dialog.fact_values["batch"].text() == "#40" - dialog.close() - - -def test_hero_band_shows_dashes_when_the_snapshot_is_not_deployed(application: QApplication, immediate: None) -> None: - repository = Repository() - repository.batches[0].pop("doctor_snapshot", None) - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.resize(1280, 860) - dialog.show() - application.processEvents() - assert dialog.identity.text() == "尚无冻结快照" - assert dialog.fact_values["prescription"].text().startswith("801") - dialog.close() - - -def test_failed_model_states_the_reason_and_offers_its_own_retry(application: QApplication, immediate: None) -> None: - repository = Repository() - repository.batches[0]["models"]["openai"].update(status="failed", error_code="INVALID_REPORT_OUTPUT", - error_message="INVALID_REPORT_OUTPUT") - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - application.processEvents() - assert dialog.model_views["openai"]["failure"].isVisible() - text = dialog.model_views["openai"]["failure_text"].text() - assert "OpenAI 失败" in text and "格式校验" in text and "原资料快照" in text - assert "INVALID_REPORT_OUTPUT" not in text - assert dialog.model_views["openai"]["retry"].isEnabled() - assert dialog.model_views["openai"]["retry"].isVisible() - # A model that is still running never shows a failure row. - dialog.model_views["openai"]["retry"].click() - application.processEvents() - assert ("retry", (40, "openai")) in repository.calls - dialog.close() - - -def test_exhausted_manual_retries_point_at_regeneration_instead_of_retry(application: QApplication, immediate: None) -> None: - repository = Repository() - repository.batches[0]["models"]["openai"].update(status="failed", error_code="UPSTREAM_TIMEOUT", - error_message="UPSTREAM_TIMEOUT", manual_retries=2) - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - application.processEvents() - 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": "已保存报告"}) - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - application.processEvents() - dialog.model_views["qwen"]["comment"].setPlainText("千问复核草稿") - dialog.review_model.setCurrentIndex(1) - dialog.model_views["openai"]["comment"].setPlainText("OpenAI复核草稿") - dialog.model_views["openai"]["review_state"].setCurrentIndex(3) - dialog._poll() - application.processEvents() - assert dialog.review_model.currentData() == "openai" - assert dialog.model_views["qwen"]["comment"].toPlainText() == "千问复核草稿" - assert dialog.model_views["openai"]["comment"].toPlainText() == "OpenAI复核草稿" - dialog.save_review_button.click() - assert ("review", (40, "openai", "reviewed", "OpenAI复核草稿")) in repository.calls - assert not any(call[0] == "review" and call[1][1] == "qwen" for call in repository.calls) - dialog.close() - - -def test_workspace_links_reach_existing_supporting_reports(application: QApplication, immediate: None) -> None: - dialog = ai.IssuedPrescriptionAiDialog(Repository(), ["*"], prescription_id=801) - dialog.show() - # Each link opens the composed page that answers it, not the raw saved text. - for field, key in (("report", "report"), ("candidate", "candidate"), ("comparison", "per_herb"), - ("sources", "gaps"), ("progress", "pipeline"), ("doctor", "original")): - dialog.comparison_panel.open_report.emit(field) - assert dialog.tabs.currentWidget() is dialog.tab_pages[key], field - dialog.nav_buttons["overview"].click() - assert dialog.tabs.currentWidget() is dialog.comparison_panel - assert dialog.nav_buttons["overview"].isChecked() - assert not dialog.nav_buttons["gaps"].isChecked() - dialog.nav_buttons["per_herb"].click() - assert dialog.tabs.currentWidget() is dialog.tab_pages["per_herb"] - dialog.close() - - -def test_retry_and_review_target_only_selected_model(application: QApplication, immediate: None) -> None: - repository = Repository() - repository.batches[0]["status"] = "partial" - repository.batches[0]["models"]["openai"].update(status="failed", error_code="timeout", error_message="模型超时") - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - assert dialog.model_views["openai"]["retry"].isEnabled() - assert not dialog._timer.isActive() - dialog._retry("openai") - assert ("retry", (40, "openai")) in repository.calls - dialog.model_views["qwen"]["review_state"].setCurrentIndex(3) - dialog.model_views["qwen"]["comment"].setPlainText("已核对逐味差异") - dialog._review("qwen") - assert ("review", (40, "qwen", "reviewed", "已核对逐味差异")) in repository.calls - assert not any(call[0] == "regenerate" for call in repository.calls) - dialog.close() - - -def test_history_and_hidden_dialog_ignore_late_detail(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: - repository = Repository() - repository.batches.append(batch(41)) - repository.batches[1]["models"]["qwen"]["report"] = {"summary": "第二批报告"} - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - pending = [] - monkeypatch.setattr(ai, "run_async", lambda function, **callbacks: pending.append((function, callbacks))) - dialog._poll() - assert len(pending) == 1 - old_generation = dialog._generation - dialog.history.setCurrentIndex(1) - assert dialog._generation > old_generation - old_function, old_callbacks = pending[0] - old_callbacks["on_success"](old_function()) - assert dialog._batch == {} - new_function, new_callbacks = pending[1] - new_callbacks["on_success"](new_function()) - assert dialog._batch["id"] == 41 - assert "第二批报告" in dialog.model_views["qwen"]["report"].toPlainText() - dialog.hide() - new_callbacks["on_success"](batch(41)) - assert "第二批报告" in dialog.model_views["qwen"]["report"].toPlainText() - - -def test_wrong_patient_batch_is_not_displayed(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: - repository = Repository() - wrong_patient = batch() - wrong_patient["patient_id"] = 999 - monkeypatch.setattr(repository, "get_prescription_ai_report", lambda _batch_id: wrong_patient) - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], diagnosis_id=501) - dialog.show() - assert repository.calls[0][1]["diagnosis_id"] == 501 - assert dialog._batch == {} - assert "归属" in dialog.message.text() - assert not dialog.model_views["qwen"]["report"].toPlainText() - dialog.close() - - -def test_patient_history_accepts_other_authorized_visits(application: QApplication, immediate: None) -> None: - repository = Repository() - repository.batches[0]["diagnosis_id"] = 499 - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], diagnosis_id=501) - dialog.show() - assert dialog._batch["diagnosis_id"] == 499 - assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() - dialog.close() - - -def test_disabled_generation_keeps_history_readable(application: QApplication, immediate: None) -> None: - repository = Repository() - repository.enabled = False - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() - assert not dialog.regenerate_button.isEnabled() - assert "未启用" in dialog.message.text() - dialog.close() - - -def test_view_permission_cannot_mutate(application: QApplication, immediate: None) -> None: - repository = Repository() - permissions = ["tcm.prescriptionAi/reports", "tcm.prescriptionAi/detail"] - dialog = ai.IssuedPrescriptionAiDialog(repository, permissions, prescription_id=801) - dialog.show() - assert dialog.regenerate_button.isHidden() - dialog._review("qwen") - dialog._retry("openai") - assert not any(call[0] in {"review", "retry", "regenerate"} for call in repository.calls) - dialog.close() - - -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() - application.processEvents() - statuses = [call for call in repository.calls if call[0] == "statuses"] - assert statuses and set(statuses[-1][1]) <= {801, 802} - assert len(statuses[-1][1]) <= 100 - assert not page.table.isColumnHidden(11) - assert not page.table.isColumnHidden(12) - 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() - assert not page._ai_timer.isActive() - calls = list(repository.calls) - page._load_ai_statuses() - assert repository.calls == calls - - -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)) - page = page_module.PrescriptionsPage(repository, ["*"]) - page.resize(1366, 800) - page.show() - application.processEvents() - # Demo row 801 contains herbs; row 802 is an empty manual prescription. - assert all(call[1] == [801] for call in repository.calls if call[0] == "statuses") - assert not page.table.isColumnHidden(11) and not page.table.isColumnHidden(12) - page._ai_statuses[802] = batch(prescription_id=802) - page._render_ai_statuses() - for column in (11, 12): - item = page.table.item(1, column) - assert item.text() == item.toolTip() == item.data(Qt.ItemDataRole.AccessibleTextRole) == "" - assert not any(button.accessibleName() == "AI 报告" for button in page.table.cellWidget(1, 2).findChildren(QPushButton)) - page.table.selectRow(1) - assert page.ai_report_button.isHidden() and not page.ai_report_button.isEnabled() - page._open_ai_report() - 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() - page.ai_report_button.click() - assert opened == [{"prescription_id": 801}] - 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_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}) - page = page_module.PrescriptionsPage(repository, ["*"]) - page.resize(1366, 800) - page.show() - application.processEvents() - 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) - assert not any(button.accessibleName() == "AI 报告" for button in page.table.cellWidget(0, 2).findChildren(QPushButton)) - - row.update(is_system_auto=0, herbs=[{"name": "黄芪", "dosage": 12}]) - page.refresh() - application.processEvents() - assert ("statuses", [803]) in repository.calls - assert not page.table.isColumnHidden(11) and not page.table.isColumnHidden(12) - assert page.ai_report_button.isVisible() and page.ai_status_notice.isVisible() - assert "千问 0%" in page.table.item(0, 12).text() - assert any(button.accessibleName() == "AI 报告" for button in page.table.cellWidget(0, 2).findChildren(QPushButton)) - page.close() - - -def test_list_disabled_explains_availability_and_keeps_history(application: QApplication, immediate: None) -> None: - repository = Repository() - page = page_module.PrescriptionsPage(repository, ["*"]) - page.resize(1366, 800) - page.show() - application.processEvents() - 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() - - -def test_list_service_error_is_visible_and_clears_after_recovery(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: - repository = Repository() - - def unavailable(_ids: list[int]) -> dict[str, Any]: - raise RuntimeError("AI service unavailable") - - monkeypatch.setattr(repository, "list_prescription_ai_statuses", unavailable) - page = page_module.PrescriptionsPage(repository, ["*"]) - page.resize(1366, 800) - page.show() - application.processEvents() - assert page.ai_status_notice.isVisible() - assert "暂不可用" in page.ai_status_notice.text() - 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() - application.processEvents() - 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, 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_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() - - -def test_list_ignores_response_after_filter_generation_changes(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: - repository = Repository() - page = page_module.PrescriptionsPage(repository, ["*"]) - page.resize(1366, 800) - page.show() - application.processEvents() - callbacks = [] - monkeypatch.setattr(page_module, "run_async", lambda function, **kwargs: callbacks.append((function, kwargs))) - page._load_ai_statuses() - assert callbacks - page._generation += 1 - page._ai_statuses = {} - function, call = callbacks[0] - call["on_success"](function()) - assert page._ai_statuses == {} - page.close() - - -def test_statistics_nulls_and_absent_review_samples(application: QApplication, immediate: None) -> None: - class StatisticsRepository: - def get_prescription_ai_capabilities(self) -> dict[str, Any]: - return {"agreement_visible": True} - - def prescription_ai_statistics(self, *_args: Any) -> dict[str, Any]: - return {"total_count": 3, "patient_count": 2, "doctors": [{"doctor_name": "张医生", "total_count": 3, "patient_count": 2, "models": {"qwen": {"eligible_count": 0, "coverage_rate": 0, "mean": None, "median": None, "excluded_reasons": {"non_independent": 3}}, "openai": {"eligible_count": 1, "coverage_rate": 33.3, "mean": 0, "median": 0}}, "review": {"evaluated_count": 0, "qualified_count": 0, "qualified_rate": None}}]} - dialog = ai.PrescriptionAiStatisticsDialog(StatisticsRepository(), ["*"]) - dialog.show() - text = dialog.report.toPlainText() - assert "均值:—" in text and "均值:0.0%" in text - assert "未建立复核样本" in text - assert "开方事件:3" in dialog.summary.text() - dialog.close() - - -def test_editor_keeps_request_key_for_identical_content_and_preserves_ai_assistance(application: QApplication, immediate: None) -> None: - editor = editor_module.PrescriptionEditorDialog(DemoDoctorRepository(), {"ai_assisted": True}) - first = editor.payload() - assert first["ai_assisted"] is True - assert str(UUID(first["request_key"])) == first["request_key"] - assert first["request_key"] == editor.payload()["request_key"] - editor.patient_name.setText("新患者") - assert first["request_key"] != editor.payload()["request_key"] - editor.close() - unknown = editor_module.PrescriptionEditorDialog(DemoDoctorRepository()) - assert "ai_assisted" not in unknown.payload() - unknown.close() - unconfirmed = editor_module.PrescriptionEditorDialog(DemoDoctorRepository(), {"ai_assisted": False}) - assert "ai_assisted" not in unconfirmed.payload() - unconfirmed.close() - - -def test_repository_exact_read_and_mutation_contracts() -> None: - class Client: - def __init__(self) -> None: - self.calls = [] - def get(self, endpoint: str, params: Any) -> dict[str, Any]: - self.calls.append(("GET", endpoint, params)) - return {"enabled": False, "items": []} - def post(self, endpoint: str, params: Any) -> dict[str, Any]: - self.calls.append(("POST", endpoint, params)) - return {"saved": True} - client = Client() - repository = RemoteDoctorRepository(client) - repository.get_prescription_ai_capabilities() - assert repository.list_prescription_ai_statuses([801, 802, 801]) == {"enabled": False, "items": []} - repository.list_prescription_ai_reports(diagnosis_id=501, page_no=2, page_size=20) - repository.get_prescription_ai_report(40) - assert all(call[0] == "GET" for call in client.calls) - repository.regenerate_prescription_ai(801, "补充病历") - repository.retry_prescription_ai(40, "openai") - repository.review_prescription_ai(40, "qwen", "reviewed", "核对完成") - repository.prescription_ai_statistics("2026-09-01", "2026-09-09", 7) - assert client.calls == [ - ("GET", "tcm.prescriptionAi/capabilities", {}), - ("GET", "tcm.prescriptionAi/statuses", {"ids": "801,802"}), - ("GET", "tcm.prescriptionAi/reports", {"diagnosis_id": 501, "page_no": 2, "page_size": 20}), - ("GET", "tcm.prescriptionAi/detail", {"batch_id": 40}), - ("POST", "tcm.prescriptionAi/regenerate", {"prescription_id": 801, "reason": "补充病历"}), - ("POST", "tcm.prescriptionAi/retry", {"batch_id": 40, "model_key": "openai"}), - ("POST", "tcm.prescriptionAi/review", {"batch_id": 40, "model_key": "qwen", "status": "reviewed", "comment": "核对完成"}), - ("GET", "tcm.prescriptionAi/statistics", {"date_from": "2026-09-01", "date_to": "2026-09-09", "doctor_id": 7}), - ] - with pytest.raises(ValueError): - repository.list_prescription_ai_statuses(list(range(1, 102))) - with pytest.raises(ValueError): - repository.list_prescription_ai_reports(prescription_id=801, diagnosis_id=501) - with pytest.raises(ValueError): - repository.retry_prescription_ai(40, "other") - - -@pytest.mark.parametrize("flag", [False, None, 1, "true"]) -def test_agreement_denied_or_missing_keeps_reports_review_and_retry( - application: QApplication, immediate: None, flag: Any, -) -> None: - repository = Repository() - repository.agreement_visible = flag - value = repository.batches[0] - value["agreement_visible"] = flag - value["models"]["openai"].update(status="failed", error_message="上游超时") - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], diagnosis_id=501, - current_user={"root": 1, "role_ids": [1]}) - dialog.show() - application.processEvents() - assert not dialog._agreement_visible - assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() - assert dialog.model_views["qwen"]["comment"].isEnabled() - assert dialog.model_views["qwen"]["save"].isVisible() - assert dialog.model_views["openai"]["retry"].isVisible() - assert dialog.model_views["openai"]["retry"].isEnabled() - assert dialog.history.count() == 1 - assert dialog.comparison_panel.checklist.isVisible() - assert dialog.comparison_panel.conclusions.isHidden() - assert not dialog.comparison_panel.rows - assert not dialog.comparison_panel.doses.rows - assert dialog.nav_buttons["history"].isHidden() - assert dialog.agreement_note.isHidden() - for key, views in dialog.model_views.items(): - assert not views["score"].text() and not views["score"].toolTip() - assert not views["agreement_bar"].toolTip() and not views["agreement_bar"].accessibleName() - assert views["gauge"]._value is None and not views["gauge"].accessibleDescription() - assert not views["comparison"].toPlainText() - assert "comparison" not in dialog._batch["models"][key] - assert not dialog.agreement.delta.text() and not dialog.agreement.overlap.text() - for key in ("differences", "consensus"): - assert not dialog.rail.focus_values[key].text() - assert dialog.rail.focus_values[key].parentWidget().isHidden() - dialog._goto("per_herb") - assert dialog.tabs.currentWidget() is dialog.tab_pages["candidate"] - assert "黄芪" in dialog.model_views["qwen"]["candidate"].toPlainText() - dialog._goto("comparison_raw") - assert dialog.tabs.currentWidget() is dialog.tab_pages["report"] - dialog._goto("history") - assert dialog.tabs.currentWidget() is dialog.tab_pages["report"] - dialog.close() - - -@pytest.mark.parametrize("missing", ["reports", "history_batch", "detail"]) -def test_each_report_visibility_flag_is_required(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, missing: str) -> None: - repository = Repository() - reports, detail = repository.list_prescription_ai_reports, repository.get_prescription_ai_report - def read_reports(**params: Any) -> dict[str, Any]: - data = reports(**params) - if missing == "reports": - data.pop("agreement_visible") - if missing == "history_batch": - data["lists"][0].pop("agreement_visible") - return data - def read_detail(batch_id: int) -> dict[str, Any]: - data = detail(batch_id) - if missing == "detail": - data.pop("agreement_visible") - return data - monkeypatch.setattr(repository, "list_prescription_ai_reports", read_reports) - monkeypatch.setattr(repository, "get_prescription_ai_report", read_detail) - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - assert not dialog._agreement_visible - assert not dialog.model_views["qwen"]["score"].text() - assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() - dialog.close() - - -def test_agreement_revocation_and_failed_read_clear_cached_views_and_survive_theme( - application: QApplication, immediate: None, -) -> None: - repository = Repository() - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - assert dialog.model_views["qwen"]["score"].text() == "0.0%" - old_batch, old_generation = deepcopy(dialog._batch), dialog._generation - dialog.model_views["qwen"]["comment"].setPlainText("保留复核草稿") - repository.agreement_visible = False - dialog.refresh() - dialog._detail_ready(old_batch, old_generation, 40) - assert not dialog._agreement_visible - assert not dialog.model_views["qwen"]["score"].text() - assert dialog.history_page.table.rowCount() == 0 - assert not dialog.history_page.chart._points - assert dialog.model_views["qwen"]["comment"].toPlainText() == "保留复核草稿" - dialog._switch_theme() - application.processEvents() - assert not dialog._agreement_visible and not dialog.model_views["qwen"]["score"].text() - assert dialog.model_views["qwen"]["comment"].toPlainText() == "保留复核草稿" - dialog._switch_theme() - repository.agreement_visible = True - dialog.refresh() - assert dialog._agreement_visible - dialog._detail_error(RuntimeError("offline"), dialog._generation) - assert not dialog._agreement_visible - assert not dialog.model_views["qwen"]["score"].text() - assert "comparison" not in dialog._batch["models"]["qwen"] - assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() - dialog._detail_ready(old_batch, dialog._generation, 40) - assert not dialog._agreement_visible - dialog.close() - - -def test_revoked_agreement_cache_discards_flat_comparison_metadata() -> None: - value = batch() - sentinel = "previous-private-comparison" - value["baseline_exclusions_json"] = sentinel - value["models"]["qwen"].update({ - "reason": sentinel, "comparison_reason_code": sentinel, - "dictionary_version": sentinel, "error_code": "", - }) - value["models"]["openai"].update({ - "error_code": "UPSTREAM_TIMEOUT", "reason": "模型请求超时", - }) - sanitized = ai.agreement_safe_batch(value, False) - assert sentinel not in str(sanitized) - assert "千问分析" in str(sanitized["models"]["qwen"]["report"]) - assert sanitized["models"]["openai"]["reason"] == "模型请求超时" - assert value["models"]["qwen"]["reason"] == sentinel - - -@pytest.mark.parametrize("flag", [False, None, 1, "true"]) -def test_unlisted_account_sees_empty_ai_cells_and_keeps_reports( - application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, flag: Any, -) -> None: - repository = Repository() - repository.agreement_visible = flag - opened = [] - monkeypatch.setattr(page_module, "present_issued_prescription_ai", lambda *_args, **kwargs: opened.append(kwargs)) - page = page_module.PrescriptionsPage(repository, ["*"], {"root": 1}) - try: - page.resize(1366, 800) - page.show() - application.processEvents() - page.table.selectRow(0) - 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)) - page.ai_report_button.click() - assert opened == [{"prescription_id": 801}] - finally: - 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, failed_read: bool, -) -> None: - repository = Repository() - page = page_module.PrescriptionsPage(repository, ["*"], {"root": 1}) - page.resize(1366, 800) - page.show() - application.processEvents() - 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 - 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_empty_ai_columns(page) - assert page.ai_statistics_button.isHidden() - assert page.ai_report_button.isVisible() - assert page._ai_statuses - 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() - - -def test_list_rechecks_completed_scores_after_hide_and_show(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: - repository = Repository() - original = repository.list_prescription_ai_statuses - def statuses(ids: list[int]) -> dict[str, Any]: - data = original(ids) - for row in data["items"]: - row["status"] = "success" - for model in row["models"].values(): - model["status"] = "success" - return data - monkeypatch.setattr(repository, "list_prescription_ai_statuses", statuses) - page = page_module.PrescriptionsPage(repository, ["*"]) - page.resize(1366, 800) - page.show() - application.processEvents() - assert "0%" in page.table.item(0, 12).text() - before = len([call for call in repository.calls if call[0] == "statuses"]) - page.hide() - page.show() - application.processEvents() - assert len([call for call in repository.calls if call[0] == "statuses"]) > before - assert "0%" in page.table.item(0, 12).text() - page.close() - - -@pytest.mark.parametrize("flag", [False, None, 1, "true"]) -def test_direct_statistics_requires_strict_server_capability(application: QApplication, immediate: None, flag: Any) -> None: - class StatisticsRepository: - calls = 0 - def get_prescription_ai_capabilities(self) -> dict[str, Any]: - return {"agreement_visible": flag, "can_manage_visibility": True} - def prescription_ai_statistics(self, *_args: Any) -> dict[str, Any]: - self.calls += 1 - return {} - repository = StatisticsRepository() - dialog = ai.PrescriptionAiStatisticsDialog(repository, ["*"]) - dialog.show() - assert repository.calls == 0 - assert dialog.panel.isHidden() and not dialog.report.toPlainText() - dialog.close() - - -def test_statistics_failed_capability_clears_old_charts_and_ignores_late_result( - application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, -) -> None: - repository = ChineseStatisticsRepository() - dialog = ai.PrescriptionAiStatisticsDialog(repository, ["*"]) - dialog.show() - assert dialog.panel.isVisible() and dialog.report.toPlainText() - old_generation = dialog._generation - monkeypatch.setattr(repository, "get_prescription_ai_capabilities", lambda: (_ for _ in ()).throw(RuntimeError("offline"))) - dialog.refresh() - dialog._ready(repository.prescription_ai_statistics(), old_generation) - assert dialog.panel.isHidden() and not dialog.report.toPlainText() - assert not dialog.panel.distribution.has_data() - assert dialog.panel.doctors.rowCount() == 0 - dialog.close() - - -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) == "" - assert ai.state_text(value) == "处方已变更" - assert not ai.batch_running({**value, "status": "running"}) - - -@pytest.mark.parametrize("status", ["preparing", "waiting_sources", "retry_wait", "queued", "running"]) -def test_server_pending_states_continue_polling(status: str) -> None: - assert ai.batch_running({"status": status, "validity": "current"}) - assert not ai.batch_running({"status": status, "validity": "prescription_changed"}) - - -def test_regeneration_selects_new_batch_and_preserves_old_history(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: - repository = Repository() - repository.batches[0]["status"] = "success" - repository.batches[0]["models"]["openai"]["status"] = "success" - def regenerate(prescription_id: int, reason: str) -> dict[str, Any]: - repository.calls.append(("regenerate", (prescription_id, reason))) - repository.batches.insert(0, batch(41)) - return {"batch_id": 41, "status": "queued"} - monkeypatch.setattr(repository, "regenerate_prescription_ai", regenerate) - monkeypatch.setattr(ai.QInputDialog, "getMultiLineText", lambda *_args: ("已补充资料", True)) - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - dialog._regenerate() - assert dialog.history.count() == 2 - assert dialog.history.currentData() == 41 - assert dialog._batch["id"] == 41 - assert dialog._timer.isActive() - assert ("regenerate", (801, "已补充资料")) in repository.calls - dialog.close() - - -def test_list_append_retains_finished_cached_scores(application: QApplication, immediate: None) -> None: - repository = Repository() - page = page_module.PrescriptionsPage(repository, ["*"]) - page.resize(1366, 800) - page.show() - application.processEvents() - for cached in page._ai_statuses.values(): - cached["status"] = "success" - cached["models"]["openai"].update(status="success", score=62) - calls = len([call for call in repository.calls if call[0] == "statuses"]) - page._apply_result(repository.list_prescriptions(), page._generation, 1) - assert "OpenAI 62%" in page.table.item(0, 12).text() - assert len([call for call in repository.calls if call[0] == "statuses"]) == calls - assert not page._ai_timer.isActive() - page.close() - - -def test_context_menu_targets_clicked_prescription(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() - application.processEvents() - page.table.selectRow(1) - expected_id = page.table.item(0, 0).data(Qt.ItemDataRole.UserRole).id - action = ai_context_action(page) - assert action.isEnabled() - action.trigger() - assert opened == [{"prescription_id": expected_id}] - page._ai_context_menu.close() - page.close() - - -def test_real_server_comparison_rows_keep_both_doses_and_basis() -> None: - rows = ai._comparison_rows([{ - "key": "1|raw|main", "medicine_id": 1, "name": "黄芪", "processing": "生品", "formula_type": "主方", - "administration_route": "口服", "group": "", "doctor": {"dosage": 30, "unit": "g", "dose_basis": "per_dose"}, - "candidate": {"dosage": 15, "unit": "g", "dose_basis": "per_dose"}, - "doctor_dosage": 30, "candidate_dosage": 15, "unit": "g", "dose_basis": "per_dose", - "match_type": "matched", "contribution": 0.5, - }]) - assert rows[0]["doctor_dosage"] == "30 克" - assert rows[0]["candidate_dosage"] == "15 克" - assert rows[0]["dose_basis"] == "per_dose" - assert rows[0]["contribution"] == 0.5 - assert "生品 / 主方 / 口服" in rows[0]["name"] - - -def test_unavailable_candidate_has_reason_and_pending_review_is_disabled(application: QApplication, immediate: None) -> None: - repository = Repository() - repository.batches[0]["models"]["qwen"]["candidate"] = {"status": "withheld_for_risk", "reason": "过敏用药信息待核实", "herbs": []} - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - text = dialog.model_views["qwen"]["candidate"].toPlainText() - assert "因风险暂缓候选用药" in text and "过敏用药信息待核实" in text - assert not dialog.model_views["openai"]["save"].isEnabled() - assert "分析尚未完成" in dialog.model_views["openai"]["candidate"].toPlainText() - dialog.close() - - -def test_preparation_failure_reason_is_visible_without_models(application: QApplication, immediate: None) -> None: - repository = Repository() - repository.batches[0].update(status="blocked", models={}, error_message="患者关联冲突,需要核对诊单", coverage_status="partial") - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - assert "患者关联冲突" in dialog.batch_summary.text() - assert "资料不全" in dialog.batch_summary.text() - assert "患者关联冲突" in dialog.model_views["qwen"]["candidate"].toPlainText() - dialog.close() - - -def test_actual_history_pagination_contract(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: - repository = Repository() - repository.batches = [batch(value) for value in range(61, 40, -1)] - def reports(**params: Any) -> dict[str, Any]: - repository.calls.append(("reports", params)) - page = params["page_no"] - return {"agreement_visible": True, "lists": repository.batches[(page - 1) * 20:page * 20], "count": 21, "page_no": page, "page_size": 20} - monkeypatch.setattr(repository, "list_prescription_ai_reports", reports) - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - assert dialog.history.count() == 20 and dialog.next.isEnabled() - dialog._history_page(1) - assert dialog.history.count() == 1 - assert dialog._batch["id"] == 41 - assert dialog.previous.isEnabled() and not dialog.next.isEnabled() - assert repository.calls[-2] == ("reports", {"prescription_id": 801, "diagnosis_id": 0, "page_no": 2, "page_size": 20}) - dialog.close() - - -@pytest.mark.parametrize(("status", "expected"), [("blank", "尚未开方"), ("not_generated", "尚无分析记录")]) -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) == "" - - -def test_statistics_displays_actual_version_strata_without_filling_null_mean(application: QApplication, immediate: None) -> None: - class StatisticsRepository: - def get_prescription_ai_capabilities(self) -> dict[str, Any]: - return {"agreement_visible": True} - - def prescription_ai_statistics(self, *_args: Any) -> dict[str, Any]: - strata = [{"versions": {"model_version": version, "algorithm_version": "v1", "prompt_version": "p1", "dictionary_version": "d1"}, "count": 1, "mean": mean, "median": mean, "distribution": {"[0,20)": 1 if mean == 0 else 0}, "sample_status": "insufficient_sample"} for version, mean in (("model-1", 0), ("model-2", 80))] - return {"total_count": 2, "patient_count": 1, "doctors": [{"doctor_id": 7, "doctor_name": "张医生", "total_count": 2, "patient_count": 1, "paired_count": 0, "models": {"qwen": {"eligible_count": 2, "coverage_rate": 100, "mean": None, "median": None, "excluded_reasons": {}, "strata": strata}}, "review": {"evaluated_count": 0, "qualified_count": 0, "qualified_rate": None}}]} - dialog = ai.PrescriptionAiStatisticsDialog(StatisticsRepository(), ["*"]) - dialog.show() - text = dialog.report.toPlainText() - assert "双模型共同有效样本:0" in text - assert "整体均值与中位数不合并" in text - assert "model-1" in text and "model-2" in text - assert "均值:—" in text and "均值:0.0%" in text and "均值:80.0%" in text - assert "样本不足" in text and "未建立复核样本" in text - dialog.close() - - -@pytest.mark.parametrize(("code", "expected"), [ - ("SOURCE_HISTORY_VERSIONS_UNAVAILABLE", "来源历史版本无法核验"), - ("ARCHIVE_SYNC_WATERMARK_UNAVAILABLE: chat_records", "归档同步完整性尚未核验:聊天记录"), - ("TRANSCRIPT_NOT_VERIFIED_COMPLETE:call_records:1820", "问诊转写完整性尚未核验:问诊通话(编号:1820)"), - ("TRANSCRIPT_PARTIAL: video_calls:1821", "问诊转写仅部分完成:视频问诊(编号:1821)"), - ("CRITICAL_CLINICAL_FACT_MISSING:clinical.allergy_history", "关键临床资料缺失:临床资料 · 过敏史"), - ("MODEL_FILE_OUTPUT_INVALID", "模型未能正确解析这组附件"), - ("missing_or_unknown_dose_basis", "每剂或每日剂量基准不明确"), - ("review_not_independent", "复核不具独立性"), -]) -def test_metadata_and_historical_composite_reasons_are_chinese(code: str, expected: str) -> None: - assert ai.label(code) == expected - assert expected in ai._html({"missing_information": [code]}) - - -def test_source_labels_keep_exact_ids_and_distinguish_source_kinds() -> None: - fingerprint = "0123456789abcdef" * 4 - payload = {"evidence_references": ["diagnoses:501", "video_calls:1820", "call_records:1820", "file:" + fingerprint], - "source_id": "clinical.pregnancy_history", "redaction_manifest": ["diagnoses:501:doctor_advice"]} - original = deepcopy(payload) - rendered = ai._html(payload) - assert "诊单(编号:501)" in rendered - assert "视频问诊(编号:1820)" in rendered and "问诊通话(编号:1820)" in rendered - assert f"附件(编号:{fingerprint})" in rendered - assert "临床资料 · 妊娠与哺乳情况" in rendered - assert "诊单(编号:501) · 医嘱" in rendered - assert all(raw not in rendered for raw in ("diagnoses:", "video_calls:", "file:", "clinical.", "doctor_advice")) - assert payload == original - - -def test_unknown_metadata_has_chinese_fallback_without_translating_clinical_prose() -> None: - clinical_text = "CT、MRI、HbA1c 6.2%,HbA1c_result 待复查,Follow-up in 2 weeks;unknown" - payload = {"summary": clinical_text, "treatment_advice": "ALT_AST 需结合 COPD 病史评估", - "status": "newphase", "error_code": "FUTURE_FAILURE_CODE", "future_field": 3, - "future_status": "newstate", "future_enum": "new_enum_value", - "missing_information": ["FUTURE_GAP_CODE:future_records:1820"], "source_id": "future_records:1821"} - original = deepcopy(payload) - rendered = ai._html(payload) - assert clinical_text in rendered and "ALT_AST 需结合 COPD 病史评估" in rendered - assert "未识别的系统状态" in rendered and "其他来源(编号:1820)" in rendered - assert "其他来源(编号:1821)" in rendered and "3" in rendered - for raw in ("newphase", "newstate", "new_enum_value", "FUTURE_FAILURE_CODE", "FUTURE_GAP_CODE", "future_field", "future_records"): - assert raw not in rendered - assert payload == original - - -def test_nested_metadata_translates_fields_values_and_retains_all_statistics() -> None: - payload = { - "coverage": {"status": "partial", "source_complete": True, "files": {"file:42": {"status": "unreadable", "version_verified": False}}}, - "source_summary": {"diagnoses_count": 2, "video_calls_count": 3, "source_record_count": 5, "history_versioning": "unavailable"}, - "normalization": {"doctor": {"defaults": [{"field": "unit", "value": "g"}, {"field": "dose_basis", "value": "per_dose"}]}, - "issues": [{"side": "both", "code": "unit_mismatch", "row": 0}], "unit_policy": "spelling_aliases_only_no_quantity_conversion"}, - "exclusion_reasons": {"SOURCE_HISTORY_VERSIONS_UNAVAILABLE": 12, "future_reason_a": 7, "future_reason_b": 8}, - "review": {"sampling_groups": [{"sampling_method": "risk_directed", "outcomes": {"qualified": 2, "needs_revision": 1}}]}, - } - original = deepcopy(payload) - rendered = ai._html(payload) - for expected in ("资料不全", "历史版本无法核验", "诊单数", "视频问诊数", "克", "每剂", "剂量单位不同", "双方", "按风险抽样", "合格", "需修订"): - assert expected in rendered - for count in (12, 7, 8, 0): - assert f"

{count}

" in rendered - assert rendered.count("未识别的系统标识") == 2 - for raw in ("partial", "version_verified", "diagnoses_count", "per_dose", "SOURCE_HISTORY", "future_reason", "risk_directed", "qualified"): - assert raw not in rendered - assert payload == original - - -def test_metadata_and_prose_remain_html_escaped(application: QApplication) -> None: - attack = '' - html = ai._html({"summary": attack, "missing_information": ["TRANSCRIPT_FAILED:call_records:1820 " + attack], - "source_id": "call_records:1820 " + attack, "status": attack}) - assert " None: - candidate = { - "prescription_name": "测试候选方", "dose_basis": "per_dose", "unit": "g", - "herbs": [{"name": "测试药材", "dosage": 12, "formula_type": "主方", - "instructions": "先煎,具体时长由医生复核", "processing": "生品", - "evidence_references": ["diagnoses:501"]}], - "rationale": "保留完整方义", "risk_warnings": ["复核提示 "], - } - html = ai._candidate_html(candidate) - assert html.index("测试药材") < html.index("保留完整方义") - assert "' - value["models"]["qwen"]["progress"]["notice"] = attack - value["models"]["qwen"]["coverage"] = {"source_ids": ["call_records:1820 " + attack]} - repository.batches = [value] - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - views = dialog.model_views["qwen"] - assert views["progress_detail"].textFormat() == Qt.TextFormat.PlainText - assert attack in views["progress_detail"].text() - assert "<script>" in views["sources"].toHtml() - assert " None: - repository = Repository() - 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() - application.processEvents() - item = page.table.item(0, 11) - assert item.text() == "千问 附件 2/5\nOpenAI 生成报告" - assert "本阶段 2/5 组" in item.toolTip() - assert "不代表附件全部读懂" in item.toolTip() - assert page.table.rowHeight(0) >= 2 * page.table.fontMetrics().height() - assert page._ai_timer.isActive() - page.close() - - -@pytest.mark.parametrize("status", ["success", "failed", "cancelled", "partial"]) -def test_terminal_batch_overrides_obsolete_running_model_checkpoint(application: QApplication, immediate: None, status: str) -> None: - repository = Repository() - value = progress_batch() - value["status"] = status - repository.batches = [value] - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - assert not ai.batch_running(value) - assert not dialog._timer.isActive() and not dialog._progress_timer.isActive() - assert "最后记录" in dialog.model_views["openai"]["progress_title"].text() - assert dialog.model_views["openai"]["progress_bar"].maximum() != 0 - dialog.close() - - -@pytest.mark.parametrize(("status", "notice"), [ - ("failed", "处理未完成,请查看失败原因。 上次进度:校验报告。 耗时按本次尝试计算。"), - ("cancelled", "任务已取消。 耗时按本次尝试计算。"), -]) -def test_terminal_progress_preserves_matching_server_failure_notice(status: str, notice: str) -> None: - value = {"status": status, "progress": {"stage": status, "phase": "failed", "notice": notice, "elapsed_seconds": 180, "attempt": 2}} - view = ai.progress_view(value, seconds=45) - assert notice in view.detail and "第 2 次尝试" in view.detail - assert "已用时 3 分 00 秒" in view.detail - assert not view.busy and view.total is None - assert notice in ai.status_tooltip({"models": {"qwen": value}}) - - -@pytest.mark.parametrize("status", ["failed", "cancelled", "success"]) -def test_terminal_progress_discards_obsolete_waiting_notice(status: str) -> None: - view = ai.progress_view({"status": status, "progress": {"stage": "final", "phase": "waiting", "notice": "等待模型返回。正在生成报告。", "elapsed_seconds": 90}}, seconds=45) - assert "等待模型返回" not in view.detail and "正在生成报告" not in view.detail - assert "已用时 1 分 30 秒" in view.detail - assert not view.busy - - -def test_retry_wait_freezes_attempt_duration_while_countdown_advances_and_poll_remains_consistent(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: - ticks = [100.0] - monkeypatch.setattr(ai, "monotonic", lambda: ticks[0]) - repository = Repository() - value = batch(status="running") - value["models"]["openai"].update(status="retry_wait", progress={ - "stage": "retry_wait", "phase": "waiting", "elapsed_seconds": 180, "stage_elapsed_seconds": 0, - "wait_remaining_seconds": 30, "updated_at": 1000, "server_time": 1010, "attempt": 2, - "notice": "本次未完成,已安排自动重试。 上次进度:校验报告。 耗时按本次尝试计算。", - }) - repository.batches = [value] - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - detail = dialog.model_views["openai"]["progress_detail"] - assert "第 2 次尝试" in detail.text() and "距下次重试 30 秒" in detail.text() - ticks[0] = 104.0 - dialog._render_progress() - assert "已用时 3 分 00 秒" in detail.text() and "距下次重试 26 秒" in detail.text() - assert "阶段更新于 14 秒前" in detail.text() - assert "本阶段" not in detail.text() - progress = repository.batches[0]["models"]["openai"]["progress"] - progress.update(server_time=1015, wait_remaining_seconds=25) - ticks[0] = 105.0 - dialog._poll() - assert "已用时 3 分 00 秒" in detail.text() and "距下次重试 25 秒" in detail.text() - assert "上次进度:校验报告。" in detail.text() - repository.batches[0]["models"]["openai"].update(status="running", progress={ - "stage": "final", "phase": "waiting", "elapsed_seconds": 0, "stage_elapsed_seconds": 0, - "attempt": 3, "updated_at": 1040, "server_time": 1040, - }) - ticks[0] = 130.0 - dialog._poll() - ticks[0] = 133.0 - dialog._render_progress() - assert "第 3 次尝试" in detail.text() and "已用时 3 秒" in detail.text() - assert "距下次重试" not in detail.text() - dialog.close() - - -@pytest.mark.parametrize("attempt", [None, 0, -1, True, "2", 1_000_001]) -def test_unknown_or_invalid_attempt_count_is_not_invented(attempt: Any) -> None: - view = ai.progress_view({"status": "retry_wait", "progress": {"stage": "retry_wait", "attempt": attempt}}) - assert "次尝试" not in view.detail - - -def test_theme_switch_keeps_the_page_the_drafts_and_every_step(application: QApplication, - immediate: None) -> None: - """The palette swaps in place; nothing the doctor typed or opened is lost.""" - - from doctor_workstation.ui.dialogs import issued_prescription_ai_theme as theme - - dialog = ai.IssuedPrescriptionAiDialog(Repository(), ["*"], prescription_id=801) - dialog.resize(1280, 860) - dialog.show() - application.processEvents() - dialog._goto("gaps") - dialog.model_views["qwen"]["comment"].setPlainText("切换前写的复核意见") - dark = theme.CONSOLE["canvas"] - try: - dialog._switch_theme() - application.processEvents() - assert theme.CONSOLE["canvas"] != dark - assert theme.current_theme() == "light" - assert dialog.model_views["qwen"]["comment"].toPlainText() == "切换前写的复核意见" - assert dialog.tabs.currentWidget() is dialog.tab_pages["gaps"] - assert len(dialog.rail.buttons) == len(ai.NAV_PRIMARY) - assert all(button.isVisible() for button in dialog.rail.buttons.values()) - finally: - dialog._switch_theme() - application.processEvents() - assert theme.CONSOLE["canvas"] == dark - dialog.close() - - -def test_every_step_stays_readable_in_both_palettes(application: QApplication, immediate: None) -> None: - """A selected step paints its own labels: a descendant :checked rule would not reach them.""" - - from doctor_workstation.ui.dialogs import issued_prescription_ai_theme as theme - - dialog = ai.IssuedPrescriptionAiDialog(Repository(), ["*"], prescription_id=801) - dialog.show() - application.processEvents() - rail = dialog.rail - assert theme.CONSOLE["heading"] in rail.names["overview"].styleSheet() - assert theme.CONSOLE["muted"] in rail.names["report"].styleSheet() - rail.set_current("report") - assert theme.CONSOLE["heading"] in rail.names["report"].styleSheet() - assert theme.CONSOLE["muted"] in rail.names["overview"].styleSheet() - dialog.close() - - -def test_native_title_bar_takes_the_console_palette() -> None: - """The frame Windows draws follows the theme, so the dark body does not stop at the caption.""" - - from doctor_workstation.ui.dialogs import issued_prescription_ai_theme as theme - - # DWM wants 0x00BBGGRR, not the #RRGGBB the palette is written in. - assert theme._colorref("#080D18") == 0x180D08 - assert theme._colorref("#FFFFFF") == 0xFFFFFF - - class Handleless: - def winId(self) -> int: - return 0 - - assert theme.apply_window_chrome(Handleless()) is False - - -def test_report_rail_lists_the_saved_sections_and_filters_to_differences( - application: QApplication, immediate: None) -> None: - repository = Repository() - repository.batches[0]["models"]["qwen"]["report"] = {"summary": "两侧一致的概要", "analysis": "千问的分析"} - repository.batches[0]["models"]["openai"]["report"] = {"summary": "两侧一致的概要", "analysis": "OpenAI 的分析"} - dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) - dialog.show() - dialog._goto("report") - application.processEvents() - titles = [dialog.report_toc.itemAt(index).widget().text() - for index in range(dialog.report_toc.count())] - assert "概要" in titles and "综合分析" in titles - both = dialog.model_views["qwen"]["report"].toPlainText() - assert "两侧一致的概要" in both and "千问的分析" in both - dialog._set_report_mode("differences") - application.processEvents() - filtered = dialog.model_views["qwen"]["report"].toPlainText() - assert "千问的分析" in filtered - assert "两侧一致的概要" not in filtered # 两侧完全相同的段落不算差异 - dialog._set_report_mode("qwen") - application.processEvents() - assert not dialog.report_columns["openai"].isVisible() - dialog._set_report_mode("both") - application.processEvents() - assert dialog.report_columns["openai"].isVisible() - dialog.close() +"""Dual-model report and API contracts, exercised offscreen without network access.""" + +from __future__ import annotations + +import os +import socket +from copy import deepcopy +from datetime import datetime +from typing import Any +from uuid import UUID + +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 +from doctor_workstation.services.repository import RemoteDoctorRepository +from doctor_workstation.ui.dialogs import issued_prescription_ai as ai +from doctor_workstation.ui.dialogs import prescription as editor_module +from doctor_workstation.ui.pages import prescriptions as page_module + + +def batch(batch_id: int = 40, prescription_id: int = 801, status: str = "running") -> dict[str, Any]: + return { + "id": batch_id, "prescription_id": prescription_id, "prescription_revision": 2, "agreement_visible": True, + "patient_id": 301, "diagnosis_id": 501, "status": status, + "validity": "current", "comparison_type": "independent_baseline", + "source_summary": {"diagnosis_count": 2, "attachment_count": 4}, + "missing": [{"source": "tongue", "reason": "第4张图片不可读"}], + "cutoff_at": "2026-09-09 10:00:00", "created_at": "2026-09-09 10:01:00", + "models": { + "qwen": { + "status": "succeeded", "report": {"summary": "已保存千问分析 "}, + "candidate": {"status": "available_for_review", "herbs": [{"name": "黄芪", "dosage": 12, "unit": "g", "dose_basis": "每剂", "formula_type": "主方"}]}, + "comparison": {"status": "comparable", "score": 0, "herb_score": 0, "algorithm_version": "v1", "rows": [{"name": "黄芪", "doctor_dose": None, "candidate_dose": 12, "contribution": 0}], "usage_differences": ["疗程需复核"]}, + "coverage": {"status": "incomplete", "manifest": [{"name": "舌象4", "status": "unreadable"}]}, + "review": {"status": "needs_information", "comment": "需补充清晰舌象"}, + }, + "openai": {"status": "running", "report": None, "candidate": None, "comparison": None, "coverage": {"status": "pending"}}, + }, + } + + +class Repository(DemoDoctorRepository): + def __init__(self) -> None: + super().__init__() + self.calls: list[tuple[str, Any]] = [] + self.batches = [batch()] + self.enabled = True + self.agreement_visible = True + + def get_prescription_ai_capabilities(self) -> dict[str, Any]: + return {"agreement_visible": self.agreement_visible, "can_manage_visibility": False} + + def list_prescription_ai_reports(self, **params: Any) -> dict[str, Any]: + self.calls.append(("reports", params)) + return {"agreement_visible": self.agreement_visible, "enabled": self.enabled, "lists": deepcopy(self.batches), "count": len(self.batches), "page_no": 1, "page_size": 20} + + def get_prescription_ai_report(self, batch_id: int) -> dict[str, Any]: + self.calls.append(("detail", batch_id)) + return deepcopy(next(row for row in self.batches if row["id"] == batch_id)) + + def retry_prescription_ai(self, batch_id: int, model_key: str) -> dict[str, Any]: + self.calls.append(("retry", (batch_id, model_key))) + return {"batch_id": batch_id, "status": "queued"} + + def regenerate_prescription_ai(self, prescription_id: int, reason: str) -> dict[str, Any]: + self.calls.append(("regenerate", (prescription_id, reason))) + return {"batch_id": 41, "status": "queued"} + + def review_prescription_ai(self, batch_id: int, model_key: str, status: str, comment: str) -> dict[str, Any]: + self.calls.append(("review", (batch_id, model_key, status, comment))) + return {"saved": True} + + def list_prescription_ai_statuses(self, ids: list[int]) -> dict[str, Any]: + self.calls.append(("statuses", list(ids))) + return {"agreement_visible": self.agreement_visible, "enabled": self.enabled, "items": [{"agreement_visible": self.agreement_visible, "prescription_id": value, "batch_id": 40, "status": "running", "validity": "current", "comparison_type": "independent_baseline", "models": {"qwen": {"status": "succeeded", "score": 0, "comparison_status": "comparable"}, "openai": {"status": "running", "score": None}}} for value in ids] if self.enabled else []} + + +@pytest.fixture(scope="module") +def application() -> QApplication: + return QApplication.instance() or QApplication([]) + + +@pytest.fixture(autouse=True) +def no_network(monkeypatch: pytest.MonkeyPatch) -> None: + def denied(*_args: Any, **_kwargs: Any) -> None: + pytest.fail("These tests must never contact external systems") + monkeypatch.setattr(socket.socket, "connect", denied) + monkeypatch.setattr(socket.socket, "connect_ex", denied) + monkeypatch.setattr(socket, "create_connection", denied) + + +@pytest.fixture +def immediate(monkeypatch: pytest.MonkeyPatch) -> None: + def run(function: Any, *, on_success: Any = None, on_error: Any = None, on_finished: Any = None) -> object: + try: + result = function() + except Exception as error: + if on_error: + on_error(error) + else: + raise + else: + if on_success: + on_success(result) + finally: + if on_finished: + on_finished() + return object() + for module in (ai, page_module, editor_module): + monkeypatch.setattr(module, "run_async", run) + + +@pytest.mark.parametrize(("value", "expected"), [(None, "—"), (0, "0%"), (100, "100%"), (42.3, "42%"), (float("nan"), "—"), (float("inf"), "—"), (False, "—"), (-1, "—")]) +def test_percentage_never_turns_missing_into_zero(value: Any, expected: str) -> None: + 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) + dialog.show() + application.processEvents() + assert [call[0] for call in repository.calls] == ["reports", "detail"] + assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() + assert dialog.model_views["qwen"]["score"].text() == "0.0%" + assert dialog.model_views["openai"]["score"].text() == "—" + assert "资料不全" in dialog.model_views["qwen"]["title"].text() + assert "黄芪" in dialog.model_views["qwen"]["candidate"].toPlainText() + assert "医生剂量" in dialog.model_views["qwen"]["comparison"].toPlainText() + assert "第4张图片不可读" in dialog.model_views["qwen"]["sources"].toPlainText() + assert "<script>" in dialog.model_views["qwen"]["report"].toHtml() + assert dialog._timer.isActive() + assert not dialog.model_views["qwen"]["retry"].isEnabled() + assert not dialog.model_views["openai"]["retry"].isEnabled() + dialog.hide() + assert not dialog._timer.isActive() + calls = list(repository.calls) + dialog._poll() + assert repository.calls == calls + + +def test_report_open_and_poll_never_show_auxiliary_windows(application: QApplication, immediate: None) -> None: + shown_windows = [] + + class WindowObserver(QObject): + def eventFilter(self, watched: QObject, event: QEvent) -> bool: + if event.type() == QEvent.Type.Show and isinstance(watched, QWidget) and watched.isWindow(): + shown_windows.append((watched.metaObject().className(), watched.windowTitle())) + return False + + observer = WindowObserver() + application.installEventFilter(observer) + dialog = None + try: + repository = Repository() + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + application.processEvents() + initial_windows = list(shown_windows) + shown_windows.clear() + dialog.tabs.setCurrentIndex(3) + dialog.model_views["qwen"]["comment"].setPlainText("正在填写的复核意见") + for _ in range(3): + dialog._timer.timeout.emit() + dialog._progress_timer.timeout.emit() + application.processEvents() + assert len([call for call in repository.calls if call[0] == "detail"]) == 4 + assert shown_windows == [], "Polling must not show even transient top-level widgets" + assert initial_windows == [("IssuedPrescriptionAiDialog", dialog.windowTitle())] + assert dialog.tabs.currentIndex() == 3 + assert dialog.model_views["qwen"]["comment"].toPlainText() == "正在填写的复核意见" + assert dialog.chip_row.count() == 2 + assert all(dialog.chip_row.itemAt(index).widget().isVisible() for index in range(2)) + assert dialog._timer.isActive() and dialog._progress_timer.isActive() + finally: + application.removeEventFilter(observer) + if dialog is not None: + dialog.close() + + +def test_navigation_names_every_destination_once(application: QApplication, immediate: None) -> None: + """A duplicated tab name makes the navigation unreadable; the live progress lives in the one tab.""" + dialog = ai.IssuedPrescriptionAiDialog(Repository(), ["*"], prescription_id=801) + dialog.show() + application.processEvents() + names = [dialog.tabs.tabText(index) for index in range(dialog.tabs.count())] + assert len(names) == len(set(names)), names + assert names.count("处理进度") == 1 + # Those pages are hosted in a scroll area, so the tab holds the host, not the page itself. + for key in ("per_herb", "gaps", "history"): + assert dialog.tabs.indexOf(dialog.tab_pages[key]) >= 0 + bar = dialog.model_views["qwen"]["progress_bar"] + assert dialog.pipeline_page.isAncestorOf(bar) + assert dialog.pipeline_page.stage_labels["qwen"].isHidden() + dialog.close() + + +@pytest.mark.parametrize(("width", "height"), [(1280, 860), (1024, 700), (940, 640)]) +def test_prescription_workspace_is_the_primary_view(application: QApplication, immediate: None, width: int, height: int) -> None: + dialog = ai.IssuedPrescriptionAiDialog(Repository(), ["*"], prescription_id=801) + dialog.resize(width, height) + dialog.show() + application.processEvents() + assert (dialog.width(), dialog.height()) == (width, height) + assert dialog.tabs.currentWidget() is dialog.comparison_panel + assert dialog.tabs.tabText(0) == "对比总览" + assert dialog.comparison_panel.isVisible() + assert dialog.tabs.height() > height * 0.28 + assert dialog.model_views["qwen"]["comment"].isVisible() + # The chart strip is on the first screen but must never outgrow its budget, and a model + # without a comparable score shows no filled bar. + assert dialog.model_views["qwen"]["agreement_bar"].value() == 0 + assert dialog.model_views["openai"]["agreement_bar"].isHidden() + assert dialog.model_views["qwen"]["gauge"].accessibleDescription() == "0.0%" + assert dialog.model_views["openai"]["gauge"].accessibleDescription() == "暂无可比结果" + dialog.close() + + +@pytest.mark.parametrize(("width", "height"), [(1440, 940), (1280, 860), (1024, 700), (940, 640)]) +def test_review_controls_remain_inside_the_sidebar(application: QApplication, immediate: None, + width: int, height: int) -> None: + repository = Repository() + model = repository.batches[0]["models"]["qwen"] + herb = model["candidate"]["herbs"][0] + model["comparison"]["rows"][0].update(key="黄芪", doctor={**herb, "dosage": 16}, candidate=herb) + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.resize(width, height) + dialog.show() + panel = dialog.comparison_panel + for _ in range(4): + application.processEvents() + assert dialog.nav_buttons["overview"].isChecked() + for key in ai.MODELS: + dialog.review_model.setCurrentIndex(0 if key == "qwen" else 1) + application.processEvents() + views = dialog.model_views[key] + for control in (dialog.review_model, views["review_state"], views["comment"], views["save"]): + assert control.isVisible() + bounds = QRect(control.mapTo(panel.checklist, control.rect().topLeft()), control.size()) + assert panel.checklist.rect().contains(bounds), (key, control.accessibleName(), bounds) + assert ai.MODELS[key] in dialog.save_review_button.toolTip() + assert panel.checklist.isVisible() + dialog.close() + + +def test_hero_band_carries_the_frozen_identity_and_yields_on_short_windows(application: QApplication, immediate: None) -> None: + repository = Repository() + repository.batches[0]["doctor_snapshot"] = { + "patient": {"name": "测试患者", "gender_label": "女", "age": 58}, + "diagnosis": {"clinical_diagnosis": "消渴病 气阴两虚"}, + "prescription": {"prescription_type": "浓缩水丸", "dose_count": 1, "dose_unit": "剂"}, + } + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.resize(1280, 860) + dialog.show() + application.processEvents() + assert "测试患者 · 女 · 58 岁" in dialog.identity.text() + assert "消渴病 气阴两虚" in dialog.identity.text() + assert "浓缩水丸 · 1 剂" in dialog.identity.text() + assert dialog.fact_values["basis"].text() == "同单位 · 每剂" + assert dialog.fact_values["prescription"].text() == "801 / 501" + dialog.resize(1024, 700) + application.processEvents() + assert dialog.fact_values["batch"].text() == "#40" + dialog.close() + + +def test_hero_band_shows_dashes_when_the_snapshot_is_not_deployed(application: QApplication, immediate: None) -> None: + repository = Repository() + repository.batches[0].pop("doctor_snapshot", None) + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.resize(1280, 860) + dialog.show() + application.processEvents() + assert dialog.identity.text() == "尚无冻结快照" + assert dialog.fact_values["prescription"].text().startswith("801") + dialog.close() + + +def test_failed_model_states_the_reason_and_offers_its_own_retry(application: QApplication, immediate: None) -> None: + repository = Repository() + repository.batches[0]["models"]["openai"].update(status="failed", error_code="INVALID_REPORT_OUTPUT", + error_message="INVALID_REPORT_OUTPUT") + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + application.processEvents() + assert dialog.model_views["openai"]["failure"].isVisible() + text = dialog.model_views["openai"]["failure_text"].text() + assert "OpenAI 失败" in text and "格式校验" in text and "原资料快照" in text + assert "INVALID_REPORT_OUTPUT" not in text + assert dialog.model_views["openai"]["retry"].isEnabled() + assert dialog.model_views["openai"]["retry"].isVisible() + # A model that is still running never shows a failure row. + dialog.model_views["openai"]["retry"].click() + application.processEvents() + assert ("retry", (40, "openai")) in repository.calls + dialog.close() + + +def test_exhausted_manual_retries_point_at_regeneration_instead_of_retry(application: QApplication, immediate: None) -> None: + repository = Repository() + repository.batches[0]["models"]["openai"].update(status="failed", error_code="UPSTREAM_TIMEOUT", + error_message="UPSTREAM_TIMEOUT", manual_retries=2) + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + application.processEvents() + 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": "已保存报告"}) + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + application.processEvents() + dialog.model_views["qwen"]["comment"].setPlainText("千问复核草稿") + dialog.review_model.setCurrentIndex(1) + dialog.model_views["openai"]["comment"].setPlainText("OpenAI复核草稿") + dialog.model_views["openai"]["review_state"].setCurrentIndex(3) + dialog._poll() + application.processEvents() + assert dialog.review_model.currentData() == "openai" + assert dialog.model_views["qwen"]["comment"].toPlainText() == "千问复核草稿" + assert dialog.model_views["openai"]["comment"].toPlainText() == "OpenAI复核草稿" + dialog.save_review_button.click() + assert ("review", (40, "openai", "reviewed", "OpenAI复核草稿")) in repository.calls + assert not any(call[0] == "review" and call[1][1] == "qwen" for call in repository.calls) + dialog.close() + + +def test_workspace_links_reach_existing_supporting_reports(application: QApplication, immediate: None) -> None: + dialog = ai.IssuedPrescriptionAiDialog(Repository(), ["*"], prescription_id=801) + dialog.show() + # Each link opens the composed page that answers it, not the raw saved text. + for field, key in (("report", "report"), ("candidate", "candidate"), ("comparison", "per_herb"), + ("sources", "gaps"), ("progress", "pipeline"), ("doctor", "original")): + dialog.comparison_panel.open_report.emit(field) + assert dialog.tabs.currentWidget() is dialog.tab_pages[key], field + dialog.nav_buttons["overview"].click() + assert dialog.tabs.currentWidget() is dialog.comparison_panel + assert dialog.nav_buttons["overview"].isChecked() + assert not dialog.nav_buttons["gaps"].isChecked() + dialog.nav_buttons["per_herb"].click() + assert dialog.tabs.currentWidget() is dialog.tab_pages["per_herb"] + dialog.close() + + +def test_retry_and_review_target_only_selected_model(application: QApplication, immediate: None) -> None: + repository = Repository() + repository.batches[0]["status"] = "partial" + repository.batches[0]["models"]["openai"].update(status="failed", error_code="timeout", error_message="模型超时") + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + assert dialog.model_views["openai"]["retry"].isEnabled() + assert not dialog._timer.isActive() + dialog._retry("openai") + assert ("retry", (40, "openai")) in repository.calls + dialog.model_views["qwen"]["review_state"].setCurrentIndex(3) + dialog.model_views["qwen"]["comment"].setPlainText("已核对逐味差异") + dialog._review("qwen") + assert ("review", (40, "qwen", "reviewed", "已核对逐味差异")) in repository.calls + assert not any(call[0] == "regenerate" for call in repository.calls) + dialog.close() + + +def test_history_and_hidden_dialog_ignore_late_detail(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: + repository = Repository() + repository.batches.append(batch(41)) + repository.batches[1]["models"]["qwen"]["report"] = {"summary": "第二批报告"} + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + pending = [] + monkeypatch.setattr(ai, "run_async", lambda function, **callbacks: pending.append((function, callbacks))) + dialog._poll() + assert len(pending) == 1 + old_generation = dialog._generation + dialog.history.setCurrentIndex(1) + assert dialog._generation > old_generation + old_function, old_callbacks = pending[0] + old_callbacks["on_success"](old_function()) + assert dialog._batch == {} + new_function, new_callbacks = pending[1] + new_callbacks["on_success"](new_function()) + assert dialog._batch["id"] == 41 + assert "第二批报告" in dialog.model_views["qwen"]["report"].toPlainText() + dialog.hide() + new_callbacks["on_success"](batch(41)) + assert "第二批报告" in dialog.model_views["qwen"]["report"].toPlainText() + + +def test_wrong_patient_batch_is_not_displayed(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: + repository = Repository() + wrong_patient = batch() + wrong_patient["patient_id"] = 999 + monkeypatch.setattr(repository, "get_prescription_ai_report", lambda _batch_id: wrong_patient) + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], diagnosis_id=501) + dialog.show() + assert repository.calls[0][1]["diagnosis_id"] == 501 + assert dialog._batch == {} + assert "归属" in dialog.message.text() + assert not dialog.model_views["qwen"]["report"].toPlainText() + dialog.close() + + +def test_patient_history_accepts_other_authorized_visits(application: QApplication, immediate: None) -> None: + repository = Repository() + repository.batches[0]["diagnosis_id"] = 499 + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], diagnosis_id=501) + dialog.show() + assert dialog._batch["diagnosis_id"] == 499 + assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() + dialog.close() + + +def test_disabled_generation_keeps_history_readable(application: QApplication, immediate: None) -> None: + repository = Repository() + repository.enabled = False + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() + assert not dialog.regenerate_button.isEnabled() + assert "未启用" in dialog.message.text() + dialog.close() + + +def test_view_permission_cannot_mutate(application: QApplication, immediate: None) -> None: + repository = Repository() + permissions = ["tcm.prescriptionAi/reports", "tcm.prescriptionAi/detail"] + dialog = ai.IssuedPrescriptionAiDialog(repository, permissions, prescription_id=801) + dialog.show() + assert dialog.regenerate_button.isHidden() + dialog._review("qwen") + dialog._retry("openai") + assert not any(call[0] in {"review", "retry", "regenerate"} for call in repository.calls) + dialog.close() + + +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) + # 无数据时只显示灰色占位提示,不得带出任何分析内容。 + placeholder = item.data(page_module._ROLE_AI_PLACEHOLDER) or "" + expected = "" if placeholder == "—" else placeholder + assert item.text() == "" + assert item.toolTip() == expected + assert (item.data(Qt.ItemDataRole.AccessibleTextRole) or "") == expected + assert "%" not in placeholder + + +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() + application.processEvents() + statuses = [call for call in repository.calls if call[0] == "statuses"] + assert statuses and set(statuses[-1][1]) <= {801, 802} + assert len(statuses[-1][1]) <= 100 + assert not page.table.isColumnHidden(11) + assert not page.table.isColumnHidden(12) + 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() + assert not page._ai_timer.isActive() + calls = list(repository.calls) + page._load_ai_statuses() + assert repository.calls == calls + + +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)) + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + application.processEvents() + # Demo row 801 contains herbs; row 802 is an empty manual prescription. + assert all(call[1] == [801] for call in repository.calls if call[0] == "statuses") + assert not page.table.isColumnHidden(11) and not page.table.isColumnHidden(12) + page._ai_statuses[802] = batch(prescription_id=802) + page._render_ai_statuses() + for column, hint in ((11, "空白处方"), (12, "")): + item = page.table.item(1, column) + assert item.text() == "" + # 空白处方只在“AI 分析”列显示占位提示,不带出分析内容。 + assert item.toolTip() == item.data(Qt.ItemDataRole.AccessibleTextRole) == hint + assert not any(button.accessibleName() == "AI 报告" for button in page.table.cellWidget(1, 2).findChildren(QPushButton)) + page.table.selectRow(1) + assert page.ai_report_button.isHidden() and not page.ai_report_button.isEnabled() + page._open_ai_report() + 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() + page.ai_report_button.click() + assert opened == [{"prescription_id": 801}] + 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_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}) + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + application.processEvents() + 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) + assert not any(button.accessibleName() == "AI 报告" for button in page.table.cellWidget(0, 2).findChildren(QPushButton)) + + row.update(is_system_auto=0, herbs=[{"name": "黄芪", "dosage": 12}]) + page.refresh() + application.processEvents() + assert ("statuses", [803]) in repository.calls + assert not page.table.isColumnHidden(11) and not page.table.isColumnHidden(12) + assert page.ai_report_button.isVisible() and page.ai_status_notice.isVisible() + assert "千问 0%" in page.table.item(0, 12).text() + assert any(button.accessibleName() == "AI 报告" for button in page.table.cellWidget(0, 2).findChildren(QPushButton)) + page.close() + + +def test_list_disabled_explains_availability_and_keeps_history(application: QApplication, immediate: None) -> None: + repository = Repository() + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + application.processEvents() + 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() + + +def test_list_service_error_is_visible_and_clears_after_recovery(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: + repository = Repository() + + def unavailable(_ids: list[int]) -> dict[str, Any]: + raise RuntimeError("AI service unavailable") + + monkeypatch.setattr(repository, "list_prescription_ai_statuses", unavailable) + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + application.processEvents() + assert page.ai_status_notice.isVisible() + assert "暂不可用" in page.ai_status_notice.text() + 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() + application.processEvents() + 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, 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_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() + + +def test_list_ignores_response_after_filter_generation_changes(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: + repository = Repository() + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + application.processEvents() + callbacks = [] + monkeypatch.setattr(page_module, "run_async", lambda function, **kwargs: callbacks.append((function, kwargs))) + page._load_ai_statuses() + assert callbacks + page._generation += 1 + page._ai_statuses = {} + function, call = callbacks[0] + call["on_success"](function()) + assert page._ai_statuses == {} + page.close() + + +def test_statistics_nulls_and_absent_review_samples(application: QApplication, immediate: None) -> None: + class StatisticsRepository: + def get_prescription_ai_capabilities(self) -> dict[str, Any]: + return {"agreement_visible": True} + + def prescription_ai_statistics(self, *_args: Any) -> dict[str, Any]: + return {"total_count": 3, "patient_count": 2, "doctors": [{"doctor_name": "张医生", "total_count": 3, "patient_count": 2, "models": {"qwen": {"eligible_count": 0, "coverage_rate": 0, "mean": None, "median": None, "excluded_reasons": {"non_independent": 3}}, "openai": {"eligible_count": 1, "coverage_rate": 33.3, "mean": 0, "median": 0}}, "review": {"evaluated_count": 0, "qualified_count": 0, "qualified_rate": None}}]} + dialog = ai.PrescriptionAiStatisticsDialog(StatisticsRepository(), ["*"]) + dialog.show() + text = dialog.report.toPlainText() + assert "均值:—" in text and "均值:0.0%" in text + assert "未建立复核样本" in text + assert "开方事件:3" in dialog.summary.text() + dialog.close() + + +def test_editor_keeps_request_key_for_identical_content_and_preserves_ai_assistance(application: QApplication, immediate: None) -> None: + editor = editor_module.PrescriptionEditorDialog(DemoDoctorRepository(), {"ai_assisted": True}) + first = editor.payload() + assert first["ai_assisted"] is True + assert str(UUID(first["request_key"])) == first["request_key"] + assert first["request_key"] == editor.payload()["request_key"] + editor.patient_name.setText("新患者") + assert first["request_key"] != editor.payload()["request_key"] + editor.close() + unknown = editor_module.PrescriptionEditorDialog(DemoDoctorRepository()) + assert "ai_assisted" not in unknown.payload() + unknown.close() + unconfirmed = editor_module.PrescriptionEditorDialog(DemoDoctorRepository(), {"ai_assisted": False}) + assert "ai_assisted" not in unconfirmed.payload() + unconfirmed.close() + + +def test_repository_exact_read_and_mutation_contracts() -> None: + class Client: + def __init__(self) -> None: + self.calls = [] + def get(self, endpoint: str, params: Any) -> dict[str, Any]: + self.calls.append(("GET", endpoint, params)) + return {"enabled": False, "items": []} + def post(self, endpoint: str, params: Any) -> dict[str, Any]: + self.calls.append(("POST", endpoint, params)) + return {"saved": True} + client = Client() + repository = RemoteDoctorRepository(client) + repository.get_prescription_ai_capabilities() + assert repository.list_prescription_ai_statuses([801, 802, 801]) == {"enabled": False, "items": []} + repository.list_prescription_ai_reports(diagnosis_id=501, page_no=2, page_size=20) + repository.get_prescription_ai_report(40) + assert all(call[0] == "GET" for call in client.calls) + repository.regenerate_prescription_ai(801, "补充病历") + repository.retry_prescription_ai(40, "openai") + repository.review_prescription_ai(40, "qwen", "reviewed", "核对完成") + repository.prescription_ai_statistics("2026-09-01", "2026-09-09", 7) + assert client.calls == [ + ("GET", "tcm.prescriptionAi/capabilities", {}), + ("GET", "tcm.prescriptionAi/statuses", {"ids": "801,802"}), + ("GET", "tcm.prescriptionAi/reports", {"diagnosis_id": 501, "page_no": 2, "page_size": 20}), + ("GET", "tcm.prescriptionAi/detail", {"batch_id": 40}), + ("POST", "tcm.prescriptionAi/regenerate", {"prescription_id": 801, "reason": "补充病历"}), + ("POST", "tcm.prescriptionAi/retry", {"batch_id": 40, "model_key": "openai"}), + ("POST", "tcm.prescriptionAi/review", {"batch_id": 40, "model_key": "qwen", "status": "reviewed", "comment": "核对完成"}), + ("GET", "tcm.prescriptionAi/statistics", {"date_from": "2026-09-01", "date_to": "2026-09-09", "doctor_id": 7}), + ] + with pytest.raises(ValueError): + repository.list_prescription_ai_statuses(list(range(1, 102))) + with pytest.raises(ValueError): + repository.list_prescription_ai_reports(prescription_id=801, diagnosis_id=501) + with pytest.raises(ValueError): + repository.retry_prescription_ai(40, "other") + + +@pytest.mark.parametrize("flag", [False, None, 1, "true"]) +def test_agreement_denied_or_missing_keeps_reports_review_and_retry( + application: QApplication, immediate: None, flag: Any, +) -> None: + repository = Repository() + repository.agreement_visible = flag + value = repository.batches[0] + value["agreement_visible"] = flag + value["models"]["openai"].update(status="failed", error_message="上游超时") + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], diagnosis_id=501, + current_user={"root": 1, "role_ids": [1]}) + dialog.show() + application.processEvents() + assert not dialog._agreement_visible + assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() + assert dialog.model_views["qwen"]["comment"].isEnabled() + assert dialog.model_views["qwen"]["save"].isVisible() + assert dialog.model_views["openai"]["retry"].isVisible() + assert dialog.model_views["openai"]["retry"].isEnabled() + assert dialog.history.count() == 1 + assert dialog.comparison_panel.checklist.isVisible() + assert dialog.comparison_panel.conclusions.isHidden() + assert not dialog.comparison_panel.rows + assert not dialog.comparison_panel.doses.rows + assert dialog.nav_buttons["history"].isHidden() + assert dialog.agreement_note.isHidden() + for key, views in dialog.model_views.items(): + assert not views["score"].text() and not views["score"].toolTip() + assert not views["agreement_bar"].toolTip() and not views["agreement_bar"].accessibleName() + assert views["gauge"]._value is None and not views["gauge"].accessibleDescription() + assert not views["comparison"].toPlainText() + assert "comparison" not in dialog._batch["models"][key] + assert not dialog.agreement.delta.text() and not dialog.agreement.overlap.text() + for key in ("differences", "consensus"): + assert not dialog.rail.focus_values[key].text() + assert dialog.rail.focus_values[key].parentWidget().isHidden() + dialog._goto("per_herb") + assert dialog.tabs.currentWidget() is dialog.tab_pages["candidate"] + assert "黄芪" in dialog.model_views["qwen"]["candidate"].toPlainText() + dialog._goto("comparison_raw") + assert dialog.tabs.currentWidget() is dialog.tab_pages["report"] + dialog._goto("history") + assert dialog.tabs.currentWidget() is dialog.tab_pages["report"] + dialog.close() + + +@pytest.mark.parametrize("missing", ["reports", "history_batch", "detail"]) +def test_each_report_visibility_flag_is_required(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, missing: str) -> None: + repository = Repository() + reports, detail = repository.list_prescription_ai_reports, repository.get_prescription_ai_report + def read_reports(**params: Any) -> dict[str, Any]: + data = reports(**params) + if missing == "reports": + data.pop("agreement_visible") + if missing == "history_batch": + data["lists"][0].pop("agreement_visible") + return data + def read_detail(batch_id: int) -> dict[str, Any]: + data = detail(batch_id) + if missing == "detail": + data.pop("agreement_visible") + return data + monkeypatch.setattr(repository, "list_prescription_ai_reports", read_reports) + monkeypatch.setattr(repository, "get_prescription_ai_report", read_detail) + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + assert not dialog._agreement_visible + assert not dialog.model_views["qwen"]["score"].text() + assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() + dialog.close() + + +def test_agreement_revocation_and_failed_read_clear_cached_views_and_survive_theme( + application: QApplication, immediate: None, +) -> None: + repository = Repository() + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + assert dialog.model_views["qwen"]["score"].text() == "0.0%" + old_batch, old_generation = deepcopy(dialog._batch), dialog._generation + dialog.model_views["qwen"]["comment"].setPlainText("保留复核草稿") + repository.agreement_visible = False + dialog.refresh() + dialog._detail_ready(old_batch, old_generation, 40) + assert not dialog._agreement_visible + assert not dialog.model_views["qwen"]["score"].text() + assert dialog.history_page.table.rowCount() == 0 + assert not dialog.history_page.chart._points + assert dialog.model_views["qwen"]["comment"].toPlainText() == "保留复核草稿" + dialog._switch_theme() + application.processEvents() + assert not dialog._agreement_visible and not dialog.model_views["qwen"]["score"].text() + assert dialog.model_views["qwen"]["comment"].toPlainText() == "保留复核草稿" + dialog._switch_theme() + repository.agreement_visible = True + dialog.refresh() + assert dialog._agreement_visible + dialog._detail_error(RuntimeError("offline"), dialog._generation) + assert not dialog._agreement_visible + assert not dialog.model_views["qwen"]["score"].text() + assert "comparison" not in dialog._batch["models"]["qwen"] + assert "千问分析" in dialog.model_views["qwen"]["report"].toPlainText() + dialog._detail_ready(old_batch, dialog._generation, 40) + assert not dialog._agreement_visible + dialog.close() + + +def test_revoked_agreement_cache_discards_flat_comparison_metadata() -> None: + value = batch() + sentinel = "previous-private-comparison" + value["baseline_exclusions_json"] = sentinel + value["models"]["qwen"].update({ + "reason": sentinel, "comparison_reason_code": sentinel, + "dictionary_version": sentinel, "error_code": "", + }) + value["models"]["openai"].update({ + "error_code": "UPSTREAM_TIMEOUT", "reason": "模型请求超时", + }) + sanitized = ai.agreement_safe_batch(value, False) + assert sentinel not in str(sanitized) + assert "千问分析" in str(sanitized["models"]["qwen"]["report"]) + assert sanitized["models"]["openai"]["reason"] == "模型请求超时" + assert value["models"]["qwen"]["reason"] == sentinel + + +@pytest.mark.parametrize("flag", [False, None, 1, "true"]) +def test_unlisted_account_sees_empty_ai_cells_and_keeps_reports( + application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, flag: Any, +) -> None: + repository = Repository() + repository.agreement_visible = flag + opened = [] + monkeypatch.setattr(page_module, "present_issued_prescription_ai", lambda *_args, **kwargs: opened.append(kwargs)) + page = page_module.PrescriptionsPage(repository, ["*"], {"root": 1}) + try: + page.resize(1366, 800) + page.show() + application.processEvents() + page.table.selectRow(0) + 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)) + page.ai_report_button.click() + assert opened == [{"prescription_id": 801}] + finally: + 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, failed_read: bool, +) -> None: + repository = Repository() + page = page_module.PrescriptionsPage(repository, ["*"], {"root": 1}) + page.resize(1366, 800) + page.show() + application.processEvents() + 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 + 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_empty_ai_columns(page) + assert page.ai_statistics_button.isHidden() + assert page.ai_report_button.isVisible() + assert page._ai_statuses + 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() + + +def test_list_rechecks_completed_scores_after_hide_and_show(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: + repository = Repository() + original = repository.list_prescription_ai_statuses + def statuses(ids: list[int]) -> dict[str, Any]: + data = original(ids) + for row in data["items"]: + row["status"] = "success" + for model in row["models"].values(): + model["status"] = "success" + return data + monkeypatch.setattr(repository, "list_prescription_ai_statuses", statuses) + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + application.processEvents() + assert "0%" in page.table.item(0, 12).text() + before = len([call for call in repository.calls if call[0] == "statuses"]) + page.hide() + page.show() + application.processEvents() + assert len([call for call in repository.calls if call[0] == "statuses"]) > before + assert "0%" in page.table.item(0, 12).text() + page.close() + + +@pytest.mark.parametrize("flag", [False, None, 1, "true"]) +def test_direct_statistics_requires_strict_server_capability(application: QApplication, immediate: None, flag: Any) -> None: + class StatisticsRepository: + calls = 0 + def get_prescription_ai_capabilities(self) -> dict[str, Any]: + return {"agreement_visible": flag, "can_manage_visibility": True} + def prescription_ai_statistics(self, *_args: Any) -> dict[str, Any]: + self.calls += 1 + return {} + repository = StatisticsRepository() + dialog = ai.PrescriptionAiStatisticsDialog(repository, ["*"]) + dialog.show() + assert repository.calls == 0 + assert dialog.panel.isHidden() and not dialog.report.toPlainText() + dialog.close() + + +def test_statistics_failed_capability_clears_old_charts_and_ignores_late_result( + application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch, +) -> None: + repository = ChineseStatisticsRepository() + dialog = ai.PrescriptionAiStatisticsDialog(repository, ["*"]) + dialog.show() + assert dialog.panel.isVisible() and dialog.report.toPlainText() + old_generation = dialog._generation + monkeypatch.setattr(repository, "get_prescription_ai_capabilities", lambda: (_ for _ in ()).throw(RuntimeError("offline"))) + dialog.refresh() + dialog._ready(repository.prescription_ai_statistics(), old_generation) + assert dialog.panel.isHidden() and not dialog.report.toPlainText() + assert not dialog.panel.distribution.has_data() + assert dialog.panel.doctors.rowCount() == 0 + dialog.close() + + +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) == "" + assert ai.state_text(value) == "处方已变更" + assert not ai.batch_running({**value, "status": "running"}) + + +@pytest.mark.parametrize("status", ["preparing", "waiting_sources", "retry_wait", "queued", "running"]) +def test_server_pending_states_continue_polling(status: str) -> None: + assert ai.batch_running({"status": status, "validity": "current"}) + assert not ai.batch_running({"status": status, "validity": "prescription_changed"}) + + +def test_regeneration_selects_new_batch_and_preserves_old_history(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: + repository = Repository() + repository.batches[0]["status"] = "success" + repository.batches[0]["models"]["openai"]["status"] = "success" + def regenerate(prescription_id: int, reason: str) -> dict[str, Any]: + repository.calls.append(("regenerate", (prescription_id, reason))) + repository.batches.insert(0, batch(41)) + return {"batch_id": 41, "status": "queued"} + monkeypatch.setattr(repository, "regenerate_prescription_ai", regenerate) + monkeypatch.setattr(ai.QInputDialog, "getMultiLineText", lambda *_args: ("已补充资料", True)) + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + dialog._regenerate() + assert dialog.history.count() == 2 + assert dialog.history.currentData() == 41 + assert dialog._batch["id"] == 41 + assert dialog._timer.isActive() + assert ("regenerate", (801, "已补充资料")) in repository.calls + dialog.close() + + +def test_list_append_retains_finished_cached_scores(application: QApplication, immediate: None) -> None: + repository = Repository() + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + application.processEvents() + for cached in page._ai_statuses.values(): + cached["status"] = "success" + cached["models"]["openai"].update(status="success", score=62) + calls = len([call for call in repository.calls if call[0] == "statuses"]) + page._apply_result(repository.list_prescriptions(), page._generation, 1) + assert "OpenAI 62%" in page.table.item(0, 12).text() + assert len([call for call in repository.calls if call[0] == "statuses"]) == calls + assert not page._ai_timer.isActive() + page.close() + + +def test_context_menu_targets_clicked_prescription(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() + application.processEvents() + page.table.selectRow(1) + expected_id = page.table.item(0, 0).data(Qt.ItemDataRole.UserRole).id + action = ai_context_action(page) + assert action.isEnabled() + action.trigger() + assert opened == [{"prescription_id": expected_id}] + page._ai_context_menu.close() + page.close() + + +def test_real_server_comparison_rows_keep_both_doses_and_basis() -> None: + rows = ai._comparison_rows([{ + "key": "1|raw|main", "medicine_id": 1, "name": "黄芪", "processing": "生品", "formula_type": "主方", + "administration_route": "口服", "group": "", "doctor": {"dosage": 30, "unit": "g", "dose_basis": "per_dose"}, + "candidate": {"dosage": 15, "unit": "g", "dose_basis": "per_dose"}, + "doctor_dosage": 30, "candidate_dosage": 15, "unit": "g", "dose_basis": "per_dose", + "match_type": "matched", "contribution": 0.5, + }]) + assert rows[0]["doctor_dosage"] == "30 克" + assert rows[0]["candidate_dosage"] == "15 克" + assert rows[0]["dose_basis"] == "per_dose" + assert rows[0]["contribution"] == 0.5 + assert "生品 / 主方 / 口服" in rows[0]["name"] + + +def test_unavailable_candidate_has_reason_and_pending_review_is_disabled(application: QApplication, immediate: None) -> None: + repository = Repository() + repository.batches[0]["models"]["qwen"]["candidate"] = {"status": "withheld_for_risk", "reason": "过敏用药信息待核实", "herbs": []} + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + text = dialog.model_views["qwen"]["candidate"].toPlainText() + assert "因风险暂缓候选用药" in text and "过敏用药信息待核实" in text + assert not dialog.model_views["openai"]["save"].isEnabled() + assert "分析尚未完成" in dialog.model_views["openai"]["candidate"].toPlainText() + dialog.close() + + +def test_preparation_failure_reason_is_visible_without_models(application: QApplication, immediate: None) -> None: + repository = Repository() + repository.batches[0].update(status="blocked", models={}, error_message="患者关联冲突,需要核对诊单", coverage_status="partial") + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + assert "患者关联冲突" in dialog.batch_summary.text() + assert "资料不全" in dialog.batch_summary.text() + assert "患者关联冲突" in dialog.model_views["qwen"]["candidate"].toPlainText() + dialog.close() + + +def test_actual_history_pagination_contract(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: + repository = Repository() + repository.batches = [batch(value) for value in range(61, 40, -1)] + def reports(**params: Any) -> dict[str, Any]: + repository.calls.append(("reports", params)) + page = params["page_no"] + return {"agreement_visible": True, "lists": repository.batches[(page - 1) * 20:page * 20], "count": 21, "page_no": page, "page_size": 20} + monkeypatch.setattr(repository, "list_prescription_ai_reports", reports) + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + assert dialog.history.count() == 20 and dialog.next.isEnabled() + dialog._history_page(1) + assert dialog.history.count() == 1 + assert dialog._batch["id"] == 41 + assert dialog.previous.isEnabled() and not dialog.next.isEnabled() + assert repository.calls[-2] == ("reports", {"prescription_id": 801, "diagnosis_id": 0, "page_no": 2, "page_size": 20}) + dialog.close() + + +@pytest.mark.parametrize(("status", "expected"), [("blank", "尚未开方"), ("not_generated", "尚无分析记录")]) +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) == "" + + +def test_statistics_displays_actual_version_strata_without_filling_null_mean(application: QApplication, immediate: None) -> None: + class StatisticsRepository: + def get_prescription_ai_capabilities(self) -> dict[str, Any]: + return {"agreement_visible": True} + + def prescription_ai_statistics(self, *_args: Any) -> dict[str, Any]: + strata = [{"versions": {"model_version": version, "algorithm_version": "v1", "prompt_version": "p1", "dictionary_version": "d1"}, "count": 1, "mean": mean, "median": mean, "distribution": {"[0,20)": 1 if mean == 0 else 0}, "sample_status": "insufficient_sample"} for version, mean in (("model-1", 0), ("model-2", 80))] + return {"total_count": 2, "patient_count": 1, "doctors": [{"doctor_id": 7, "doctor_name": "张医生", "total_count": 2, "patient_count": 1, "paired_count": 0, "models": {"qwen": {"eligible_count": 2, "coverage_rate": 100, "mean": None, "median": None, "excluded_reasons": {}, "strata": strata}}, "review": {"evaluated_count": 0, "qualified_count": 0, "qualified_rate": None}}]} + dialog = ai.PrescriptionAiStatisticsDialog(StatisticsRepository(), ["*"]) + dialog.show() + text = dialog.report.toPlainText() + assert "双模型共同有效样本:0" in text + assert "整体均值与中位数不合并" in text + assert "model-1" in text and "model-2" in text + assert "均值:—" in text and "均值:0.0%" in text and "均值:80.0%" in text + assert "样本不足" in text and "未建立复核样本" in text + dialog.close() + + +@pytest.mark.parametrize(("code", "expected"), [ + ("SOURCE_HISTORY_VERSIONS_UNAVAILABLE", "来源历史版本无法核验"), + ("ARCHIVE_SYNC_WATERMARK_UNAVAILABLE: chat_records", "归档同步完整性尚未核验:聊天记录"), + ("TRANSCRIPT_NOT_VERIFIED_COMPLETE:call_records:1820", "问诊转写完整性尚未核验:问诊通话(编号:1820)"), + ("TRANSCRIPT_PARTIAL: video_calls:1821", "问诊转写仅部分完成:视频问诊(编号:1821)"), + ("CRITICAL_CLINICAL_FACT_MISSING:clinical.allergy_history", "关键临床资料缺失:临床资料 · 过敏史"), + ("MODEL_FILE_OUTPUT_INVALID", "模型未能正确解析这组附件"), + ("missing_or_unknown_dose_basis", "每剂或每日剂量基准不明确"), + ("review_not_independent", "复核不具独立性"), +]) +def test_metadata_and_historical_composite_reasons_are_chinese(code: str, expected: str) -> None: + assert ai.label(code) == expected + assert expected in ai._html({"missing_information": [code]}) + + +def test_source_labels_keep_exact_ids_and_distinguish_source_kinds() -> None: + fingerprint = "0123456789abcdef" * 4 + payload = {"evidence_references": ["diagnoses:501", "video_calls:1820", "call_records:1820", "file:" + fingerprint], + "source_id": "clinical.pregnancy_history", "redaction_manifest": ["diagnoses:501:doctor_advice"]} + original = deepcopy(payload) + rendered = ai._html(payload) + assert "诊单(编号:501)" in rendered + assert "视频问诊(编号:1820)" in rendered and "问诊通话(编号:1820)" in rendered + assert f"附件(编号:{fingerprint})" in rendered + assert "临床资料 · 妊娠与哺乳情况" in rendered + assert "诊单(编号:501) · 医嘱" in rendered + assert all(raw not in rendered for raw in ("diagnoses:", "video_calls:", "file:", "clinical.", "doctor_advice")) + assert payload == original + + +def test_unknown_metadata_has_chinese_fallback_without_translating_clinical_prose() -> None: + clinical_text = "CT、MRI、HbA1c 6.2%,HbA1c_result 待复查,Follow-up in 2 weeks;unknown" + payload = {"summary": clinical_text, "treatment_advice": "ALT_AST 需结合 COPD 病史评估", + "status": "newphase", "error_code": "FUTURE_FAILURE_CODE", "future_field": 3, + "future_status": "newstate", "future_enum": "new_enum_value", + "missing_information": ["FUTURE_GAP_CODE:future_records:1820"], "source_id": "future_records:1821"} + original = deepcopy(payload) + rendered = ai._html(payload) + assert clinical_text in rendered and "ALT_AST 需结合 COPD 病史评估" in rendered + assert "未识别的系统状态" in rendered and "其他来源(编号:1820)" in rendered + assert "其他来源(编号:1821)" in rendered and "3" in rendered + for raw in ("newphase", "newstate", "new_enum_value", "FUTURE_FAILURE_CODE", "FUTURE_GAP_CODE", "future_field", "future_records"): + assert raw not in rendered + assert payload == original + + +def test_nested_metadata_translates_fields_values_and_retains_all_statistics() -> None: + payload = { + "coverage": {"status": "partial", "source_complete": True, "files": {"file:42": {"status": "unreadable", "version_verified": False}}}, + "source_summary": {"diagnoses_count": 2, "video_calls_count": 3, "source_record_count": 5, "history_versioning": "unavailable"}, + "normalization": {"doctor": {"defaults": [{"field": "unit", "value": "g"}, {"field": "dose_basis", "value": "per_dose"}]}, + "issues": [{"side": "both", "code": "unit_mismatch", "row": 0}], "unit_policy": "spelling_aliases_only_no_quantity_conversion"}, + "exclusion_reasons": {"SOURCE_HISTORY_VERSIONS_UNAVAILABLE": 12, "future_reason_a": 7, "future_reason_b": 8}, + "review": {"sampling_groups": [{"sampling_method": "risk_directed", "outcomes": {"qualified": 2, "needs_revision": 1}}]}, + } + original = deepcopy(payload) + rendered = ai._html(payload) + for expected in ("资料不全", "历史版本无法核验", "诊单数", "视频问诊数", "克", "每剂", "剂量单位不同", "双方", "按风险抽样", "合格", "需修订"): + assert expected in rendered + for count in (12, 7, 8, 0): + assert f"

{count}

" in rendered + assert rendered.count("未识别的系统标识") == 2 + for raw in ("partial", "version_verified", "diagnoses_count", "per_dose", "SOURCE_HISTORY", "future_reason", "risk_directed", "qualified"): + assert raw not in rendered + assert payload == original + + +def test_metadata_and_prose_remain_html_escaped(application: QApplication) -> None: + attack = '' + html = ai._html({"summary": attack, "missing_information": ["TRANSCRIPT_FAILED:call_records:1820 " + attack], + "source_id": "call_records:1820 " + attack, "status": attack}) + assert " None: + candidate = { + "prescription_name": "测试候选方", "dose_basis": "per_dose", "unit": "g", + "herbs": [{"name": "测试药材", "dosage": 12, "formula_type": "主方", + "instructions": "先煎,具体时长由医生复核", "processing": "生品", + "evidence_references": ["diagnoses:501"]}], + "rationale": "保留完整方义", "risk_warnings": ["复核提示 "], + } + html = ai._candidate_html(candidate) + assert html.index("测试药材") < html.index("保留完整方义") + assert "' + value["models"]["qwen"]["progress"]["notice"] = attack + value["models"]["qwen"]["coverage"] = {"source_ids": ["call_records:1820 " + attack]} + repository.batches = [value] + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + views = dialog.model_views["qwen"] + assert views["progress_detail"].textFormat() == Qt.TextFormat.PlainText + assert attack in views["progress_detail"].text() + assert "<script>" in views["sources"].toHtml() + assert " None: + repository = Repository() + 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() + application.processEvents() + item = page.table.item(0, 11) + assert item.text() == "千问 附件 2/5\nOpenAI 生成报告" + assert "本阶段 2/5 组" in item.toolTip() + assert "不代表附件全部读懂" in item.toolTip() + assert page.table.rowHeight(0) >= 2 * page.table.fontMetrics().height() + assert page._ai_timer.isActive() + page.close() + + +@pytest.mark.parametrize("status", ["success", "failed", "cancelled", "partial"]) +def test_terminal_batch_overrides_obsolete_running_model_checkpoint(application: QApplication, immediate: None, status: str) -> None: + repository = Repository() + value = progress_batch() + value["status"] = status + repository.batches = [value] + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + assert not ai.batch_running(value) + assert not dialog._timer.isActive() and not dialog._progress_timer.isActive() + assert "最后记录" in dialog.model_views["openai"]["progress_title"].text() + assert dialog.model_views["openai"]["progress_bar"].maximum() != 0 + dialog.close() + + +@pytest.mark.parametrize(("status", "notice"), [ + ("failed", "处理未完成,请查看失败原因。 上次进度:校验报告。 耗时按本次尝试计算。"), + ("cancelled", "任务已取消。 耗时按本次尝试计算。"), +]) +def test_terminal_progress_preserves_matching_server_failure_notice(status: str, notice: str) -> None: + value = {"status": status, "progress": {"stage": status, "phase": "failed", "notice": notice, "elapsed_seconds": 180, "attempt": 2}} + view = ai.progress_view(value, seconds=45) + assert notice in view.detail and "第 2 次尝试" in view.detail + assert "已用时 3 分 00 秒" in view.detail + assert not view.busy and view.total is None + assert notice in ai.status_tooltip({"models": {"qwen": value}}) + + +@pytest.mark.parametrize("status", ["failed", "cancelled", "success"]) +def test_terminal_progress_discards_obsolete_waiting_notice(status: str) -> None: + view = ai.progress_view({"status": status, "progress": {"stage": "final", "phase": "waiting", "notice": "等待模型返回。正在生成报告。", "elapsed_seconds": 90}}, seconds=45) + assert "等待模型返回" not in view.detail and "正在生成报告" not in view.detail + assert "已用时 1 分 30 秒" in view.detail + assert not view.busy + + +def test_retry_wait_freezes_attempt_duration_while_countdown_advances_and_poll_remains_consistent(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: + ticks = [100.0] + monkeypatch.setattr(ai, "monotonic", lambda: ticks[0]) + repository = Repository() + value = batch(status="running") + value["models"]["openai"].update(status="retry_wait", progress={ + "stage": "retry_wait", "phase": "waiting", "elapsed_seconds": 180, "stage_elapsed_seconds": 0, + "wait_remaining_seconds": 30, "updated_at": 1000, "server_time": 1010, "attempt": 2, + "notice": "本次未完成,已安排自动重试。 上次进度:校验报告。 耗时按本次尝试计算。", + }) + repository.batches = [value] + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + detail = dialog.model_views["openai"]["progress_detail"] + assert "第 2 次尝试" in detail.text() and "距下次重试 30 秒" in detail.text() + ticks[0] = 104.0 + dialog._render_progress() + assert "已用时 3 分 00 秒" in detail.text() and "距下次重试 26 秒" in detail.text() + assert "阶段更新于 14 秒前" in detail.text() + assert "本阶段" not in detail.text() + progress = repository.batches[0]["models"]["openai"]["progress"] + progress.update(server_time=1015, wait_remaining_seconds=25) + ticks[0] = 105.0 + dialog._poll() + assert "已用时 3 分 00 秒" in detail.text() and "距下次重试 25 秒" in detail.text() + assert "上次进度:校验报告。" in detail.text() + repository.batches[0]["models"]["openai"].update(status="running", progress={ + "stage": "final", "phase": "waiting", "elapsed_seconds": 0, "stage_elapsed_seconds": 0, + "attempt": 3, "updated_at": 1040, "server_time": 1040, + }) + ticks[0] = 130.0 + dialog._poll() + ticks[0] = 133.0 + dialog._render_progress() + assert "第 3 次尝试" in detail.text() and "已用时 3 秒" in detail.text() + assert "距下次重试" not in detail.text() + dialog.close() + + +@pytest.mark.parametrize("attempt", [None, 0, -1, True, "2", 1_000_001]) +def test_unknown_or_invalid_attempt_count_is_not_invented(attempt: Any) -> None: + view = ai.progress_view({"status": "retry_wait", "progress": {"stage": "retry_wait", "attempt": attempt}}) + assert "次尝试" not in view.detail + + +def test_theme_switch_keeps_the_page_the_drafts_and_every_step(application: QApplication, + immediate: None) -> None: + """The palette swaps in place; nothing the doctor typed or opened is lost.""" + + from doctor_workstation.ui.dialogs import issued_prescription_ai_theme as theme + + dialog = ai.IssuedPrescriptionAiDialog(Repository(), ["*"], prescription_id=801) + dialog.resize(1280, 860) + dialog.show() + application.processEvents() + dialog._goto("gaps") + dialog.model_views["qwen"]["comment"].setPlainText("切换前写的复核意见") + dark = theme.CONSOLE["canvas"] + try: + dialog._switch_theme() + application.processEvents() + assert theme.CONSOLE["canvas"] != dark + assert theme.current_theme() == "light" + assert dialog.model_views["qwen"]["comment"].toPlainText() == "切换前写的复核意见" + assert dialog.tabs.currentWidget() is dialog.tab_pages["gaps"] + assert len(dialog.rail.buttons) == len(ai.NAV_PRIMARY) + assert all(button.isVisible() for button in dialog.rail.buttons.values()) + finally: + dialog._switch_theme() + application.processEvents() + assert theme.CONSOLE["canvas"] == dark + dialog.close() + + +def test_every_step_stays_readable_in_both_palettes(application: QApplication, immediate: None) -> None: + """A selected step paints its own labels: a descendant :checked rule would not reach them.""" + + from doctor_workstation.ui.dialogs import issued_prescription_ai_theme as theme + + dialog = ai.IssuedPrescriptionAiDialog(Repository(), ["*"], prescription_id=801) + dialog.show() + application.processEvents() + rail = dialog.rail + assert theme.CONSOLE["heading"] in rail.names["overview"].styleSheet() + assert theme.CONSOLE["muted"] in rail.names["report"].styleSheet() + rail.set_current("report") + assert theme.CONSOLE["heading"] in rail.names["report"].styleSheet() + assert theme.CONSOLE["muted"] in rail.names["overview"].styleSheet() + dialog.close() + + +def test_native_title_bar_takes_the_console_palette() -> None: + """The frame Windows draws follows the theme, so the dark body does not stop at the caption.""" + + from doctor_workstation.ui.dialogs import issued_prescription_ai_theme as theme + + # DWM wants 0x00BBGGRR, not the #RRGGBB the palette is written in. + assert theme._colorref("#080D18") == 0x180D08 + assert theme._colorref("#FFFFFF") == 0xFFFFFF + + class Handleless: + def winId(self) -> int: + return 0 + + assert theme.apply_window_chrome(Handleless()) is False + + +def test_report_rail_lists_the_saved_sections_and_filters_to_differences( + application: QApplication, immediate: None) -> None: + repository = Repository() + repository.batches[0]["models"]["qwen"]["report"] = {"summary": "两侧一致的概要", "analysis": "千问的分析"} + repository.batches[0]["models"]["openai"]["report"] = {"summary": "两侧一致的概要", "analysis": "OpenAI 的分析"} + dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=801) + dialog.show() + dialog._goto("report") + application.processEvents() + titles = [dialog.report_toc.itemAt(index).widget().text() + for index in range(dialog.report_toc.count())] + assert "概要" in titles and "综合分析" in titles + both = dialog.model_views["qwen"]["report"].toPlainText() + assert "两侧一致的概要" in both and "千问的分析" in both + dialog._set_report_mode("differences") + application.processEvents() + filtered = dialog.model_views["qwen"]["report"].toPlainText() + assert "千问的分析" in filtered + assert "两侧一致的概要" not in filtered # 两侧完全相同的段落不算差异 + dialog._set_report_mode("qwen") + application.processEvents() + assert not dialog.report_columns["openai"].isVisible() + dialog._set_report_mode("both") + application.processEvents() + assert dialog.report_columns["openai"].isVisible() + dialog.close() + + +def _dispose(page: page_module.PrescriptionsPage) -> None: + # 大列表每行都有操作按钮;不销毁会让后续测试 apply_theme 重新 polish 时极慢。 + page.close() + page.deleteLater() + QApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) + + +class PagedRepository(Repository): + """45 条非空白处方,按 page_no 分页返回,用于验证下拉加载时 AI 列保持稳定。""" + + def __init__(self, total: int = 45) -> None: + super().__init__() + from dataclasses import asdict, is_dataclass + template = page_module.page_items(DemoDoctorRepository.list_prescriptions(self, page_no=1, page_size=20))[0] + template = asdict(template) if is_dataclass(template) else dict(template) + self.rows = [dict(deepcopy(template), id=2000 + index, sn=f"RX{2000 + index}") for index in range(total)] + self.fail_statuses = 0 + + def list_prescriptions(self, page_no: int = 1, page_size: int = 15, **_filters: Any) -> dict[str, Any]: + return {"lists": deepcopy(self.rows[(page_no - 1) * page_size: page_no * page_size]), "count": len(self.rows)} + + def list_prescription_ai_statuses(self, ids: list[int]) -> dict[str, Any]: + if self.fail_statuses: + self.fail_statuses -= 1 + self.calls.append(("statuses_failed", list(ids))) + raise RuntimeError("状态接口超时") + return super().list_prescription_ai_statuses(ids) + + +def _rows_missing_ai(page: page_module.PrescriptionsPage) -> list[int]: + table = page.table + return [table.item(row, 0).data(Qt.ItemDataRole.UserRole)["id"] for row in range(table.rowCount()) + if not table.item(row, 12).text()] + + +def _rows_missing_ai_button(page: page_module.PrescriptionsPage) -> list[int]: + table = page.table + return [table.item(row, 0).data(Qt.ItemDataRole.UserRole)["id"] for row in range(table.rowCount()) + if not any(button.accessibleName() == "AI 报告" for button in table.cellWidget(row, 2).findChildren(QPushButton))] + + +def _scroll_to_end(application: QApplication, page: page_module.PrescriptionsPage) -> None: + bar = page.table.verticalScrollBar() + bar.setValue(bar.maximum()) + QTest.qWait(400) + application.processEvents() + + +def test_scroll_loading_keeps_ai_results_for_every_loaded_row(application: QApplication, immediate: None) -> None: + repository = PagedRepository() + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + try: + QTest.qWait(400) + assert _rows_missing_ai(page) == [] + for _ in range(4): + _scroll_to_end(application, page) + assert page.table.rowCount() == 45 + # 快速下拉越过的行、压在视口边缘的行也必须拿到结果,不能留空。 + assert _rows_missing_ai(page) == [] + assert _rows_missing_ai_button(page) == [] + finally: + _dispose(page) + + +def test_transient_status_failure_keeps_shown_results_and_retries(application: QApplication, immediate: None) -> None: + repository = PagedRepository() + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + try: + QTest.qWait(400) + shown = page.table.item(0, 12).text() + assert shown + repository.fail_statuses = 1 + _scroll_to_end(application, page) + assert any(call[0] == "statuses_failed" for call in repository.calls) + # 一次失败不能清空已显示的分析结果,也不能让行内“AI”按钮消失。 + assert page.table.item(0, 12).text() == shown + assert _rows_missing_ai_button(page) == [] + assert "暂不可用" not in page.ai_status_notice.text() + page._ai_timer.timeout.emit() + application.processEvents() + QTest.qWait(400) + assert _rows_missing_ai(page) == [] + finally: + _dispose(page) + + +def test_refresh_never_blanks_ai_columns_or_row_buttons(application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch) -> None: + repository = PagedRepository(total=10) + page = page_module.PrescriptionsPage(repository, ["*"]) + page.resize(1366, 800) + page.show() + try: + QTest.qWait(400) + assert _rows_missing_ai(page) == [] + seen: list[tuple[list[int], list[int]]] = [] + original = page._render_ai_statuses + + def record() -> None: + original() + seen.append((_rows_missing_ai(page), _rows_missing_ai_button(page))) + + monkeypatch.setattr(page, "_render_ai_statuses", record) + page.refresh() + QTest.qWait(400) + page.hide() + page.show() + QTest.qWait(400) + assert seen + assert all(missing == [] and no_button == [] for missing, no_button in seen) + finally: + _dispose(page) diff --git a/app/tests/test_window_fullscreen.py b/app/tests/test_window_fullscreen.py new file mode 100644 index 000000000..95f42e655 --- /dev/null +++ b/app/tests/test_window_fullscreen.py @@ -0,0 +1,245 @@ +"""独立窗口全屏查看:切换、快捷键与退出后的几何 / 停靠状态恢复(offscreen,全程离线)。""" + +from __future__ import annotations + +import os + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +import pytest +from PySide6.QtCore import QRect +from PySide6.QtTest import QTest +from PySide6.QtWidgets import QApplication, QDialog, QLabel, QVBoxLayout + +from doctor_workstation.core.permissions import PermissionSet +from doctor_workstation.services.demo_repository import DEMO_PERMISSIONS, DemoDoctorRepository +from doctor_workstation.ui.fullscreen import ( + FULLSCREEN_ENTER_TEXT, + FULLSCREEN_EXIT_TEXT, + install_window_fullscreen, + window_fullscreen_controller, +) +from doctor_workstation.ui.shell_spatial import SpatialShellWindow +from doctor_workstation.ui.theme import apply_theme + + +def _settle(app: QApplication, rounds: int = 8) -> None: + for _ in range(rounds): + app.processEvents() + QTest.qWait(8) + + +@pytest.fixture(scope="module") +def application() -> QApplication: + app = QApplication.instance() or QApplication([]) + apply_theme(app) + return app + + +def _plain_dialog() -> QDialog: + dialog = QDialog() + dialog.setProperty("doctorSkipOpenGeometry", True) + layout = QVBoxLayout(dialog) + layout.addWidget(QLabel("诊断与药方 · AI 分析报告", dialog)) + return dialog + + +def test_controller_toggles_fullscreen_and_restores_geometry(application: QApplication) -> None: + dialog = _plain_dialog() + dialog.show() + dialog.setGeometry(120, 90, 640, 480) + _settle(application) + original = QRect(dialog.geometry()) + controller = install_window_fullscreen(dialog) + assert install_window_fullscreen(dialog) is controller + states: list[bool] = [] + controller.toggled.connect(states.append) + try: + # 非全屏时 Esc 不被拦截,保留对话框原有的取消语义。 + assert controller.toggle_shortcut.isEnabled() + assert not controller.escape_shortcut.isEnabled() + + controller.toggle_shortcut.activated.emit() # 模拟 F11 + _settle(application) + assert dialog.isFullScreen() + assert controller.escape_shortcut.isEnabled() + assert controller.saved_geometry == original + + controller.escape_shortcut.activated.emit() # 模拟 Esc + _settle(application) + assert not dialog.isFullScreen() + assert dialog.isVisible() + assert dialog.geometry() == original + assert not controller.escape_shortcut.isEnabled() + assert states == [True, False] + + # F11 再按两次:进入后再退出,同样回到原位。 + controller.toggle() + _settle(application) + controller.toggle() + _settle(application) + assert not dialog.isFullScreen() + assert dialog.geometry() == original + finally: + dialog.close() + dialog.deleteLater() + + +def test_controller_restores_maximized_state(application: QApplication) -> None: + dialog = _plain_dialog() + dialog.setGeometry(100, 100, 600, 420) + dialog.showMaximized() + _settle(application) + controller = install_window_fullscreen(dialog) + try: + controller.enter() + _settle(application) + assert dialog.isFullScreen() + controller.exit() + _settle(application) + assert not dialog.isFullScreen() + assert dialog.isMaximized() + finally: + dialog.close() + dialog.deleteLater() + + +def test_top_level_business_dialog_gets_fullscreen_on_show(application: QApplication) -> None: + dialog = _plain_dialog() + dialog.resize(700, 500) + try: + dialog.show() + _settle(application) + controller = window_fullscreen_controller(dialog) + assert controller is not None + controller.enter() + _settle(application) + assert dialog.isFullScreen() + controller.exit() + _settle(application) + assert not dialog.isFullScreen() + finally: + dialog.close() + dialog.deleteLater() + + +@pytest.fixture() +def shell(application: QApplication): + repo = DemoDoctorRepository() + session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) + window = SpatialShellWindow( + repo, + {"session": session, "user": session.user, "demo_mode": True}, + PermissionSet(DEMO_PERMISSIONS), + ) + window.resize(1520, 920) + window.show() + _settle(application, 24) + try: + yield window + finally: + window.wing_manager.close_all() + window.close() + window.deleteLater() + _settle(application, 4) + + +def test_docked_wing_fullscreen_and_restores_dock(shell, application: QApplication) -> None: + shell._open_active_patient_ai_report() + _settle(application) + wm = shell.wing_manager + header = wm.card.header + assert wm.is_open and wm.mode == "docked" and wm.side == "right" + assert header.fullscreen_btn.text() == FULLSCREEN_ENTER_TEXT + shell_geom = QRect(shell.geometry()) + + header.fullscreen_btn.click() + _settle(application) + assert wm.is_fullscreen + assert wm.sidecar is not None and wm.sidecar.isFullScreen() + assert wm.card.window() is wm.sidecar + assert header.fullscreen_btn.text() == FULLSCREEN_EXIT_TEXT + assert header.fullscreen_btn.isChecked() + # 全屏下卡片铺满整个窗口,内容不再被挤压。 + assert wm.card.width() >= wm.sidecar.width() - 2 + assert not shell.right_wing_dock.isVisible() + + # 全屏时 Esc 只退出全屏,不关闭视窗。 + wm._on_escape() + _settle(application) + assert wm.is_open + assert not wm.is_fullscreen + assert wm.mode == "docked" and wm.side == "right" + assert shell.right_wing_dock.isVisible() + assert wm.card.window() is shell + assert not wm.sidecar.isVisible() + assert header.fullscreen_btn.text() == FULLSCREEN_ENTER_TEXT + assert not header.fullscreen_btn.isChecked() + assert shell.geometry() == shell_geom + + # 非全屏时 Esc 仍然关闭视窗。 + wm._on_escape() + _settle(application) + assert not wm.is_open + + +def test_left_sidecar_fullscreen_restores_side_mode_and_geometry( + shell, application: QApplication +) -> None: + shell._open_active_patient_ai_report() + _settle(application) + wm = shell.wing_manager + wm.set_side("left") + wm.set_mode("sidecar") + _settle(application) + sidecar = wm.sidecar + assert sidecar is not None and sidecar.isVisible() + sidecar.setGeometry(sidecar.x(), sidecar.y(), 460, 700) + _settle(application) + before = QRect(sidecar.geometry()) + + wm.toggle_fullscreen() # F11 与按钮共用同一入口 + _settle(application) + assert sidecar.isFullScreen() + assert wm.card.header.left_btn.isChecked() + + wm.toggle_fullscreen() + _settle(application) + assert not sidecar.isFullScreen() + assert wm.mode == "sidecar" and wm.side == "left" + assert sidecar.geometry() == before + assert wm.card.header.detach_btn.text() == "↙ 嵌回主窗" + + +def test_switching_side_while_fullscreen_exits_first(shell, application: QApplication) -> None: + shell._open_active_patient_ai_report() + _settle(application) + wm = shell.wing_manager + wm.enter_fullscreen() + _settle(application) + assert wm.is_fullscreen + + wm.card.header.left_btn.click() + _settle(application) + assert not wm.is_fullscreen + assert wm.mode == "docked" and wm.side == "left" + assert shell.left_wing_dock.isVisible() + assert not wm.sidecar.isVisible() + + +def test_close_wing_while_fullscreen_restores_placement(shell, application: QApplication) -> None: + shell._open_active_patient_ai_report() + _settle(application) + wm = shell.wing_manager + wm.enter_fullscreen() + _settle(application) + wm.close_wing() + _settle(application) + assert not wm.is_fullscreen + assert not wm.sidecar.isVisible() + assert wm.mode == "docked" + + shell._open_active_patient_ai_report() + _settle(application) + assert wm.mode == "docked" and shell.right_wing_dock.isVisible() + assert wm.card.header.fullscreen_btn.text() == FULLSCREEN_ENTER_TEXT