i
This commit is contained in:
gr
2026-10-22 11:12:29 +08:00
480 changed files with 9840 additions and 953 deletions
+1 -1
View File
@@ -3,7 +3,7 @@
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
# Single source of truth for runtime, package, installer, and executable versions.
__version__ = "1.4.5"
__version__ = "1.4.8"
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
@@ -12,6 +12,7 @@ from urllib.parse import urljoin, urlsplit, urlunsplit
import httpx
from doctor_workstation import __version__
from doctor_workstation.core.errors import (
ApiBusinessError,
ApiHttpError,
@@ -483,6 +484,7 @@ class ApiClient:
result = {
"Accept": "application/json",
"version": self.API_VERSION,
"User-Agent": f"ZytDoctorWorkstation/{__version__}",
}
if json_content_type:
result["Content-Type"] = "application/json;charset=UTF-8"
+376
View File
@@ -0,0 +1,376 @@
"""Shared, display-only normalization of archived chat messages and IM events."""
from __future__ import annotations
import json
import math
import re
from collections.abc import Mapping
from datetime import date, datetime
from typing import Any, NamedTuple
class ChatItem(NamedTuple):
variant: str
role: str
text: Any
title: str
detail: str
time_text: str
tone: str
marker: str
def _first_value(source: Any, *keys: str, default: Any = None) -> Any:
for key in keys:
if isinstance(source, Mapping):
value = source.get(key)
else:
value = getattr(source, key, None)
raw = getattr(source, "raw", None)
if value is None and isinstance(raw, Mapping):
value = raw.get(key)
if value is not None and value != "":
return value
return default
def _as_int(value: Any, default: int = 0) -> int:
try:
return int(value)
except (TypeError, ValueError, OverflowError):
return default
def _truthy(value: Any) -> bool:
if isinstance(value, bool):
return value
return str(value or "").strip().lower() in {"1", "true", "yes", "on", "是", "有"}
def format_chat_time(value: Any, *, include_date: bool = False) -> str:
"""Show actual archive times; accept Unix seconds/milliseconds and ISO dates."""
if value is None or value == "" or isinstance(value, bool):
return ""
pattern = "%Y-%m-%d %H:%M" if include_date else "%H:%M"
if isinstance(value, datetime):
return value.strftime(pattern)
if isinstance(value, date):
return value.isoformat()
text = str(value).strip()
if not text:
return ""
if isinstance(value, (int, float)) or re.fullmatch(r"[+-]?\d+(?:\.\d+)?", text):
numeric = float(value)
if not math.isfinite(numeric) or numeric <= 0:
return ""
if numeric >= 10_000_000_000:
numeric /= 1000
try:
return datetime.fromtimestamp(numeric).strftime(pattern)
except (OverflowError, OSError, ValueError):
return ""
try:
moment = datetime.fromisoformat(text.replace("Z", "+00:00"))
except ValueError:
# Legacy archive rows can already contain a display-only time.
return text if include_date else text.rsplit(" ", 1)[-1][:16]
return moment.strftime(pattern)
def _decode_json_value(value: Any) -> Any:
if isinstance(value, Mapping):
return dict(value)
if isinstance(value, (list, tuple)):
return list(value)
if not isinstance(value, str):
return None
text = value.strip()
if not text or text[0] not in "[{":
return None
try:
return json.loads(text)
except (TypeError, ValueError, json.JSONDecodeError):
return None
def _normalized_token(value: Any) -> str:
return re.sub(r"[^a-z0-9]", "", str(value or "").strip().lower())
def _format_call_duration(value: Any) -> str:
seconds = _as_int(value)
if seconds <= 0:
return ""
if seconds < 60:
return f"通话 {seconds} 秒"
minutes, remaining = divmod(seconds, 60)
return f"通话 {minutes} 分 {remaining} 秒" if remaining else f"通话 {minutes} 分钟"
def _event_time(
row: Mapping[str, Any], *payloads: Mapping[str, Any], include_date: bool = False
) -> str:
value = _first_value(
row, "time", "create_time", "created_at", "msg_time", "timestamp", default=None
)
if value in (None, ""):
for payload in payloads:
value = _first_value(payload, "time", "timestamp", "create_time", default=None)
if value not in (None, ""):
break
return format_chat_time(value, include_date=include_date)
def _event_item(
*,
title: str,
detail: str = "",
time_text: str = "",
tone: str = "neutral",
marker: str = "系",
) -> ChatItem:
return ChatItem("event", "system", "", title, detail, time_text, tone, marker)
def _system_event_from_payload(
payload: Mapping[str, Any],
row: Mapping[str, Any],
*,
include_date: bool = False,
) -> ChatItem | None:
business = _normalized_token(_first_value(payload, "businessID", "businessId", "business_id"))
time_text = _event_time(row, payload, include_date=include_date)
patient_name = str(
_first_value(payload, "patientName", "patient_name", default="患者") or "患者"
)
if business in {"patientopenedchat", "patientopenchat", "openchat"}:
return _event_item(
title="患者进入在线问诊",
detail=f"{patient_name}已进入当前会话",
time_text=time_text,
tone="success",
marker="入",
)
if business in {"patientclosedchat", "patientclosechat", "patientleftchat", "closechat"}:
return _event_item(
title="患者离开在线问诊",
detail=f"{patient_name}已离开当前会话",
time_text=time_text,
marker="离",
)
if business == "doctorenteredconsultroom":
return _event_item(
title="医生进入在线诊室",
detail="本次在线问诊已准备就绪",
time_text=time_text,
tone="success",
marker="医",
)
if business == "consultationcomplete":
return _event_item(
title="本次问诊已完成",
detail="会话内容已归档",
time_text=time_text,
tone="success",
marker="完",
)
nested = _decode_json_value(payload.get("data"))
rtc_payload: Mapping[str, Any] | None = None
if business in {"rtccall", "rtcvideo", "rtcaudio"}:
rtc_payload = payload
elif business in {"1", "avcall"}:
rtc_payload = {**payload, **nested} if isinstance(nested, Mapping) else payload
elif _first_value(payload, "cmd", "command", default="") not in (None, ""):
rtc_payload = payload
elif isinstance(nested, Mapping):
nested_business = _normalized_token(
_first_value(nested, "businessID", "businessId", "business_id")
)
if nested_business in {"rtccall", "rtcvideo", "rtcaudio"}:
rtc_payload = nested
else:
nested_event = _system_event_from_payload(nested, row, include_date=include_date)
if nested_event is not None:
return nested_event
if rtc_payload is None:
return None
call_data = _decode_json_value(rtc_payload.get("data"))
if not isinstance(call_data, Mapping):
call_data = rtc_payload
command = _normalized_token(_first_value(call_data, "cmd", "command", "action"))
action_type = _as_int(_first_value(rtc_payload, "actionType", "action_type"))
if not command:
command = {
1: "invite",
2: "cancel",
3: "accept",
4: "reject",
5: "timeout",
6: "hangup",
7: "linebusy",
}.get(action_type, "")
call_type = _as_int(_first_value(rtc_payload, "call_type", default=2), 2)
medium = (
"语音" if call_type == 1 or business == "rtcaudio" or command == "audiocall" else "视频"
)
marker = "音" if medium == "语音" else "视"
time_text = _event_time(row, payload, rtc_payload, call_data, include_date=include_date)
duration = _format_call_duration(
_first_value(
rtc_payload,
"call_end",
"duration",
"callDuration",
default=_first_value(call_data, "call_end", "duration", "callDuration", default=0),
)
)
if command in {"videocall", "audiocall", "call", "invite", "startcall"}:
return _event_item(
title=f"发起{medium}问诊",
detail=f"医生已向患者发起{medium}通话",
time_text=time_text,
tone="info",
marker=marker,
)
if command in {"accept", "answer", "answered", "connected", "join"}:
return _event_item(
title=f"{medium}问诊已接通",
detail="医生与患者已进入通话",
time_text=time_text,
tone="success",
marker=marker,
)
if command in {"hangup", "end", "endcall", "finish", "finished"}:
return _event_item(
title=f"{medium}问诊已结束",
detail=duration,
time_text=time_text,
marker=marker,
)
if command in {"reject", "refuse", "decline"}:
return _event_item(
title=f"{medium}问诊未接通",
detail="患者已拒绝本次通话邀请",
time_text=time_text,
tone="warning",
marker=marker,
)
if command in {"timeout", "busy", "linebusy", "cancel", "cancelled", "canceled"}:
reasons = {
"timeout": "呼叫超时,患者未接听",
"busy": "患者当前忙线",
"linebusy": "患者当前忙线",
"cancel": "通话邀请已取消",
"cancelled": "通话邀请已取消",
"canceled": "通话邀请已取消",
}
return _event_item(
title=f"{medium}问诊未接通",
detail=reasons[command],
time_text=time_text,
tone="warning",
marker=marker,
)
if command in {"switchtoaudio", "switchaudio"}:
return _event_item(
title="通话已切换为语音",
detail="视频画面已关闭",
time_text=time_text,
tone="info",
marker="音",
)
if command in {"switchtovideo", "switchvideo"}:
return _event_item(
title="通话已切换为视频",
time_text=time_text,
tone="info",
marker="视",
)
return _event_item(
title=f"{medium}问诊状态已更新",
detail="通话信令已归档",
time_text=time_text,
tone="info",
marker=marker,
)
def parse_chat_item(row: Mapping[str, Any], *, include_date: bool = False) -> ChatItem | None:
raw_text = _first_value(row, "text", "content", "message", default="")
payload = _decode_json_value(raw_text)
if isinstance(payload, Mapping):
business = _normalized_token(
_first_value(payload, "businessID", "businessId", "business_id")
)
if business == "usertypingstatus":
return None
event = _system_event_from_payload(payload, row, include_date=include_date)
if event is not None:
return event
kind = str(
_first_value(row, "msg_type", "message_type", "type", default="text") or "text"
).lower()
technical_keys = {
"businessID",
"businessId",
"business_id",
"actionType",
"inviteID",
"cmd",
"command",
}
if isinstance(payload, Mapping) and (
kind in {"custom", "other", "system"} or technical_keys.intersection(payload)
):
return _event_item(
title="系统状态已同步",
detail="技术消息已归档,不影响问诊内容",
time_text=_event_time(row, payload, include_date=include_date),
)
doctor_flag = _first_value(row, "is_from_doctor", "from_doctor", default=False)
sender_role = _normalized_token(_first_value(row, "role", "sender_type", default=""))
from_account = str(_first_value(row, "from_account", "sender", default="") or "").lower()
from_doctor = (
_truthy(doctor_flag)
or sender_role in {"doctor", "staff", "2"}
or from_account.startswith("doctor_")
)
from_ai = sender_role in {"ai", "assistant", "model"} or from_account.startswith(
("ai_", "assistant_")
)
role = "ai" if from_ai else "doctor" if from_doctor else "patient"
time_text = _event_time(row, include_date=include_date)
attachment_labels = {
"image": "图片消息",
"2": "图片消息",
"file": "附件",
"3": "附件",
"sound": "语音消息",
"audio": "语音消息",
"video": "视频消息",
"location": "位置消息",
"face": "表情消息",
}
if kind in attachment_labels:
file_name = str(_first_value(row, "file_name", default="") or "").strip()
detail = str(raw_text or "").strip()
if kind in {"file", "3"} and file_name:
text: Any = f"附件:{file_name}"
elif kind == "location" and detail:
text = f"位置:{detail}"
else:
text = attachment_labels[kind]
elif isinstance(payload, (Mapping, list)):
text = payload
else:
text = str(raw_text or _first_value(row, "file_name", default="") or "").strip()
if text in (None, "", {}, []):
return None
return ChatItem("message", role, text, "", "", time_text, "", "")
@@ -63,7 +63,8 @@ from PySide6.QtWidgets import (
QWidget,
)
from .diagnosis_editors import FlowLayout
from .chat_items import ChatItem, parse_chat_item
from .diagnosis_editors import FlowLayout
from .diagnosis_media import shared_image_manager
from .diagnosis_terms import FIELD_DICTIONARIES, format_timestamp, shared_terms
@@ -720,6 +721,25 @@ QFrame#DiagnosisChatBubble[side="doctor"] {
border: 1px solid #F0F0F0;
border-radius: 8px;
}
QFrame#DiagnosisChatEvent {
background-color: #F7F8FA;
border: 1px solid #EDEDEE;
border-radius: 8px;
}
QLabel#DiagnosisChatEventMarker {
color: #697386;
font-size: 12px;
font-weight: 600;
}
QLabel#DiagnosisChatEventTitle {
color: #374151;
font-size: 13px;
font-weight: 600;
}
QLabel#DiagnosisChatEventDetail {
color: #697386;
font-size: 12px;
}
QLabel#DiagnosisChatMeta {
color: #606163;
font-size: 12px;
@@ -3034,25 +3054,16 @@ class ChatPanel(QWidget):
widget = item.widget()
if widget is not None and widget not in {self.empty, self.toolbar, self.info}:
widget.deleteLater()
self.empty.setVisible(not messages)
visible_count = 0
for message in messages:
doctor_flag = _pick(message, "is_from_doctor", default=False)
is_doctor = (
doctor_flag.strip().lower() not in {"", "0", "false", "no"}
if isinstance(doctor_flag, str)
else bool(doctor_flag)
)
side = (
"doctor"
if is_doctor
or str(_pick(message, "role", "sender_type", default="")).lower()
in {
"doctor",
"staff",
"2",
}
else "patient"
)
item = parse_chat_item(message, include_date=True)
if item is None:
continue
visible_count += 1
if item.variant == "event":
self.root.insertWidget(max(2, self.root.count() - 1), self._event_row(item))
continue
side = "doctor" if item.role == "doctor" else "patient"
row = QWidget()
row_layout = QHBoxLayout(row)
row_layout.setContentsMargins(0, 0, 0, 0)
@@ -3065,13 +3076,14 @@ class ChatPanel(QWidget):
bubble_layout.setSpacing(5)
meta = QLabel(
f"{_text(_pick(message, 'sender_name', 'from_staff_name', 'name'), '患者' if side == 'patient' else '医生')} "
f"{_text(_pick(message, 'create_time', 'time'), '')}"
f"{item.time_text}"
)
meta.setObjectName("DiagnosisChatMeta")
meta.setTextFormat(Qt.TextFormat.PlainText)
message_type = str(
_pick(message, "message_type", "msg_type", "type", default="text") or "text"
).lower()
body_text = _text(_pick(message, "content", "text", "message"), "不支持的消息")
body_text = _text(_pick(message, "text", "content", "message"), "不支持的消息")
body: QWidget
if message_type in {"image", "2"}:
target = str(
@@ -3111,9 +3123,11 @@ class ChatPanel(QWidget):
)
body = action
else:
text = QLabel(body_text)
text = QLabel(body_text)
text.setObjectName("DiagnosisChatText")
text.setTextFormat(Qt.TextFormat.PlainText)
text.setWordWrap(True)
text.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
body = text
bubble_layout.addWidget(meta)
bubble_layout.addWidget(body)
@@ -3124,6 +3138,50 @@ class ChatPanel(QWidget):
row_layout.addWidget(bubble)
row_layout.addStretch(1)
self.root.insertWidget(max(2, self.root.count() - 1), row)
self.empty.setVisible(visible_count == 0)
@staticmethod
def _event_row(item: ChatItem) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 0, 0, 0)
layout.addStretch(1)
card = QFrame()
card.setObjectName("DiagnosisChatEvent")
card.setProperty("tone", item.tone)
card.setMaximumWidth(620)
card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
content = QGridLayout(card)
content.setContentsMargins(12, 10, 12, 10)
content.setHorizontalSpacing(9)
content.setVerticalSpacing(4)
marker = QLabel(item.marker)
marker.setObjectName("DiagnosisChatEventMarker")
marker.setTextFormat(Qt.TextFormat.PlainText)
marker.setFixedWidth(22)
marker.setAlignment(Qt.AlignmentFlag.AlignCenter)
content.addWidget(marker, 0, 0)
title = QLabel(item.title)
title.setObjectName("DiagnosisChatEventTitle")
title.setTextFormat(Qt.TextFormat.PlainText)
title.setWordWrap(True)
content.addWidget(title, 0, 1)
content.setColumnStretch(1, 1)
if item.time_text:
time = QLabel(item.time_text)
time.setObjectName("DiagnosisChatMeta")
time.setTextFormat(Qt.TextFormat.PlainText)
content.addWidget(time, 0, 2, alignment=Qt.AlignmentFlag.AlignRight)
if item.detail:
detail = QLabel(item.detail)
detail.setObjectName("DiagnosisChatEventDetail")
detail.setTextFormat(Qt.TextFormat.PlainText)
detail.setWordWrap(True)
detail.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
content.addWidget(detail, 1, 1, 1, 2)
layout.addWidget(card, 4)
layout.addStretch(1)
return row
@dataclass(frozen=True)
@@ -9,7 +9,6 @@ from collections.abc import Container, Mapping, Sequence
from contextlib import suppress
from copy import deepcopy
from datetime import datetime
from html import escape
from threading import Event
from time import monotonic
from typing import Any
@@ -18,9 +17,12 @@ from PySide6.QtCore import QObject, QRunnable, QSize, Qt, QThreadPool, QTimer, S
from PySide6.QtGui import (
QIcon,
QKeyEvent,
QTextCharFormat,
QTextCursor,
QTextDocument,
)
from PySide6.QtWidgets import (
QComboBox,
QDialog,
QFrame,
QGridLayout,
@@ -40,6 +42,7 @@ from PySide6.QtWidgets import (
)
from .. import icons
from ..chat_items import parse_chat_item as _parse_chat_item
from ..diagnosis_drawer import CaseGrid, _RemoteImageButton
from ..diagnosis_media import (
ImagePreviewDialog,
@@ -69,6 +72,20 @@ from ..widgets import (
run_async,
show_toast,
)
from .ai_consult_charts import GlucoseChartData
from .ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
UNKNOWN_COLOR,
combined_metric_state,
risk_color,
)
from .ai_consult_metric_text import MetricTextState, metric_text_context, metric_text_html
from .ai_consult_report_visuals import (
ReportVisual,
build_report_visuals,
create_report_visual,
)
from .prescription_ai import can_use_diagnosis_ai_assistant, diagnosis_ai_task
AI_CONSULT_QSS = """
@@ -949,10 +966,6 @@ _STRUCTURED_FIELD_LABELS = {
"message": "消息",
"status": "状态",
}
_ChatItem = namedtuple(
"_ChatItem",
"variant role text title detail time_text tone marker",
)
def can_open_ai_consult(permissions: Any) -> bool:
@@ -1014,27 +1027,6 @@ def _paint_icon(kind: str, color: str = "accent", size: int = 18) -> QIcon:
return icons.icon(kind, color, size)
def _format_time(value: Any) -> str:
if value in (None, ""):
return ""
numeric: float | None = None
if isinstance(value, (int, float)):
numeric = float(value)
elif isinstance(value, str) and value.strip().isdigit():
numeric = float(value.strip())
if numeric is not None and numeric > 1_000_000_000:
if numeric > 100_000_000_000:
numeric /= 1000
try:
return datetime.fromtimestamp(numeric).strftime("%H:%M")
except (OverflowError, OSError, ValueError):
return ""
text = str(value)
if " " in text:
return text.split(" ")[-1][:5]
return text[:16]
def _join_meta(*parts: Any) -> str:
return " · ".join(
str(part).strip()
@@ -1043,22 +1035,6 @@ def _join_meta(*parts: Any) -> str:
)
def _decode_json_value(value: Any) -> Any:
if isinstance(value, Mapping):
return dict(value)
if isinstance(value, (list, tuple)):
return list(value)
if not isinstance(value, str):
return None
text = value.strip()
if not text or text[0] not in "[{":
return None
try:
return json.loads(text)
except (TypeError, ValueError, json.JSONDecodeError):
return None
def _structured_markdown(value: Any, *, depth: int = 0) -> str:
"""Turn small structured replies into readable clinical copy, not code dumps."""
@@ -1087,258 +1063,6 @@ def _structured_markdown(value: Any, *, depth: int = 0) -> str:
return str(value)
def _normalized_token(value: Any) -> str:
return re.sub(r"[^a-z0-9]", "", str(value or "").strip().lower())
def _format_call_duration(value: Any) -> str:
seconds = _as_int(value)
if seconds <= 0:
return ""
if seconds < 60:
return f"通话 {seconds} 秒"
minutes, remaining = divmod(seconds, 60)
return f"通话 {minutes} 分 {remaining} 秒" if remaining else f"通话 {minutes} 分钟"
def _event_time(row: Mapping[str, Any], *payloads: Mapping[str, Any]) -> str:
value = first_value(row, "time", "create_time", "created_at", "msg_time", default=None)
if value in (None, ""):
for payload in payloads:
value = first_value(payload, "time", "timestamp", "create_time", default=None)
if value not in (None, ""):
break
return _format_time(value)
def _event_item(
*,
title: str,
detail: str = "",
time_text: str = "",
tone: str = "neutral",
marker: str = "系",
) -> _ChatItem:
return _ChatItem("event", "system", "", title, detail, time_text, tone, marker)
def _system_event_from_payload(
payload: Mapping[str, Any],
row: Mapping[str, Any],
) -> _ChatItem | None:
business = _normalized_token(first_value(payload, "businessID", "businessId", "business_id"))
time_text = _event_time(row, payload)
patient_name = str(first_value(payload, "patientName", "patient_name", default="患者") or "患者")
if business in {"patientopenedchat", "patientopenchat", "openchat"}:
return _event_item(
title="患者进入在线问诊",
detail=f"{patient_name}已进入当前会话",
time_text=time_text,
tone="success",
marker="入",
)
if business in {"patientclosedchat", "patientclosechat", "patientleftchat", "closechat"}:
return _event_item(
title="患者离开在线问诊",
detail=f"{patient_name}已离开当前会话",
time_text=time_text,
marker="离",
)
if business == "doctorenteredconsultroom":
return _event_item(
title="医生进入在线诊室",
detail="本次在线问诊已准备就绪",
time_text=time_text,
tone="success",
marker="医",
)
if business == "consultationcomplete":
return _event_item(
title="本次问诊已完成",
detail="会话内容已归档",
time_text=time_text,
tone="success",
marker="完",
)
nested = _decode_json_value(payload.get("data"))
rtc_payload: Mapping[str, Any] | None = None
if business in {"rtccall", "rtcvideo", "rtcaudio"}:
rtc_payload = payload
elif business in {"1", "avcall"}:
rtc_payload = {**payload, **nested} if isinstance(nested, Mapping) else payload
elif first_value(payload, "cmd", "command", default="") not in (None, ""):
rtc_payload = payload
elif isinstance(nested, Mapping):
nested_business = _normalized_token(
first_value(nested, "businessID", "businessId", "business_id")
)
if nested_business in {"rtccall", "rtcvideo", "rtcaudio"}:
rtc_payload = nested
else:
nested_event = _system_event_from_payload(nested, row)
if nested_event is not None:
return nested_event
if rtc_payload is None:
return None
call_data = _decode_json_value(rtc_payload.get("data"))
if not isinstance(call_data, Mapping):
call_data = rtc_payload
command = _normalized_token(first_value(call_data, "cmd", "command", "action"))
action_type = _as_int(first_value(rtc_payload, "actionType", "action_type"))
if not command:
command = {
1: "invite",
2: "cancel",
3: "accept",
4: "reject",
5: "timeout",
6: "hangup",
7: "linebusy",
}.get(action_type, "")
call_type = _as_int(first_value(rtc_payload, "call_type", default=2), 2)
medium = "语音" if call_type == 1 or business == "rtcaudio" else "视频"
marker = "音" if medium == "语音" else "视"
time_text = _event_time(row, payload, rtc_payload, call_data)
duration = _format_call_duration(
first_value(rtc_payload, "call_end", "duration", "callDuration", default=0)
)
if command in {"videocall", "audiocall", "call", "invite", "startcall"}:
return _event_item(
title=f"发起{medium}问诊",
detail=f"医生已向患者发起{medium}通话",
time_text=time_text,
tone="info",
marker=marker,
)
if command in {"accept", "answer", "answered", "connected", "join"}:
return _event_item(
title=f"{medium}问诊已接通",
detail="医生与患者已进入通话",
time_text=time_text,
tone="success",
marker=marker,
)
if command in {"hangup", "end", "endcall", "finish", "finished"}:
return _event_item(
title=f"{medium}问诊已结束",
detail=duration,
time_text=time_text,
marker=marker,
)
if command in {"reject", "refuse", "decline"}:
return _event_item(
title=f"{medium}问诊未接通",
detail="患者已拒绝本次通话邀请",
time_text=time_text,
tone="warning",
marker=marker,
)
if command in {"timeout", "busy", "linebusy", "cancel", "cancelled", "canceled"}:
reasons = {
"timeout": "呼叫超时,患者未接听",
"busy": "患者当前忙线",
"linebusy": "患者当前忙线",
"cancel": "通话邀请已取消",
"cancelled": "通话邀请已取消",
"canceled": "通话邀请已取消",
}
return _event_item(
title=f"{medium}问诊未接通",
detail=reasons[command],
time_text=time_text,
tone="warning",
marker=marker,
)
if command in {"switchtoaudio", "switchaudio"}:
return _event_item(
title="通话已切换为语音",
detail="视频画面已关闭",
time_text=time_text,
tone="info",
marker="音",
)
if command in {"switchtovideo", "switchvideo"}:
return _event_item(
title="通话已切换为视频",
time_text=time_text,
tone="info",
marker="视",
)
return _event_item(
title=f"{medium}问诊状态已更新",
detail="通话信令已归档",
time_text=time_text,
tone="info",
marker=marker,
)
def _parse_chat_item(row: Mapping[str, Any]) -> _ChatItem | None:
raw_text = first_value(row, "text", "content", "message", default="")
payload = _decode_json_value(raw_text)
if isinstance(payload, Mapping):
business = _normalized_token(
first_value(payload, "businessID", "businessId", "business_id")
)
if business == "usertypingstatus":
return None
event = _system_event_from_payload(payload, row)
if event is not None:
return event
kind = str(first_value(row, "msg_type", "message_type", "type", default="text") or "text").lower()
technical_keys = {"businessID", "businessId", "actionType", "inviteID", "cmd", "command"}
if isinstance(payload, Mapping) and (
kind in {"custom", "other", "system"} or technical_keys.intersection(payload)
):
return _event_item(
title="系统状态已同步",
detail="技术消息已归档,不影响问诊内容",
time_text=_event_time(row, payload),
)
doctor_flag = first_value(row, "is_from_doctor", "from_doctor", default=False)
sender_role = _normalized_token(first_value(row, "role", "sender_type", default=""))
from_account = str(first_value(row, "from_account", "sender", default="") or "").lower()
from_doctor = _truthy(doctor_flag) or sender_role in {"doctor", "staff", "2"} or from_account.startswith("doctor_")
from_ai = sender_role in {"ai", "assistant", "model"} or from_account.startswith(
("ai_", "assistant_")
)
role = "ai" if from_ai else "doctor" if from_doctor else "patient"
time_text = _event_time(row)
attachment_labels = {
"image": "图片消息",
"2": "图片消息",
"file": "附件",
"3": "附件",
"sound": "语音消息",
"audio": "语音消息",
"video": "视频消息",
"location": "位置消息",
"face": "表情消息",
}
if kind in attachment_labels:
file_name = str(first_value(row, "file_name", default="") or "").strip()
detail = str(raw_text or "").strip()
if kind in {"file", "3"} and file_name:
text: Any = f"附件:{file_name}"
elif kind == "location" and detail:
text = f"位置:{detail}"
else:
text = attachment_labels[kind]
elif isinstance(payload, (Mapping, list)):
text = payload
else:
text = str(raw_text or first_value(row, "file_name", default="") or "").strip()
if text in (None, "", {}, []):
return None
return _ChatItem("message", role, text, "", "", time_text, "", "")
def render_chat_payload(browser: QTextBrowser, raw: Any, *, role: str = "ai") -> None:
"""Render markdown, HTML, JSON or plain text inside a chat bubble."""
@@ -2006,7 +1730,10 @@ def _clinical_entries(text: str, *, limit: int) -> list[_ClinicalEntry]:
def _clinical_evidence(text: str) -> list[_ClinicalEvidence]:
evidence: list[_ClinicalEvidence] = []
glucose = re.search(
r"空腹血糖(?:偏高)?[^0-9]{0,10}([0-9]+(?:\.[0-9]+)?)\s*(mmol/L)?",
r"空腹血糖(?:偏高)?[^0-9<>≤≥]{0,10}"
r"([<>≤≥]?\s*[0-9]+(?:\.[0-9]+)?"
r"(?:\s*(?:[-~~–—]|至|到)\s*[0-9]+(?:\.[0-9]+)?)?)"
r"(?![0-9.xX点~~–—-]|至|到|左右|多|余)\s*(mmol/L)?",
text,
re.IGNORECASE,
)
@@ -2168,8 +1895,9 @@ def _report_provenance_widget(raw: Any, parent: QWidget) -> QFrame:
_InsightItem = namedtuple("_InsightItem", "kind marker label text")
_INSIGHT_LIST_RE = re.compile(r"^\s*(\d{1,2})\s*([\.、))]\s*)")
_INSIGHT_LIST_LOOKAHEAD_RE = re.compile(r"(?:^|(?<=[::;;。\s]))(\d{1,2})\s*([\.、))])\s*")
_INSIGHT_MARKER = r"(\d{1,2})\s*(\.(?!\d)|[、))])\s*"
_INSIGHT_LIST_RE = re.compile(r"^\s*" + _INSIGHT_MARKER)
_INSIGHT_LIST_LOOKAHEAD_RE = re.compile(r"(?:^|(?<=[::;;。\s]))" + _INSIGHT_MARKER)
_INSIGHT_LABEL_RE = re.compile(r"^([\u4e00-\u9fa5A-Za-z()()·\s]{1,12})[::]\s*(.*)$")
@@ -2243,10 +1971,7 @@ def _split_numbered_list(text: str) -> list[_InsightItem]:
candidate_ends: list[int] = []
if sentence_match is not None:
candidate_ends.append(sentence_match.end())
next_marker_match = re.search(
r"\s\d{1,2}\s*[\.、))]",
after_marker,
)
next_marker_match = re.search(r"\s" + _INSIGHT_MARKER, after_marker)
if next_marker_match is not None:
candidate_ends.append(next_marker_match.start() + 1)
inner_end = min(candidate_ends) if candidate_ends else len(after_marker)
@@ -2372,10 +2097,10 @@ _REPORT_ORDINAL_RE = re.compile(r"^\s*(?:\d{1,2}|[一二三四五六七八九十
_READING_LINE_HEIGHT = 172
def _reading_html(text: str) -> str:
def _reading_html(text: str, *, metric_label: str = "") -> str:
"""Wrap plain report text in the reading rhythm used across the workspace."""
escaped = escape(str(text or "").strip()).replace("\n", "<br>")
escaped = metric_text_html(str(text or "").strip(), metric_label=metric_label)
return f'<div style="line-height:{_READING_LINE_HEIGHT}%">{escaped}</div>'
@@ -2438,6 +2163,47 @@ class _FittedText(QLabel):
self._fitting = False
def _fitted_metric_label(text: str, parent: QWidget) -> _FittedText:
html = metric_text_html(text)
highlighted = "color:" in html
return _FittedText(html if highlighted else text, rich=highlighted, parent=parent)
def _set_metric_label(label: QLabel, text: str, *, metric_label: str = "") -> None:
html = metric_text_html(text, metric_label=metric_label)
highlighted = "color:" in html
label.setTextFormat(Qt.TextFormat.RichText if highlighted else Qt.TextFormat.PlainText)
label.setText(html if highlighted else text)
def _highlight_document_metrics(document: QTextDocument) -> None:
"""Keep Markdown structure while emphasizing metrics in a short completed reply."""
text = document.toPlainText()
colored = QTextDocument()
colored.setHtml(metric_text_html(text))
if colored.toPlainText() != text:
return
cursor = QTextCursor(document)
cursor.beginEditBlock()
block = colored.begin()
while block.isValid():
fragments = block.begin()
while not fragments.atEnd():
fragment = fragments.fragment()
foreground = fragment.charFormat().foreground()
if foreground.style() != Qt.BrushStyle.NoBrush:
style = QTextCharFormat()
style.setForeground(foreground)
style.setFontWeight(fragment.charFormat().fontWeight())
cursor.setPosition(fragment.position())
cursor.setPosition(fragment.position() + fragment.length(), QTextCursor.MoveMode.KeepAnchor)
cursor.mergeCharFormat(style)
fragments += 1
block = block.next()
cursor.endEditBlock()
_REPORT_LEAD_RE = re.compile(r"^\s*(?P<label>[^::。;;!!??]{2,20})\s*[::]\s*(?P<body>.+)$")
@@ -2528,6 +2294,9 @@ class _StructuredReportPanel(QWidget):
# 富余高度归到底部,否则会被平摊进每张卡片,把报告拉得空空荡荡。
root.addStretch(1)
def set_time_text(self, text: str) -> None:
self.meta_label.setText(text)
def _section_card(self, index: int, section: _ReportSection) -> QFrame:
card = QFrame(self)
card.setObjectName("AiConsultReportSection")
@@ -2545,9 +2314,7 @@ class _StructuredReportPanel(QWidget):
chip.setAlignment(Qt.AlignmentFlag.AlignCenter)
head.addWidget(chip, 0, Qt.AlignmentFlag.AlignTop)
# 序号已经在圆点里,标题再带一次 "1." 只是噪音。
title = _FittedText(
_strip_leading_ordinal(section.title), rich=False, parent=card
)
title = _fitted_metric_label(_strip_leading_ordinal(section.title), card)
title.setObjectName("AiConsultReportSectionTitle")
head.addWidget(title, 1)
layout.addLayout(head)
@@ -2579,10 +2346,10 @@ class _StructuredReportPanel(QWidget):
column.setContentsMargins(0, 0, 0, 0)
column.setSpacing(3)
if label:
lead = _FittedText(label, rich=False, parent=host)
lead = _fitted_metric_label(label, host)
lead.setObjectName("AiConsultReportLead")
column.addWidget(lead)
body = _FittedText(_reading_html(body_text), parent=host)
body = _FittedText(_reading_html(body_text, metric_label=label), parent=host)
body.setObjectName("AiConsultReportBody")
body.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
column.addWidget(body)
@@ -2693,7 +2460,7 @@ class _ClinicalAnalysisPanel(QWidget):
_style_surface(disclaimer)
root.addWidget(disclaimer)
root.addWidget(_report_provenance_widget(provenance, self))
QTimer.singleShot(0, self._apply_responsive_layout)
QTimer.singleShot(0, self, self._apply_responsive_layout)
def set_time_text(self, time_text: str) -> None:
self.meta_label.setText(
@@ -2725,6 +2492,7 @@ class _ClinicalAnalysisPanel(QWidget):
label = QLabel(item.label)
label.setObjectName("AiConsultEvidenceLabel")
value = QLabel(item.value)
_set_metric_label(value, item.value, metric_label=item.label)
value.setObjectName("AiConsultEvidenceValue")
value.setWordWrap(True)
copy.addWidget(label)
@@ -2749,6 +2517,7 @@ class _ClinicalAnalysisPanel(QWidget):
card_layout.setSpacing(6)
heading = QHBoxLayout()
title = QLabel(entry.title)
_set_metric_label(title, entry.title)
title.setObjectName("AiConsultHypothesisTitle")
title.setWordWrap(True)
heading.addWidget(title, 1)
@@ -2792,6 +2561,7 @@ class _ClinicalAnalysisPanel(QWidget):
if entry.details:
copy += ":" + ";".join(entry.details)
text = QLabel(_compact_copy(copy, max_chars=82))
_set_metric_label(text, _compact_copy(copy, max_chars=82))
text.setObjectName("AiConsultGapText")
text.setWordWrap(True)
text.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
@@ -2814,6 +2584,7 @@ class _ClinicalAnalysisPanel(QWidget):
_style_surface(number)
layout.addWidget(number, 0, Qt.AlignmentFlag.AlignHCenter)
title = QLabel(entry.title)
_set_metric_label(title, entry.title)
title.setObjectName("AiConsultWorkflowTitle")
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
title.setWordWrap(True)
@@ -2852,6 +2623,7 @@ class _ClinicalAnalysisPanel(QWidget):
item_layout.setContentsMargins(0, 0, 0, 0)
item_layout.setSpacing(3)
title = QLabel(entry.title)
_set_metric_label(title, entry.title)
title.setObjectName("AiConsultRiskTitle")
title.setWordWrap(True)
item_layout.addWidget(title)
@@ -2903,6 +2675,83 @@ class _ClinicalAnalysisPanel(QWidget):
)
def _metric_text_states(
visuals: Sequence[GlucoseChartData | ReportVisual],
) -> tuple[MetricTextState, ...]:
"""Bind prose to the same immutable, owned measurements used by the charts."""
states = []
glucose_fields = (
("fasting", "空腹血糖"), ("postprandial", "餐后血糖"), ("other", "其他血糖"),
)
for visual in visuals:
if isinstance(visual, GlucoseChartData):
for reading in visual.readings:
for field, label in glucose_fields:
value = getattr(reading, field)
if value is not None:
states.append(MetricTextState(
label, f"{value:g} mmol/L", getattr(reading, f"{field}_status", ""),
))
continue
if visual.kind not in {"metrics", "blood_pressure"}:
continue
systolic = None
for item in visual.items:
if visual.kind == "blood_pressure" and item.series == "systolic_pressure":
systolic = item if item.value is not None else None
if item.value is None and item.interval is None:
if visual.kind == "blood_pressure" and item.series == "diastolic_pressure":
systolic = None
continue
states.append(MetricTextState(item.label, item.value_text, item.status))
if item.label == "BMI" and item.value is not None:
# BMI is also displayed without its conventional unit in prose and key facts.
states.append(MetricTextState(item.label, item.raw_value, item.status))
if visual.kind != "blood_pressure":
continue
if (item.series == "diastolic_pressure" and systolic is not None
and systolic.recorded_at == item.recorded_at):
states.append(MetricTextState(
"血压", f"{systolic.value:g}/{item.value:g} mmHg",
combined_metric_state([systolic.status, item.status]),
))
systolic = None
return tuple(states)
def _report_visual_widget(
visuals: Sequence[GlucoseChartData | ReportVisual], parent: QWidget
) -> QWidget:
if len(visuals) == 1:
return create_report_visual(visuals[0], parent)
host = QWidget(parent)
host.setObjectName("AiConsultReportVisualGroup")
host.setMinimumWidth(0)
host.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
layout = QVBoxLayout(host)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(8)
selector = QComboBox(host)
selector.setObjectName("AiConsultReportVisualSelector")
selector.setAccessibleName("切换报告相关数据图表")
selector.setToolTip("根据本次分析内容与已有记录选择图表")
for data in visuals:
selector.addItem("血糖变化趋势" if isinstance(data, GlucoseChartData) else data.title)
layout.addWidget(selector)
cards = [create_report_visual(data, host) for data in visuals]
for index, card in enumerate(cards):
layout.addWidget(card)
card.setVisible(index == 0)
def select(index: int) -> None:
for position, card in enumerate(cards):
card.setVisible(position == index)
host.updateGeometry()
selector.currentIndexChanged.connect(select)
return host
class _ChatBubble(QWidget):
def __init__(
self,
@@ -2917,7 +2766,8 @@ class _ChatBubble(QWidget):
self._role = role
self._raw_payload = text
self._provenance: Mapping[str, Any] = {}
self._clinical_panel: _ClinicalAnalysisPanel | None = None
self._clinical_panel: _ClinicalAnalysisPanel | _StructuredReportPanel | None = None
self._standalone_visuals: list[QWidget] = []
row = QHBoxLayout(self)
row.setContentsMargins(12, 7, 12, 7)
row.setSpacing(10)
@@ -2999,11 +2849,23 @@ class _ChatBubble(QWidget):
else:
self.stamp.show()
def finalize_clinical_analysis(self) -> bool:
def finalize_clinical_analysis(
self,
*,
chart_data: GlucoseChartData | None = None,
visuals: Sequence[GlucoseChartData | ReportVisual] = (),
) -> bool:
"""Replace a completed long clinical reply with its scan-first panel."""
if self._role != "ai" or self.body is None:
return False
report_visuals = tuple(visuals)
if chart_data is not None and chart_data.available:
report_visuals = (chart_data, *report_visuals)
with metric_text_context(_metric_text_states(report_visuals)):
return self._finalize_report_panel(report_visuals)
def _finalize_report_panel(self, report_visuals: Sequence[GlucoseChartData | ReportVisual]) -> bool:
model = _parse_clinical_analysis(self._raw_payload)
panel: QWidget | None = None
if model is not None:
@@ -3024,9 +2886,16 @@ class _ChatBubble(QWidget):
provenance=self._provenance,
parent=self._bubble_frame,
)
if panel is None:
return False
self._reset_clinical_panel()
if panel is None:
_highlight_document_metrics(self.body.document())
if report_visuals:
visual = _report_visual_widget(report_visuals, self._bubble_frame)
self._standalone_visuals.append(visual)
self._inner.insertWidget(1, visual)
return False
if report_visuals:
panel.layout().insertWidget(1, _report_visual_widget(report_visuals, panel))
panel.setParent(self._bubble_frame)
self._clinical_panel = panel
self._role_name.hide()
@@ -3043,6 +2912,11 @@ class _ChatBubble(QWidget):
return True
def _reset_clinical_panel(self) -> None:
for visual in self._standalone_visuals:
self._inner.removeWidget(visual)
visual.hide()
visual.deleteLater()
self._standalone_visuals.clear()
if self._clinical_panel is None:
return
panel = self._clinical_panel
@@ -3522,6 +3396,7 @@ class AiConsultDialog(QDialog):
self.permissions = permissions
self.diagnosis_id = 0
self.patient_id = 0
self._chart_patient_id = 0
self._seed: Mapping[str, Any] = {}
self._detail: Mapping[str, Any] = {}
self._workspace_sections: dict[str, dict[str, Any]] = {}
@@ -3547,8 +3422,6 @@ class AiConsultDialog(QDialog):
self._patient_ai_context: str = ""
self._patient_ai_context_labels: list[str] = []
self._patient_ai_context_bubble: _ChatBubble | None = None
# 全量上下文说明每轮问答都一样,只在本次会话第一次提问时提示一次。
self._context_notice_shown = False
# done 事件是否到达。用于区分“模型没内容”和“连接直接断了”。
self._stream_completed = False
self._follow_chat = True
@@ -3606,7 +3479,10 @@ class AiConsultDialog(QDialog):
self._session_closed = False
self.diagnosis_id = diagnosis_id
self.patient_id = _as_int(patient_id)
self._chart_patient_id = self.patient_id
self._seed = dict(seed) if isinstance(seed, Mapping) else {}
self._detail = {}
self._workspace_sections = {}
self.source_crumb.setText(source_title)
self._generation += 1
self._image_generation += 1
@@ -3618,8 +3494,6 @@ class AiConsultDialog(QDialog):
self._patient_ai_context = ""
self._patient_ai_context_labels = []
self._patient_ai_context_bubble = None
# 换患者等于开启新会话,全量上下文说明需要再提示一次。
self._context_notice_shown = False
# Appointment seeds are presentation hints only. In the admin list,
# ``patient_id`` may actually be the diagnosis id, so it must never
# replace the separately supplied patient owner.
@@ -4137,7 +4011,7 @@ class AiConsultDialog(QDialog):
QTimer.singleShot(0, self._scroll_chat_to_bottom)
def _scroll_chat_to_bottom(self) -> None:
if not self._follow_chat:
if self._session_closed or not self._follow_chat:
return
bar = self.chat_scroll.verticalScrollBar()
bar.setValue(bar.maximum())
@@ -4173,8 +4047,15 @@ class AiConsultDialog(QDialog):
inner = QVBoxLayout(card)
inner.setContentsMargins(10, 8, 10, 8)
inner.setSpacing(2)
number = QLabel(value or "未记录")
reading = value or "未记录"
number = QLabel(reading)
number.setObjectName("AiConsultKeyValue")
number.setTextFormat(Qt.TextFormat.PlainText)
document = QTextDocument()
document.setHtml(metric_text_html(reading, metric_label=label))
foreground = document.find(reading).charFormat().foreground()
if foreground.style() != Qt.BrushStyle.NoBrush:
number.setStyleSheet(f"color: {foreground.color().name()};")
caption = QLabel(label)
caption.setObjectName("AiConsultKeyLabel")
inner.addWidget(number)
@@ -4207,6 +4088,9 @@ class AiConsultDialog(QDialog):
badge.setObjectName("AiConsultTag")
_style_surface(badge)
badge.setProperty("level", level)
color = UNKNOWN_COLOR if tag in {"加载中", "未生成", "未提供", "未记录"} else risk_color(level)
background = {ABNORMAL_COLOR: "#FFF1F3", NORMAL_COLOR: "#EAF9F3"}.get(color, "#F0F0F0")
badge.setStyleSheet(f"color: {color}; background-color: {background};")
badge.style().unpolish(badge)
badge.style().polish(badge)
header_row.addWidget(badge, 0, Qt.AlignmentFlag.AlignTop)
@@ -4250,15 +4134,15 @@ class AiConsultDialog(QDialog):
text_label.setTextFormat(Qt.TextFormat.RichText)
if item.label:
html_label = _escape_html(item.label)
html_body = _escape_html(item.text or "")
html_label = metric_text_html(item.label)
html_body = metric_text_html(item.text or "", metric_label=item.label)
text_label.setText(
f"<span style='color:#1A1C1F;font-weight:600;'>{html_label}</span>"
f"<span style='color:#6A6B6D;'>:</span>"
f"<span style='color:#1A1C1F;'>{html_body}</span>"
)
else:
text_label.setText(_escape_html(item.text or ""))
text_label.setText(metric_text_html(item.text or ""))
if marker_label is not None:
layout.addWidget(marker_label, 0, Qt.AlignmentFlag.AlignTop)
@@ -4332,14 +4216,15 @@ class AiConsultDialog(QDialog):
self._set_chips(chips)
self.side_name.setText(_join_meta(name, gender, age_text) or name)
self.side_tags.setText(_join_meta(illness, "需持续随访") or "暂无诊断标签")
self._set_key_facts(
[
("病程", _course_text(*sources) or "未记录"),
("BMI", _bmi_text(*sources) or "未记录"),
("吸烟", _smoking_text(*sources) or "未记录"),
("家族史", _family_text(*sources) or "未记录"),
]
)
with metric_text_context(_metric_text_states(self._record_visuals("综合分析", ""))):
self._set_key_facts(
[
("病程", _course_text(*sources) or "未记录"),
("BMI", _bmi_text(*sources) or "未记录"),
("吸烟", _smoking_text(*sources) or "未记录"),
("家族史", _family_text(*sources) or "未记录"),
]
)
def _load_workspace(self, generation: int) -> None:
diagnosis_id = self.diagnosis_id
@@ -4722,7 +4607,29 @@ class AiConsultDialog(QDialog):
)
if item.role == "ai":
bubble.set_provenance(row)
bubble.finalize_clinical_analysis()
self._finalize_ai_bubble(bubble)
def _finalize_ai_bubble(self, bubble: _ChatBubble, *, prompt: str = "") -> None:
"""Choose useful visual evidence from the current, owned record snapshot."""
metadata = _unwrap_analysis(bubble._provenance)
if not metadata.get("risk_assessment") and isinstance(bubble._raw_payload, Mapping):
metadata = _unwrap_analysis(bubble._raw_payload)
visuals = self._record_visuals(prompt, _structured_markdown(bubble._raw_payload), metadata)
bubble.finalize_clinical_analysis(visuals=visuals)
def _record_visuals(
self, prompt: str, reply: str, metadata: Mapping[str, Any] | None = None
) -> tuple[GlucoseChartData | ReportVisual, ...]:
if self._chart_patient_id > 0 and self.patient_id != self._chart_patient_id:
return ()
sections = dict(self._workspace_sections)
if metadata and metadata.get("risk_assessment"):
sections["analysis"] = {"value": metadata}
return build_report_visuals(
prompt, reply, sections=sections, diagnosis_id=self.diagnosis_id,
patient_id=self._chart_patient_id or self.patient_id,
)
def _render_analysis(self, analysis: Mapping[str, Any]) -> None:
payload = _unwrap_analysis(analysis)
@@ -4749,14 +4656,15 @@ class AiConsultDialog(QDialog):
if markdown:
bubble = self._append_bubble("ai", markdown)
bubble.set_provenance(payload)
bubble.finalize_clinical_analysis()
self._set_insights(
[
("血糖控制评估", advice or "报告未提供此项分析。", "已分析" if advice else "未提供", "low" if advice else "unknown"),
("并发症风险评估", risk_label or "报告未列出风险项。", level_text, risk_level),
("用药合理性评估", treatment or "报告未提供此项分析。", "已分析" if treatment else "未提供", "low" if treatment else "unknown"),
]
)
self._finalize_ai_bubble(bubble)
with metric_text_context(_metric_text_states(self._record_visuals("综合分析", markdown, payload))):
self._set_insights(
[
("血糖控制评估", advice or "报告未提供此项分析。", "已分析" if advice else "未提供", "low" if advice else "unknown"),
("并发症风险评估", risk_label or "报告未列出风险项。", level_text, risk_level),
("用药合理性评估", treatment or "报告未提供此项分析。", "已分析" if treatment else "未提供", "low" if treatment else "unknown"),
]
)
@staticmethod
def _section_error(section: Mapping[str, Any]) -> str:
@@ -6029,14 +5937,6 @@ class AiConsultDialog(QDialog):
self._append_bubble(
"doctor", text, time_text=datetime.now().strftime("%H:%M")
)
if not self._context_notice_shown:
self._append_bubble(
"ai",
"服务端将按当前诊单实时附带患者全部纵向资料"
"(病历、备注/舌苔、报告、日常记录、视频转写及历史处方)。",
time_text="全量上下文",
)
self._context_notice_shown = True
# 首帧到达前先占位。空气泡在后端无响应时会一直是一块空白卡片,
# 医生无法判断是还在生成还是已经失败。
self._stream_bubble = self._append_bubble("ai", AI_STREAM_PENDING_TEXT)
@@ -6152,7 +6052,7 @@ class AiConsultDialog(QDialog):
self._stream_text = "未返回分析内容。"
self._stream_bubble.set_payload(self._stream_text)
self._stream_bubble.set_provenance(self._stream_meta)
self._stream_bubble.finalize_clinical_analysis()
self._finalize_ai_bubble(self._stream_bubble, prompt=self._stream_prompt)
# A terminal event completes the UI request even if transport cleanup
# has not returned yet. The next click must not depend on finished.
self._asking = False
@@ -0,0 +1,646 @@
"""Verified measurement snapshots and native glucose charts for completed AI replies.
Charts use recorded observations, never numbers extracted from the generated advice.
"""
from __future__ import annotations
import math
import re
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from datetime import date, datetime, time
from typing import Any
from PySide6.QtCore import QPointF, QRectF, QSize, Qt
from PySide6.QtGui import QColor, QMouseEvent, QPainter, QPaintEvent, QPen
from PySide6.QtWidgets import (
QAbstractItemView,
QFrame,
QHBoxLayout,
QHeaderView,
QLabel,
QPushButton,
QSizePolicy,
QTableWidget,
QTableWidgetItem,
QToolTip,
QVBoxLayout,
QWidget,
)
from .ai_consult_metric_state import UNKNOWN_COLOR, metric_color
_NUMERIC = re.compile(r"(?:\d+(?:\.\d+)?|\.\d+)(?:\s*mmol\s*/\s*l)?", re.IGNORECASE)
_DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
_DATETIME = re.compile(r"\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2})?")
_TIME = re.compile(r"\d{2}:\d{2}(?::\d{2})?")
_MISSING = frozenset(("", "—", "--", "-", "未填写", "未记录", "暂无"))
_SERIES = (
("fasting", "空腹血糖", Qt.PenStyle.SolidLine),
("postprandial", "餐后血糖", Qt.PenStyle.DashLine),
("other", "其他血糖", Qt.PenStyle.DotLine),
)
_SERIES_KEYS = {
"fasting": ("fasting_blood_sugar", "fasting_glucose"),
"postprandial": ("postprandial_blood_sugar", "postprandial_glucose"),
"other": ("other_blood_sugar", "other_glucose", "blood_sugar"),
}
_STATUS_LABELS = {
"high": "偏高", "low": "偏低", "normal": "正常", "abnormal": "异常",
"warning": "需关注", "0": "正常", "unknown": "未标注",
}
_CARD_QSS = """
QFrame#AiConsultGlucoseReport {
background: #FFFFFF; border: 1px solid #EDEDEE; border-radius: 10px;
}
QFrame#AiConsultGlucoseReport QLabel { background: transparent; border: 0; }
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseTitle {
color: #1A1C1F; font-size: 15px; font-weight: 600;
}
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseCount,
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseSource {
color: #606163; font-size: 12px;
}
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseState {
color: #606163; font-size: 13px; padding: 9px 0;
}
QFrame#AiConsultGlucoseReport QPushButton#AiConsultGlucoseDataToggle {
color: #4F63D9; background: #F7F8FC; border: 1px solid #E4E7F4;
border-radius: 6px; padding: 5px 9px; font-size: 12px;
}
QFrame#AiConsultGlucoseReport QPushButton#AiConsultGlucoseDataToggle:hover {
background: #EEF1FA;
}
QFrame#AiConsultGlucoseReport QTableWidget#AiConsultGlucoseTable {
color: #1A1C1F; background: #FFFFFF; alternate-background-color: #F7F8FC;
border: 1px solid #EDEDEE; border-radius: 4px; gridline-color: #EDEDEE;
font-size: 12px; selection-background-color: #EEF1FA; selection-color: #1A1C1F;
}
QFrame#AiConsultGlucoseReport QHeaderView::section {
background: #F7F8FC; color: #606163; border: 0; padding: 6px 3px; font-size: 12px;
}
"""
@dataclass(frozen=True, slots=True)
class GlucoseReading:
"""One source row. Missing series stay absent, including a whole-row gap."""
recorded_at: datetime
fasting: float | None = None
postprandial: float | None = None
other: float | None = None
has_recorded_time: bool = False
fasting_status: str = ""
postprandial_status: str = ""
other_status: str = ""
@property
def readout_count(self) -> int:
return sum(value is not None for value in (self.fasting, self.postprandial, self.other))
@property
def time_label(self) -> str:
if self.has_recorded_time:
pattern = "%Y-%m-%d %H:%M:%S" if self.recorded_at.second else "%Y-%m-%d %H:%M"
return self.recorded_at.strftime(pattern)
return self.recorded_at.strftime("%Y-%m-%d")
@dataclass(frozen=True, slots=True)
class GlucoseChartData:
readings: tuple[GlucoseReading, ...] = ()
diagnosis_id: int = 0
patient_id: int = 0
excluded_count: int = 0
unavailable_reason: str = ""
@property
def available(self) -> bool:
return self.readout_count > 0
@property
def readout_count(self) -> int:
return sum(reading.readout_count for reading in self.readings)
@property
def record_count(self) -> int:
return sum(reading.readout_count > 0 for reading in self.readings)
@property
def date_range(self) -> tuple[date, date] | None:
dates = [reading.recorded_at.date() for reading in self.readings if reading.readout_count]
return (min(dates), max(dates)) if dates else None
def _exact_owner(value: Any, expected: int) -> bool:
return type(value) is int and type(expected) is int and expected > 0 and value == expected
def _patient_matches(source: Mapping[str, Any], patient_id: int) -> bool:
if "patient_id" not in source:
return True
owner = source["patient_id"]
return type(owner) is int and owner > 0 and (patient_id <= 0 or owner == patient_id)
def _first(source: Mapping[str, Any], *keys: str) -> Any:
for key in keys:
value = source.get(key)
if value is not None and value != "":
return value
return None
def _rows(value: Any) -> list[Any]:
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
return list(value)
return []
def _unit_matches(source: Mapping[str, Any]) -> bool:
unit = _first(source, "unit", "glucose_unit", "blood_sugar_unit")
if unit is None:
return True
return isinstance(unit, str) and re.sub(r"\s", "", unit).casefold() == "mmol/l"
def _number(value: Any) -> tuple[float | None, bool]:
"""Return (reading, ambiguous); daily-record zero is the unfilled sentinel.
DailyRecordDialog writes every spinbox, whose zero text is 未填写. The server's
BloodRecordLogic likewise includes only >0 glucose values in its trend data.
"""
if value is None:
return None, False
if isinstance(value, str):
value = value.strip()
if value in _MISSING:
return None, False
if not _NUMERIC.fullmatch(value):
return None, True
value = re.sub(r"\s*mmol\s*/\s*l$", "", value, flags=re.IGNORECASE)
elif type(value) not in (int, float):
return None, True
try:
number = float(value)
except (OverflowError, TypeError, ValueError):
return None, True
if not math.isfinite(number) or number < 0:
return None, True
return (number, False) if number > 0 else (None, False)
def _recorded_at(row: Mapping[str, Any]) -> tuple[datetime, bool] | None:
value = _first(row, "record_date", "date", "measured_at", "time_text")
if not isinstance(value, str):
return None
value = value.strip()
try:
if _DATETIME.fullmatch(value):
return datetime.fromisoformat(value), True
if not _DATE.fullmatch(value):
return None
day = date.fromisoformat(value)
clock = row.get("record_time")
if clock is None or clock == "":
# Midnight positions a date-only observation; it is never displayed as a known time.
return datetime.combine(day, time.min), False
if not isinstance(clock, str) or not _TIME.fullmatch(clock.strip()):
return None
return datetime.combine(day, time.fromisoformat(clock.strip())), True
except ValueError:
return None
def _values(row: Mapping[str, Any], *, legacy: bool) -> tuple[dict[str, float | None], bool, bool]:
raw = {field: _first(row, *keys) for field, keys in _SERIES_KEYS.items()}
if legacy and all(value is None for value in raw.values()):
period = str(_first(row, "period", "time_slot", "meal") or "").strip().casefold()
target = "other"
if period in {"空腹", "空腹血糖", "fasting"}:
target = "fasting"
elif period in {
"餐后",
"餐后血糖",
"餐后2小时",
"餐后 2 小时",
"postprandial",
"postprandial_2h",
}:
target = "postprandial"
raw[target] = row.get("value")
parsed: dict[str, float | None] = {}
ambiguous = False
for field, value in raw.items():
parsed[field], invalid = _number(value)
ambiguous = ambiguous or invalid
return parsed, ambiguous, any(value is not None for value in raw.values())
def _statuses(row: Mapping[str, Any], *, legacy: bool) -> dict[str, str]:
"""Keep only explicit scalar states on the same verified source row."""
statuses = {}
for field, keys in _SERIES_KEYS.items():
raw = _first(row, *(f"{key}_status" for key in keys))
# Generic legacy states belong only to that row's single value/period.
if legacy and raw is None and all(_first(row, *keys) is None for keys in _SERIES_KEYS.values()):
values, _ambiguous, _has_fields = _values(row, legacy=True)
if values[field] is not None:
raw = _first(row, "value_status", "glucose_status", "blood_sugar_status", "status")
statuses[f"{field}_status"] = str(raw).strip() if type(raw) in (str, int) else ""
return statuses
def build_glucose_chart_data(
tracking: Any, *, diagnosis_id: int, patient_id: int = 0
) -> GlucoseChartData:
"""Snapshot only explicitly owned, dated observations without mutating the DTO.
Production blood_records takes precedence over legacy blood_sugar.entries to
avoid double plotting a response containing two representations of the same data.
"""
empty = GlucoseChartData(diagnosis_id=diagnosis_id, patient_id=patient_id)
if type(patient_id) is not int or patient_id < 0:
return GlucoseChartData(
diagnosis_id=diagnosis_id,
patient_id=0,
unavailable_reason="缺少可核验的患者归属信息。",
)
if not isinstance(tracking, Mapping):
return GlucoseChartData(
diagnosis_id=diagnosis_id,
patient_id=patient_id,
unavailable_reason="尚未加载本诊单的血糖记录。",
)
if not _exact_owner(tracking.get("diagnosis_id"), diagnosis_id) or not _patient_matches(
tracking, patient_id
):
return GlucoseChartData(
diagnosis_id=diagnosis_id,
patient_id=patient_id,
unavailable_reason="血糖记录未通过本诊单归属校验。",
)
expected_patient = patient_id or tracking.get("patient_id", 0)
legacy = "blood_records" not in tracking
section = tracking.get("blood_sugar") if legacy else tracking
if not isinstance(section, Mapping):
return empty
if legacy and (
("diagnosis_id" in section and not _exact_owner(section["diagnosis_id"], diagnosis_id))
or not _patient_matches(section, expected_patient)
):
return GlucoseChartData(
diagnosis_id=diagnosis_id,
patient_id=patient_id,
unavailable_reason="血糖记录未通过本诊单归属校验。",
)
expected_patient = expected_patient or section.get("patient_id", 0)
rows = (
_rows(_first(section, "entries", "records", "items"))
if legacy
else _rows(section.get("blood_records"))
)
readings: list[GlucoseReading] = []
excluded = 0
for row in rows:
if (
not isinstance(row, Mapping)
or not _exact_owner(row.get("diagnosis_id"), diagnosis_id)
or not _patient_matches(row, expected_patient)
):
excluded += 1
continue
if not _unit_matches(tracking) or not _unit_matches(section) or not _unit_matches(row):
excluded += 1
continue
recorded = _recorded_at(row)
if recorded is None:
excluded += 1
continue
values, ambiguous, has_fields = _values(row, legacy=legacy)
excluded += int(ambiguous)
if not has_fields:
continue
readings.append(GlucoseReading(
recorded[0], has_recorded_time=recorded[1], **values, **_statuses(row, legacy=legacy)
))
readings.sort(key=lambda reading: reading.recorded_at) # Stable: same-time rows stay separate.
return GlucoseChartData(tuple(readings), diagnosis_id, patient_id, excluded)
def _value_text(value: float | None) -> str:
return "—" if value is None else str(value).removesuffix(".0")
def _reading_status(reading: GlucoseReading, field: str) -> str:
if getattr(reading, field) is None:
return "未记录"
status = getattr(reading, f"{field}_status")
label = _STATUS_LABELS.get(status.casefold(), status) if status else "未标注"
return f"{label}(原始:{status})" if status and label != status else label
def _draw_marker(painter: QPainter, point: QPointF, series: str) -> None:
if series in {"postprandial", "diastolic_pressure"}:
painter.drawRect(QRectF(point.x() - 3.5, point.y() - 3.5, 7, 7))
elif series == "other":
painter.drawLine(QPointF(point.x() - 4, point.y()), QPointF(point.x() + 4, point.y()))
painter.drawLine(QPointF(point.x(), point.y() - 4), QPointF(point.x(), point.y() + 4))
else:
painter.drawEllipse(point, 3.5, 3.5)
class GlucoseTrendChart(QWidget):
"""An actual-date axis, with gaps and one point for every saved observation."""
def __init__(self, data: GlucoseChartData, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.data = data
self.setObjectName("AiConsultGlucoseChart")
self.setMinimumHeight(210)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.setMouseTracking(True)
self.setAccessibleName("本诊单血糖趋势图,单位 mmol/L")
description = []
for reading in data.readings:
values = ",".join(
f"{label} {_value_text(getattr(reading, field))}"
+ (" mmol/L" if getattr(reading, field) is not None else "")
+ f" · 状态 {_reading_status(reading, field)}"
for field, label, _style in _SERIES
)
if values:
description.append(f"{reading.time_label}:{values}")
self.setAccessibleDescription(
"空腹实线圆点、餐后虚线方点、其他点线十字;红色异常、绿色正常、灰色未记录/未标注。"
+ ";".join(description)
)
@staticmethod
def _point_color(reading: GlucoseReading, field: str) -> str:
return (
metric_color(getattr(reading, f"{field}_status"))
if getattr(reading, field) is not None
else UNKNOWN_COLOR
)
def sizeHint(self) -> QSize: # noqa: N802 - Qt API
return QSize(580, 220)
def _geometry(self) -> tuple[QRectF, datetime, float, float, float]:
plot = QRectF(self.rect()).adjusted(43, 32, -15, -35)
dates = [reading.recorded_at for reading in self.data.readings if reading.readout_count]
origin = min(dates) if dates else datetime.min
span = (max(dates) - origin).total_seconds() if dates else 0.0
values = [
value
for reading in self.data.readings
for value in (reading.fasting, reading.postprandial, reading.other)
if value is not None
]
lower, upper = (min(values), max(values)) if values else (0.0, 1.0)
padding = max(1.0, (upper - lower) * 0.18, upper * 0.05)
padded_upper = upper + padding
return (
plot,
origin,
span,
max(0.0, lower - padding),
padded_upper if math.isfinite(padded_upper) else upper,
)
def _position(
self,
reading: GlucoseReading,
value: float,
geometry: tuple[QRectF, datetime, float, float, float] | None = None,
) -> QPointF:
plot, origin, span, lower, upper = geometry or self._geometry()
x = (
plot.left() + plot.width() * (reading.recorded_at - origin).total_seconds() / span
if span
else plot.center().x()
)
y = plot.bottom() - plot.height() * ((value - lower) / (upper - lower))
return QPointF(x, y)
def _point_tooltip(self, position: QPointF) -> str:
hits: list[str] = []
geometry = self._geometry()
for index, reading in enumerate(self.data.readings, 1):
for field, label, _style in _SERIES:
value = getattr(reading, field)
if value is None:
continue
point = self._position(reading, value, geometry)
if (point.x() - position.x()) ** 2 + (point.y() - position.y()) ** 2 <= 100:
hits.append(
f"{reading.time_label} · 记录 {index}\n{label} {_value_text(value)} mmol/L"
f" · 状态 {_reading_status(reading, field)}"
)
return "\n\n".join(hits)
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt API
tip = self._point_tooltip(event.position())
if tip:
QToolTip.showText(event.globalPosition().toPoint(), tip, self)
else:
QToolTip.hideText()
super().mouseMoveEvent(event)
def leaveEvent(self, event: Any) -> None: # noqa: N802 - Qt API
QToolTip.hideText()
super().leaveEvent(event)
def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 - Qt API
super().paintEvent(event)
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
font = painter.font()
font.setPixelSize(11)
painter.setFont(font)
geometry = self._geometry()
plot, _origin, _span, lower, upper = geometry
if plot.width() <= 0 or plot.height() <= 0:
painter.end()
return
painter.setPen(QColor("#606163"))
painter.drawText(QRectF(0, 0, 55, 20), Qt.AlignmentFlag.AlignLeft, "mmol/L")
legend_x = 64.0
for field, label, style in _SERIES:
if not any(getattr(reading, field) is not None for reading in self.data.readings):
continue
painter.setPen(QPen(QColor(UNKNOWN_COLOR), 2, style))
painter.setBrush(QColor(UNKNOWN_COLOR))
painter.drawLine(QPointF(legend_x, 10), QPointF(legend_x + 17, 10))
_draw_marker(painter, QPointF(legend_x + 8, 10), field)
painter.setPen(QColor(UNKNOWN_COLOR))
short_label = label.replace("血糖", "")
painter.drawText(
QRectF(legend_x + 23, 0, 40, 20), Qt.AlignmentFlag.AlignLeft, short_label
)
legend_x += 64
for tick in range(4):
y = plot.bottom() - plot.height() * tick / 3
painter.setPen(QPen(QColor("#EDEDEE"), 1))
painter.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y))
painter.setPen(QColor("#606163"))
painter.drawText(
QRectF(0, y - 8, 35, 16),
Qt.AlignmentFlag.AlignRight,
f"{lower + (upper - lower) * (tick / 3):.1f}",
)
for field, _label, style in _SERIES:
previous: QPointF | None = None
for reading in self.data.readings:
value = getattr(reading, field)
if value is None:
previous = None
continue
point = self._position(reading, value, geometry)
if previous is not None:
painter.setPen(QPen(QColor(UNKNOWN_COLOR), 2, style))
painter.drawLine(previous, point)
previous = point
# Draw status markers after all neutral line segments in this series.
for reading in self.data.readings:
value = getattr(reading, field)
if value is None:
continue
color = QColor(self._point_color(reading, field))
painter.setPen(QPen(color, 2))
painter.setBrush(color)
_draw_marker(painter, self._position(reading, value, geometry), field)
painter.setPen(QColor("#606163"))
dates = sorted(
{reading.recorded_at.date() for reading in self.data.readings if reading.readout_count}
)
if len(dates) == 1:
painter.drawText(
QRectF(plot.center().x() - 52, plot.bottom() + 9, 104, 18),
Qt.AlignmentFlag.AlignCenter,
dates[0].isoformat(),
)
elif dates:
painter.drawText(
QRectF(plot.left(), plot.bottom() + 9, 104, 18),
Qt.AlignmentFlag.AlignLeft,
dates[0].isoformat(),
)
painter.drawText(
QRectF(plot.right() - 104, plot.bottom() + 9, 104, 18),
Qt.AlignmentFlag.AlignRight,
dates[-1].isoformat(),
)
painter.end()
class GlucoseReportCard(QFrame):
def __init__(self, data: GlucoseChartData, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.data = data
self.chart: GlucoseTrendChart | None = None
self.toggle_button: QPushButton | None = None
self.setObjectName("AiConsultGlucoseReport")
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
self.setStyleSheet(_CARD_QSS)
root = QVBoxLayout(self)
root.setContentsMargins(14, 12, 14, 12)
root.setSpacing(7)
title = QLabel("血糖变化趋势", self)
title.setObjectName("AiConsultGlucoseTitle")
root.addWidget(title)
self.table = QTableWidget(self)
self.table.setObjectName("AiConsultGlucoseTable")
self.table.hide()
if data.available:
count = QLabel(f"{data.readout_count} 次测量 · {data.record_count} 条记录", self)
count.setObjectName("AiConsultGlucoseCount")
root.addWidget(count)
self.chart = GlucoseTrendChart(data, self)
root.addWidget(self.chart)
if data.record_count == 1:
single = self._note("仅有 1 条记录,暂不连线。", "AiConsultGlucoseCount")
root.addWidget(single)
actions = QHBoxLayout()
actions.setContentsMargins(0, 0, 0, 0)
self.toggle_button = QPushButton("查看原始记录", self)
self.toggle_button.setObjectName("AiConsultGlucoseDataToggle")
self.toggle_button.setCheckable(True)
self.toggle_button.setAccessibleName("查看血糖原始记录")
self.toggle_button.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.toggle_button.toggled.connect(self._toggle_table)
actions.addWidget(self.toggle_button)
actions.addStretch(1)
root.addLayout(actions)
self._populate_table()
else:
root.addWidget(self._note("暂无可绘制的血糖记录", "AiConsultGlucoseState"))
reason = data.unavailable_reason or "尚无带明确日期的有效血糖读数。"
root.addWidget(self._note(reason, "AiConsultGlucoseSource"))
root.addWidget(self.table)
source = f"本诊单 #{data.diagnosis_id} 的已记录数据"
if data.date_range:
start, end = data.date_range
source += f" · {start.isoformat()}" + (f" 至 {end.isoformat()}" if end != start else "")
source += ";未填写处保留空缺。红色异常、绿色正常、灰色未记录/未标注;状态以原始记录为准。"
if data.excluded_count:
source += f"\n{data.excluded_count} 条记录含未纳入的内容(归属、日期或读数无法核验)。"
root.addWidget(self._note(source, "AiConsultGlucoseSource"))
def _note(self, text: str, name: str) -> QLabel:
label = QLabel(text, self)
label.setObjectName(name)
label.setTextFormat(Qt.TextFormat.PlainText)
label.setWordWrap(True)
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
return label
def _populate_table(self) -> None:
table = self.table
table.setColumnCount(4)
table.setRowCount(len(self.data.readings))
table.setHorizontalHeaderLabels(["记录日期 / 时间", "空腹", "餐后", "其他"])
table.setAccessibleName("血糖原始记录,读数单位 mmol/L")
table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
table.setAlternatingRowColors(True)
table.verticalHeader().hide()
table.verticalHeader().setDefaultSectionSize(29)
table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
table.horizontalHeader().setMinimumSectionSize(48)
table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
table.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
table.setFixedHeight(min(224, 35 + max(1, len(self.data.readings)) * 29))
for row_index, reading in enumerate(self.data.readings):
values = [
reading.time_label,
*(_value_text(getattr(reading, field)) for field, _, _ in _SERIES),
]
for column, text in enumerate(values):
item = QTableWidgetItem(text)
if column == 0:
item.setToolTip(text)
else:
field = _SERIES[column - 1][0]
item.setForeground(QColor(GlucoseTrendChart._point_color(reading, field)))
item.setToolTip(
(f"{text} mmol/L" if text != "—" else "— · 未记录或读数不明确")
+ f" · 状态 {_reading_status(reading, field)}"
)
table.setItem(row_index, column, item)
def _toggle_table(self, checked: bool) -> None:
self.table.setVisible(checked)
if self.toggle_button is not None:
self.toggle_button.setText("收起原始记录" if checked else "查看原始记录")
self.toggle_button.setAccessibleName(
"收起血糖原始记录" if checked else "查看血糖原始记录"
)
self.updateGeometry()
@@ -0,0 +1,86 @@
"""Shared display semantics for recorded indicator states; no threshold inference."""
from __future__ import annotations
from typing import Any
ABNORMAL_COLOR = "#BD4B58"
NORMAL_COLOR = "#287B65"
UNKNOWN_COLOR = "#697386"
_ABNORMAL = frozenset(
{
"high",
"low",
"abnormal",
"warning",
"positive",
"alert",
"偏高",
"偏低",
"升高",
"降低",
"高",
"低",
"异常",
"阳性",
"警告",
"需关注",
"临界",
"超标",
"未达标",
"不达标",
"控制不佳",
"控制欠佳",
"不正常",
"非正常",
"未恢复正常",
}
)
_NORMAL = frozenset(
{
"normal",
"negative",
"正常",
"阴性",
"达标",
"已达标",
"控制良好",
"未见异常",
"无异常",
"未发现异常",
"没有异常",
"0",
}
)
def metric_state(value: Any) -> str:
"""Normalize only explicit source states; an unclassified number stays unknown."""
text = str(value).strip().casefold() if type(value) in (str, int) else ""
if text in _ABNORMAL:
return "abnormal"
if text in _NORMAL:
return "normal"
return "unknown"
def metric_color(value: Any) -> str:
return {"abnormal": ABNORMAL_COLOR, "normal": NORMAL_COLOR}.get(
metric_state(value), UNKNOWN_COLOR
)
def risk_color(value: Any) -> str:
return {
"high": ABNORMAL_COLOR,
"medium": ABNORMAL_COLOR,
"low": NORMAL_COLOR,
}.get(value if isinstance(value, str) else "", UNKNOWN_COLOR)
def combined_metric_state(values: list[Any]) -> str:
states = [metric_state(value) for value in values]
if "abnormal" in states:
return "abnormal"
return "normal" if states and all(state == "normal" for state in states) else "unknown"
@@ -0,0 +1,411 @@
"""Conservative, display-only emphasis for clinical report text.
Measurements are identified by their units or an explicit clinical label. Colors
come from matching recorded states or explicit local assertions, never numeric
thresholds. All source text remains literal HTML text.
"""
from __future__ import annotations
import re
import unicodedata
from collections.abc import Iterator, Sequence
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from html import escape
from .ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
UNKNOWN_COLOR,
metric_state,
risk_color,
)
@dataclass(frozen=True)
class MetricTextState:
"""A source field, its displayed reading (including unit), and recorded state."""
label: str
value: str
status: str
_METRIC_STATES: ContextVar[tuple[MetricTextState, ...]] = ContextVar(
"metric_text_states", default=()
)
@contextmanager
def metric_text_context(states: Sequence[MetricTextState]) -> Iterator[None]:
"""Bind trusted states for synchronous rendering and restore the outer scope."""
token = _METRIC_STATES.set(tuple(states))
try:
yield
finally:
_METRIC_STATES.reset(token)
_NUMBER = r"[+\-−]?(?:\d+(?:\.\d+)?|\.\d+)"
_COMPARATOR = r"(?:(?:<=|>=|[<>≤≥≦≧≈=<>=]|小于|大于|不超过|不低于|不高于|低于|高于|约为|约)\s*)?"
_VALUE = rf"{_COMPARATOR}{_NUMBER}(?:\s*(?:[–—~~-\-]|至|到)\s*{_NUMBER})?"
_VALUE_START = r"(?<![A-Za-z0-9_.+\-−/])"
_VALUE_END = r"(?![A-Za-z0-9_.²³/]|\s*[–—~~-\-至到]\s*\d)"
_UNIT = (
r"(?:mL\s*/\s*min(?:\s*/\s*1\.73\s*m(?:²|2|\^2))?"
r"|(?:mmol|[μµu]mol)\s*/\s*L"
r"|mmol\s*/\s*mol"
r"|mg\s*/\s*(?:dL|mmol|g(?:Cr)?|L)"
r"|[μµu]g\s*/\s*(?:g|mg|L)"
r"|(?:ng|pg)\s*/\s*mL"
r"|(?:g|IU|U|mIU|mU)\s*/\s*L"
r"|g\s*/\s*dL"
r"|[μµu]IU\s*/\s*mL"
r"|kg\s*/\s*m(?:²|2|\^2)"
r"|mmHg|bpm|次\s*/\s*(?:分钟|分|min)"
r"|kg|cm|°\s*C|℃)"
)
_UNIT_END = r"(?![A-Za-z0-9_²³/])"
_PRESSURE_VALUE = rf"{_COMPARATOR}{_NUMBER}\s*[//]\s*{_NUMBER}\s*mmHg"
_UNIT_VALUE = rf"(?:{_PRESSURE_VALUE}|{_VALUE}\s*{_UNIT}){_UNIT_END}"
_UNIT_RE = re.compile(rf"{_VALUE_START}(?P<value>{_UNIT_VALUE})", re.IGNORECASE)
# A label is necessary when a number has no unit, or directly follows an ASCII
# label (a general numeric boundary intentionally rejects IDs such as abc123).
_LABEL_GAP = r"\s*[))]?\s*(?:(?:[::=]|为|约为|是|达到|下降至|降至|上升至|升至)\s*)?"
_LABEL_START = r"(?<![A-Za-z0-9_])"
_UNIT_LABELS = (
r"(?:fasting(?:[_ ]blood[_ ]sugar|[_ ](?:blood[_ ])?glucose)?|"
r"postprandial(?:[_ ]blood[_ ](?:sugar|glucose))?|"
r"FPG|FBG|PBG|PPG|TC|TG|LDL(?:-C)?|HDL(?:-C)?|UA|Scr|Cr|"
r"UACR|ACR|ALT|AST|SBP|DBP|BP|HR|eGFR|BMI|heart_rate|height|weight)"
)
_LABELED_UNIT_RE = re.compile(
rf"{_LABEL_START}{_UNIT_LABELS}{_LABEL_GAP}(?P<value>{_UNIT_VALUE})",
re.IGNORECASE,
)
_UNITLESS_RE = re.compile(
rf"{_LABEL_START}(?:BMI|体质指数|体质量指数|体重指数|eGFR|"
rf"估算肾小球滤过率|肾小球滤过率|heart_rate|心率){_LABEL_GAP}"
rf"(?P<value>{_VALUE}){_VALUE_END}",
re.IGNORECASE,
)
_HEIGHT_RE = re.compile(
rf"{_LABEL_START}(?:height|身高){_LABEL_GAP}"
rf"(?P<value>{_VALUE}\s*(?:cm|m|厘米|米)){_UNIT_END}",
re.IGNORECASE,
)
_PERCENT_LABEL = (
r"(?:HbA1c|glycated[_ ]h(?:a)?emoglobin|糖化血红蛋白(?:水平)?|"
r"SpO2|SaO2|血氧饱和度|血氧)"
)
_LABELED_PERCENT_RE = re.compile(
rf"{_LABEL_START}{_PERCENT_LABEL}{_LABEL_GAP}"
rf"(?P<value>{_VALUE}\s*[%%]){_VALUE_END}",
re.IGNORECASE,
)
_PERCENT_RE = re.compile(rf"{_VALUE_START}(?P<value>{_VALUE}\s*[%%]){_VALUE_END}")
_PERCENT_LABEL_RE = re.compile(rf"{_LABEL_START}{_PERCENT_LABEL}", re.IGNORECASE)
_UNRELATED_PERCENT_RE = re.compile(
r"占比|比例|概率|风险|增长|下降|降低|上升|提高|提升|改善|减轻|"
r"有效率|发生率|依从|完成率|百分比|报销|费用|患者|人群"
)
_CLAUSE_BOUNDARY_RE = re.compile(r"[,,。;;!!??\n]")
_SENTENCE_BOUNDARY_RE = re.compile(r"[。;;!!??\n]")
_REFERENCE_RE = re.compile(
r"目标|参考|理想|阈值|正常(?:值|范围)|\b(?:targets?|reference|ideal|thresholds?)\b",
re.IGNORECASE,
)
_CURRENT_RE = re.compile(
r"当前|现测|本次|实测|测得|检测结果|实际|目前|现值|\b(?:current|actual|measured)\b",
re.IGNORECASE,
)
_REFERENCE_SUFFIX_RE = re.compile(
r"^\s*[((](?:目标|参考|理想|阈值|正常)(?:值|范围)?[))]"
r"|^\s*\((?:target|reference|ideal|threshold)(?:\s*(?:value|range))?\)",
re.IGNORECASE,
)
_NORMAL_STATUS = (
r"(?:未见|未发现|没有|无)(?:其他)?(?:明显|显著)?异常"
r"|(?:基本|大致)?正常|(?:已|完全)?达标|控制良好"
r"|\b(?:normal|negative)\b"
)
_ABNORMAL_STATUS = (
r"(?:尚未完全|尚未|未完全|未能|不完全|未|不)达标"
r"|不正常|非正常|未恢复正常"
r"|(?:严重|明显|显著)?异常|控制不佳|控制欠佳"
r"|\b(?:not normal|abnormal|warning|high|low|positive|alert)\b"
)
_CAUTION_STATUS = r"(?:轻度|轻微|明显|显著|略)?(?:偏高|偏低|升高|降低)|临界|超标"
_STATUS_RE = re.compile(
rf"(?P<abnormal>{_ABNORMAL_STATUS})|(?P<normal>{_NORMAL_STATUS})"
rf"|(?P<caution>{_CAUTION_STATUS})",
re.IGNORECASE,
)
_RISK_STATUS_RE = re.compile(r"高风险|中风险|低风险")
_MISSING_RE = re.compile(
r"未记录|无记录|未检测|未测量|未检查|未提供|未填写|未录入|未获取|暂无数据|"
r"暂无|缺失|未知|待测|未测|未查|未做|无数据|"
r"\b(?:not recorded|not measured|not available|unrecorded|unknown|missing|N/A)\b",
re.IGNORECASE,
)
_NON_ASSERTIVE_RE = re.compile(
r"排除|排查|除外|警惕|预防|避免|防止|谨防|建议|可能|疑似|怀疑|"
r"是否|待排|待查|如果|假如|一旦|若|如|风险|倾向|有望|争取|力争|以期|"
r"应当|应该|应使|应将|应控制|应达到|应达标|需使|需将|需达到|以达到"
r"|\b(?:possible|possibly|may|might|should|if|risk|exclude|suspected)\b",
re.IGNORECASE,
)
_NEGATED_PREFIX_RE = re.compile(
r"(?:尚未|未见|未发现|未达到|未能达到|未能|不能|无法|难以|未|没有|无|不|非)"
r"(?:明显|显著|完全|充分)?$"
)
_MISSING_PLACEHOLDER_RE = re.compile(r"\s*(?:[—–--]+|/|null|none)\s*\Z", re.IGNORECASE)
# An alias identifies a source field, never a diagnosis. More specific aliases
# win over contained words, so 空腹血糖 cannot accidentally match generic 血糖.
_FIELD_ALIASES = (
("hba1c", r"HbA1c|glycated[_ ]h(?:a)?emoglobin|糖化血红蛋白(?:水平)?"),
("fasting", r"fasting(?:[_ ]blood[_ ]sugar|[_ ](?:blood[_ ])?glucose)?|FPG|FBG|空腹血糖|空腹"),
(
"postprandial",
r"postprandial(?:[_ ]blood[_ ](?:sugar|glucose))?|PBG|PPG|餐后(?:2|两|二)?(?:小时)?血糖|餐后",
),
("random_glucose", r"random[_ ](?:blood[_ ])?(?:sugar|glucose)|随机血糖"),
("glucose", r"blood[_ ](?:sugar|glucose)|glucose|血糖"),
("blood_pressure", r"blood[_ ]pressure|BP|血压"),
("systolic", r"systolic(?:[_ ](?:blood[_ ])?pressure)?|SBP|收缩压"),
("diastolic", r"diastolic(?:[_ ](?:blood[_ ])?pressure)?|DBP|舒张压"),
("bmi", r"BMI|体质指数|体质量指数|体重指数"),
("heart_rate", r"heart[_ ]rate|HR|心率"),
("height", r"height|身高"),
("weight", r"weight|体重"),
("ldl", r"LDL(?:[-_ ]C)?|低密度脂蛋白(?:胆固醇)?"),
("hdl", r"HDL(?:[-_ ]C)?|高密度脂蛋白(?:胆固醇)?"),
("cholesterol", r"TC|total[_ ]cholesterol|总胆固醇"),
("triglycerides", r"TG|triglycerides?|甘油三酯"),
("egfr", r"eGFR|估算肾小球滤过率|肾小球滤过率"),
("uacr", r"UACR|ACR|尿白蛋白(?:与)?肌酐比(?:值)?"),
("creatinine", r"Scr|Cr|creatinine|血(?:清)?肌酐|肌酐"),
("uric_acid", r"UA|uric[_ ]acid|尿酸"),
("alt", r"ALT|丙氨酸氨基转移酶|谷丙转氨酶"),
("ast", r"AST|天门冬氨酸氨基转移酶|谷草转氨酶"),
("spo2", r"SpO2|SaO2|血氧饱和度|血氧"),
("temperature", r"temperature|体温"),
("hemoglobin", r"h(?:a)?emoglobin|血红蛋白"),
)
_FIELD_PATTERNS = tuple(
(field, re.compile(rf"{_LABEL_START}(?:{aliases})(?![A-Za-z_])", re.IGNORECASE))
for field, aliases in _FIELD_ALIASES
)
_STANDALONE_VALUE_RE = re.compile(rf"\s*(?P<value>{_VALUE}(?:\s*[%%])?)\s*\Z")
def _display_key(value: str) -> str:
return re.sub(r"\s+", "", unicodedata.normalize("NFKC", value)).casefold()
def _field_mentions(text: str) -> list[tuple[int, int, str]]:
mentions = [
(match.start(), match.end(), field)
for field, pattern in _FIELD_PATTERNS
for match in pattern.finditer(text)
]
# Unknown source labels can still bind to an exact label in the rendered text.
for state in _METRIC_STATES.get():
label = state.label.strip()
if not label or any(pattern.search(label) for _, pattern in _FIELD_PATTERNS):
continue
pattern = re.compile(rf"{_LABEL_START}{re.escape(label)}(?![A-Za-z_])", re.IGNORECASE)
mentions.extend((m.start(), m.end(), _display_key(label)) for m in pattern.finditer(text))
mentions.sort(key=lambda item: (item[0], -(item[1] - item[0])))
selected: list[tuple[int, int, str]] = []
for mention in mentions:
if not selected or mention[0] >= selected[-1][1]:
selected.append(mention)
return selected
def _field_key(label: str) -> str:
mentions = _field_mentions(label)
return mentions[-1][2] if mentions else _display_key(label)
def _reading_field(text: str, start: int, metric_label: str) -> str:
_, clause_start = _clause(text, start)
mentions = _field_mentions(text[clause_start:start])
return mentions[-1][2] if mentions else _field_key(metric_label)
def _recorded_color(text: str, start: int, end: int, metric_label: str) -> str | None:
field = _reading_field(text, start, metric_label)
if not field:
return None
reading = _display_key(text[start:end])
states = {
metric_state(state.status)
for state in _METRIC_STATES.get()
if _field_key(state.label) == field and _display_key(state.value) == reading
}
if not states:
return None
if len(states) != 1:
return UNKNOWN_COLOR
return {"normal": NORMAL_COLOR, "abnormal": ABNORMAL_COLOR}.get(states.pop(), UNKNOWN_COLOR)
def _clause(text: str, position: int) -> tuple[str, int]:
start = 0
for boundary in _CLAUSE_BOUNDARY_RE.finditer(text, 0, position):
start = boundary.end()
boundary = _CLAUSE_BOUNDARY_RE.search(text, position)
end = boundary.start() if boundary else len(text)
return text[start:end], start
def _is_reference(text: str, start: int, end: int) -> bool:
clause, clause_start = _clause(text, start)
prefix = clause[: start - clause_start][-64:]
references = list(_REFERENCE_RE.finditer(prefix))
current = list(_CURRENT_RE.finditer(prefix))
if references and (not current or references[-1].start() > current[-1].start()):
return True
return bool(_REFERENCE_SUFFIX_RE.match(text[end:]))
def _is_reference_percent(text: str, start: int, end: int) -> bool:
if not _is_reference(text, start, end):
return False
sentence_start = 0
for boundary in _SENTENCE_BOUNDARY_RE.finditer(text, 0, start):
sentence_start = boundary.end()
prefix = text[max(sentence_start, start - 100) : start]
labels = list(_PERCENT_LABEL_RE.finditer(prefix))
if not labels:
return False
return not _UNRELATED_PERCENT_RE.search(prefix[labels[-1].end() :])
def _status_color(text: str, match: re.Match[str]) -> str | None:
clause, clause_start = _clause(text, match.start())
if _NON_ASSERTIVE_RE.search(clause):
return None
prefix = text[max(clause_start, match.start() - 12) : match.start()]
if _NEGATED_PREFIX_RE.search(prefix):
return None
if text[match.end() :].startswith(("率", "值", "范围", "标准", "目标", "阈值")):
return None
if match.lastgroup == "normal":
return NORMAL_COLOR
return ABNORMAL_COLOR
def _local_color(
text: str,
start: int,
end: int,
readings: Sequence[tuple[int, int]],
statuses: Sequence[tuple[re.Match[str], str]],
metric_label: str,
) -> str:
clause, clause_start = _clause(text, start)
field = _reading_field(text, start, metric_label)
colors: set[str] = set()
for status, color in statuses:
if not clause_start <= status.start() < clause_start + len(clause):
continue
left, right = (end, status.start()) if status.start() >= end else (status.end(), start)
if right < left or right - left > 32:
continue
if any(left <= other_start < right for other_start, _ in readings):
continue
# A status belonging to a new field in the same clause must not leak.
mentions = _field_mentions(text[left:right])
if any(other_field != field for _, _, other_field in mentions):
continue
colors.add(color)
return colors.pop() if len(colors) == 1 else UNKNOWN_COLOR
def metric_text_html(text: str, *, metric_label: str = "") -> str:
"""Return escaped, whitespace-preserving HTML with conservative emphasis.
Clinical values retain their original range, comparator, unit and spelling.
A bound state requires the same field alias and displayed reading, including
comparator, range and unit. Without a matching record only an asserted local
status can classify a reading. References and unclassified values stay gray.
Newlines follow Qt plain text; incoming HTML is always shown literally.
"""
text = text.replace("\r\n", "\n").replace("\r", "\n")
spans: list[tuple[int, int, str]] = []
candidates: set[tuple[int, int]] = set()
for pattern in (_UNIT_RE, _LABELED_UNIT_RE, _UNITLESS_RE, _HEIGHT_RE, _LABELED_PERCENT_RE):
for match in pattern.finditer(text):
candidates.add(match.span("value"))
for match in _PERCENT_RE.finditer(text):
start, end = match.span("value")
clause, clause_start = _clause(text, start)
hinted_percent = _field_key(metric_label) in {
"hba1c",
"spo2",
} and not _UNRELATED_PERCENT_RE.search(clause[: start - clause_start])
if hinted_percent or _is_reference_percent(text, start, end):
candidates.add((start, end))
if metric_label and (standalone := _STANDALONE_VALUE_RE.fullmatch(text)):
candidates.add(standalone.span("value"))
readings: list[tuple[int, int]] = []
for start, end in sorted(candidates, key=lambda span: (span[0], -span[1])):
if not readings or start >= readings[-1][1]:
readings.append((start, end))
statuses = [
(match, color)
for match in _STATUS_RE.finditer(text)
if (color := _status_color(text, match))
]
for start, end in readings:
if _is_reference(text, start, end) or _REFERENCE_RE.search(metric_label):
color = UNKNOWN_COLOR
else:
color = _recorded_color(text, start, end, metric_label)
if color is None:
color = _local_color(text, start, end, readings, statuses, metric_label)
spans.append((start, end, color))
spans.extend((match.start(), match.end(), color) for match, color in statuses)
for match in _RISK_STATUS_RE.finditer(text):
clause, clause_start = _clause(text, match.start())
prefix = text[max(clause_start, match.start() - 12) : match.start()]
if (
_NON_ASSERTIVE_RE.search(clause.replace("风险", ""))
or _NEGATED_PREFIX_RE.search(prefix)
or _REFERENCE_RE.search(clause)
):
continue
level = {"高风险": "high", "中风险": "medium", "低风险": "low"}[match.group()]
spans.append((match.start(), match.end(), risk_color(level)))
spans.extend(
(match.start(), match.end(), UNKNOWN_COLOR) for match in _MISSING_RE.finditer(text)
)
if metric_label and _MISSING_PLACEHOLDER_RE.fullmatch(text):
spans.append((0, len(text), UNKNOWN_COLOR))
# Prefer a full reading over a contained unitless value, then consume each
# original character once. Generated markup is never scanned by a regex.
spans.sort(key=lambda span: (span[0], -(span[1] - span[0])))
pieces = ['<span style="white-space: pre-wrap;">']
position = 0
for start, end, color in spans:
if start < position:
continue
pieces.append(escape(text[position:start]))
pieces.append(
f'<span style="color: {color}; font-weight: 600;">{escape(text[start:end])}</span>'
)
position = end
pieces.append(escape(text[position:]))
pieces.append("</span>")
return "".join(pieces).replace("\n", "<br>")
@@ -0,0 +1,953 @@
"""Content-selected native report visuals backed only by owned source records.
Generated prose selects topics; it never supplies numeric observations, dates,
reference limits, or risk levels. All render data is an immutable snapshot.
"""
from __future__ import annotations
import math
import re
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, fields, is_dataclass
from datetime import datetime
from typing import Any
from PySide6.QtCore import QPointF, QRectF, QSize, Qt
from PySide6.QtGui import QColor, QMouseEvent, QPainter, QPaintEvent, QPen
from PySide6.QtWidgets import (
QAbstractItemView,
QFrame,
QHeaderView,
QLabel,
QPushButton,
QSizePolicy,
QTableWidget,
QTableWidgetItem,
QToolTip,
QVBoxLayout,
QWidget,
)
from .ai_consult_charts import (
GlucoseChartData,
GlucoseReportCard,
_draw_marker,
_recorded_at,
build_glucose_chart_data,
)
from .ai_consult_metric_state import UNKNOWN_COLOR, metric_color, risk_color
_NUMBER = r"(?:\d+(?:\.\d+)?|\.\d+)"
_RANGE = re.compile(rf"({_NUMBER})\s*[-–—~~至]\s*({_NUMBER})")
_TOPICS = {
"glucose": r"血糖|糖尿病|糖化|glucose|glyc[ae]m|hba1c|\ba1c\b",
"blood_pressure": r"血压|收缩压|舒张压|blood\s*pressure|hypertension|hypotension",
"lipids": r"血脂|胆固醇|甘油三酯|脂蛋白|lipid|cholesterol|triglyceride|\b[hl]dl\b",
"renal": r"肾|肌酐|尿素|尿酸|尿微量白蛋白|renal|kidney|creatinine|egfr|albumin",
"weight": r"体重|肥胖|减重|体质指数|weight|\bbmi\b|obesity",
"risk": r"风险|并发症|risk|complication",
"medication": r"用药|药物|处方|服药|药方|治疗方案|medication|prescription|\bdrug",
"activity": r"运动|活动|锻炼|exercise|activity|walking",
}
_OVERVIEW = re.compile(
r"综合|全面|总体|健康概览|病情总结|总结.*病情|病情.*总结|overall|comprehensive", re.I
)
_NEUTRAL = UNKNOWN_COLOR
_RISK_LABELS = {"low": "低风险", "medium": "中风险", "high": "高风险", "unknown": "未知"}
_STATUS_LABELS = {
"high": "偏高", "low": "偏低", "normal": "正常", "abnormal": "异常",
"warning": "需关注", "0": "正常", "unknown": "未标注",
}
def _status_label(item: VisualDatum) -> str:
if item.raw_value == "—":
return "未记录"
labels = _RISK_LABELS if item.raw_value == _RISK_LABELS.get(item.status) else _STATUS_LABELS
return labels.get(item.status.casefold(), item.status) or "未标注"
@dataclass(frozen=True, slots=True)
class VisualDatum:
label: str
raw_value: str
value: float | None = None
unit: str = ""
recorded_at: datetime | None = None
time_label: str = ""
series: str = ""
status: str = ""
color: str = _NEUTRAL
interval: tuple[float, float] | None = None
reference: tuple[float, float] | None = None
@property
def value_text(self) -> str:
return self.raw_value + (f" {self.unit}" if self.unit and self.raw_value != "—" else "")
@dataclass(frozen=True, slots=True)
class ReportVisual:
kind: str
title: str
items: tuple[VisualDatum, ...]
source: str
diagnosis_id: int
patient_id: int = 0
# Defaults are the units used by the existing diagnosis / reception fields.
# A declared source unit always takes precedence, without conversion.
_METRICS = (
("glucose", "空腹血糖", ("fasting_blood_sugar", "fasting_glucose"), "mmol/L"),
("glucose", "餐后血糖", ("postprandial_blood_sugar", "postprandial_glucose"), "mmol/L"),
("glucose", "糖化血红蛋白", ("glycated_hemoglobin", "hba1c", "glycosylated_hemoglobin"), "%"),
("blood_pressure", "收缩压", ("systolic_pressure", "systolic"), "mmHg"),
("blood_pressure", "舒张压", ("diastolic_pressure", "diastolic"), "mmHg"),
("lipids", "总胆固醇", ("total_cholesterol", "cholesterol"), "mmol/L"),
("lipids", "甘油三酯", ("triglycerides", "triglyceride"), "mmol/L"),
("lipids", "高密度脂蛋白", ("hdl_c", "hdl", "high_density_lipoprotein"), "mmol/L"),
("lipids", "低密度脂蛋白", ("ldl_c", "ldl", "low_density_lipoprotein"), "mmol/L"),
("renal", "尿微量白蛋白", ("urine_microalbumin", "microalbumin", "urinary_albumin"), "mg/L"),
("renal", "肌酐", ("creatinine", "serum_creatinine"), "μmol/L"),
("renal", "尿素氮", ("blood_urea_nitrogen", "bun"), "mmol/L"),
("renal", "尿酸", ("uric_acid",), "μmol/L"),
("renal", "估算肾小球滤过率", ("egfr",), "mL/min/1.73m²"),
("weight", "体重", ("weight",), "kg"),
("weight", "身高", ("height",), "cm"),
("weight", "BMI", ("bmi",), "kg/m²"),
)
def _mapping(value: Any) -> Mapping[str, Any]:
if isinstance(value, Mapping):
return value
if is_dataclass(value) and not isinstance(value, type):
result = {field.name: getattr(value, field.name) for field in fields(value)}
raw = result.pop("raw", None)
if isinstance(raw, Mapping):
# Preserve original ownership values rather than trusting DTO coercions.
result.update(raw)
return result
return {}
def _rows(value: Any) -> tuple[Any, ...]:
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
return tuple(value)
return ()
def _first(source: Mapping[str, Any], *keys: str) -> Any:
return next((source[key] for key in keys if source.get(key) not in (None, "")), None)
def _exact(value: Any, expected: int) -> bool:
return type(value) is int and type(expected) is int and expected > 0 and value == expected
def _patient_matches(source: Mapping[str, Any], expected: int) -> bool:
if "patient_id" not in source:
return True
owner = source["patient_id"]
return type(owner) is int and owner > 0 and (expected == 0 or owner == expected)
def _owned(source: Mapping[str, Any], diagnosis_id: int, patient_id: int) -> bool:
return _exact(source.get("diagnosis_id"), diagnosis_id) and _patient_matches(source, patient_id)
def _declared_owners_match(source: Mapping[str, Any], diagnosis_id: int, patient_id: int) -> bool:
return (
"diagnosis_id" not in source or _exact(source["diagnosis_id"], diagnosis_id)
) and _patient_matches(source, patient_id)
def _section(sections: Mapping[str, Any], key: str) -> Any:
section = _mapping(sections.get(key))
return None if section.get("error") else section.get("value")
def _numeric(value: Any, unit: str = "", *, allow_zero: bool = False) -> float | None:
if isinstance(value, str):
value = value.strip()
suffix = rf"(?:\s*{re.escape(unit)})?" if unit else ""
match = re.fullmatch(rf"({_NUMBER}){suffix}", value, re.I)
if match is None:
return None
value = match.group(1)
elif type(value) not in (int, float):
return None
try:
number = float(value)
except (ValueError, TypeError, OverflowError):
return None
# Zero is the unfilled spinbox sentinel for these existing clinical fields.
return number if math.isfinite(number) and (number > 0 or allow_zero and number == 0) else None
def _interval(value: Any, unit: str) -> tuple[float, float] | None:
if not isinstance(value, str):
return None
text = value.strip()
if unit and text.casefold().endswith(unit.casefold()):
text = text[: -len(unit)].strip()
match = _RANGE.fullmatch(text)
if match:
low, high = (
_numeric(match.group(1), allow_zero=True),
_numeric(match.group(2), allow_zero=True),
)
if low is not None and high is not None and low < high:
return low, high
return None
def _number_text(value: float) -> str:
return str(value).removesuffix(".0")
def _plain(value: Any) -> str:
return str(value).strip() if type(value) in (str, int, float) else ""
def _reference(
source: Mapping[str, Any], keys: tuple[str, ...], unit: str
) -> tuple[float, float] | None:
for key in keys:
value = source.get(f"{key}_reference_range")
if isinstance(value, Mapping):
ref_unit = value.get("unit", unit)
low, high = (
_numeric(value.get("low"), unit, allow_zero=True),
_numeric(value.get("high"), unit, allow_zero=True),
)
if ref_unit == unit and low is not None and high is not None and low < high:
return low, high
elif (interval := _interval(value, unit)) is not None:
return interval
low = _numeric(source.get(f"{key}_reference_low"), unit, allow_zero=True)
high = _numeric(source.get(f"{key}_reference_high"), unit, allow_zero=True)
if low is not None and high is not None and low < high:
return low, high
return None
def _snapshot_items(
detail: Mapping[str, Any],
topics: set[str],
diagnosis_id: int,
patient_id: int,
*,
glucose_trend: bool,
pressure_trend: bool,
) -> tuple[VisualDatum, ...]:
diagnosis = _mapping(detail.get("diagnosis"))
sources = [diagnosis]
for base in (diagnosis, detail):
for key in ("vitals", "lab_results", "labs"):
source = _mapping(base.get(key))
if source and _declared_owners_match(source, diagnosis_id, patient_id):
sources.append(source)
result = []
for topic, label, keys, default_unit in _METRICS:
if topic not in topics:
continue
if pressure_trend and topic == "blood_pressure":
continue
if glucose_trend and keys[0] in {"fasting_blood_sugar", "postprandial_blood_sugar"}:
continue
for source in sources:
raw = _first(source, *keys)
if raw is None:
continue
unit = _plain(_first(source, *(f"{key}_unit" for key in keys))) or default_unit
value, interval = _numeric(raw, unit), _interval(raw, unit)
if value is None and interval is None:
break
status = _plain(_first(source, *(f"{key}_status" for key in keys)))
# Reception also uses hdl_status / ldl_status for *_c aliases.
if not status and keys[0] in {"hdl_c", "ldl_c"}:
status = _plain(source.get(f"{keys[1]}_status"))
raw_text = _number_text(value) if value is not None else _plain(raw)
if interval and unit and raw_text.casefold().endswith(unit.casefold()):
raw_text = raw_text[: -len(unit)].strip()
result.append(
VisualDatum(
label,
raw_text,
value,
unit,
status=status,
color=metric_color(status),
interval=interval,
reference=_reference(source, keys, unit),
)
)
break
# The detail loader has already verified this patient's identity. Body
# measurements may live in patient rather than in the visit's diagnosis.
patient = _mapping(detail.get("patient"))
existing = {item.label for item in result}
if "weight" in topics and _patient_matches(patient, patient_id):
for _topic, label, keys, default_unit in _METRICS:
if _topic != "weight" or label in existing:
continue
unit = _plain(_first(patient, *(f"{key}_unit" for key in keys))) or default_unit
value = _numeric(_first(patient, *keys), unit)
if value is not None:
status = _plain(_first(patient, *(f"{key}_status" for key in keys)))
result.append(VisualDatum(
label, _number_text(value), value, unit, status=status,
color=metric_color(status),
))
return tuple(result)
def _tracking_visual(
tracking: Any,
*,
diagnosis_id: int,
patient_id: int,
activity: bool = False,
) -> ReportVisual | None:
source = _mapping(tracking)
if not _owned(source, diagnosis_id, patient_id):
return None
patient_id = patient_id or source.get("patient_id", 0)
items = []
definitions = (
((("duration",), "运动时长"),)
if activity
else (
(("systolic_pressure", "systolic"), "收缩压"),
(("diastolic_pressure", "diastolic"), "舒张压"),
)
)
unit = "分钟" if activity else "mmHg"
unit_keys = (
("duration_unit", "exercise_unit") if activity else ("pressure_unit", "blood_pressure_unit")
)
for raw in _rows(source.get("exercise_records" if activity else "blood_records")):
row = _mapping(raw)
if not _owned(row, diagnosis_id, patient_id) or (recorded := _recorded_at(row)) is None:
continue
declared_unit = _first(row, *unit_keys)
root_unit = _first(source, *unit_keys)
if any(value is not None and value != unit for value in (declared_unit, root_unit)):
continue
timestamp, has_time = recorded
time_label = (
timestamp.strftime("%Y-%m-%d %H:%M:%S" if timestamp.second else "%Y-%m-%d %H:%M")
if has_time
else timestamp.date().isoformat()
)
for keys, label in definitions:
value = _numeric(_first(row, *keys), unit)
status = _plain(_first(row, *(f"{key}_status" for key in keys)))
items.append(
VisualDatum(
label,
_number_text(value) if value is not None else "—",
value,
unit,
timestamp,
time_label,
keys[0],
status=status,
color=metric_color(status) if value is not None else UNKNOWN_COLOR,
)
)
if not any(item.value is not None for item in items):
return None
items.sort(key=lambda item: item.recorded_at or datetime.min)
title = "运动时长记录" if activity else "血压变化趋势"
return ReportVisual(
"exercise" if activity else "blood_pressure",
title,
tuple(items),
f"本诊单 #{diagnosis_id} 的已记录数据 · {unit};按实际记录日期排列。"
"红色异常、绿色正常、灰色未记录/未标注;状态以原始记录为准。",
diagnosis_id,
patient_id,
)
def _analysis_payload(raw: Any, diagnosis_id: int, patient_id: int) -> Mapping[str, Any]:
"""Unwrap one saved report, carrying its ownership through every envelope."""
current = _mapping(raw)
result: dict[str, Any] = {}
for _depth in range(5):
if not current or not _patient_matches(current, patient_id):
return {}
declared = current.get("diagnosis_id")
source_ids = current.get("source_diagnosis_ids", result.get("source_diagnosis_ids"))
# A patient report may cover several visits. Its explicit, exact source
# IDs can establish report ownership but never measurement ownership.
longitudinal = (
patient_id > 0
and _exact(current.get("patient_id", result.get("patient_id")), patient_id)
and diagnosis_id in _rows(source_ids)
and all(type(item) is int and item > 0 for item in _rows(source_ids))
)
if (
"diagnosis_id" in current
and not _exact(declared, diagnosis_id)
and not (longitudinal and type(declared) is int and declared > 0)
):
return {}
result.update(current)
if isinstance(current.get("report"), Mapping):
current = current["report"]
elif isinstance(current.get("latest_by_model"), Mapping):
latest = current["latest_by_model"]
current = next(
(
_mapping(latest.get(key))
for key in ("qwen", "openai")
if _mapping(latest.get(key))
),
{},
)
elif _rows(current.get("reports")):
current = _mapping(_rows(current["reports"])[0])
else:
break
source_ids = _rows(result.get("source_diagnosis_ids"))
owned = _exact(result.get("diagnosis_id"), diagnosis_id) or (
patient_id > 0
and _exact(result.get("patient_id"), patient_id)
and diagnosis_id in source_ids
and all(type(item) is int and item > 0 for item in source_ids)
)
return result if owned else {}
def _risk_visual(raw: Any, diagnosis_id: int, patient_id: int) -> ReportVisual | None:
analysis = _analysis_payload(raw, diagnosis_id, patient_id)
items = []
for raw_row in _rows(analysis.get("risk_assessment")):
row = _mapping(raw_row)
label, level = _plain(row.get("label")), row.get("level")
if not label or not _declared_owners_match(row, diagnosis_id, patient_id):
continue
if not isinstance(level, str) or level not in _RISK_LABELS:
continue
items.append(
VisualDatum(label, _RISK_LABELS[level], status=level, color=risk_color(level))
)
if not items:
return None
source_ids = _rows(analysis.get("source_diagnosis_ids"))
visits = "、".join(f"#{item}" for item in source_ids if type(item) is int and item > 0)
source = "AI 报告的定性风险标注 · 保留报告原始等级"
if visits:
source += f" · 报告来源诊单 {visits}"
return ReportVisual("risks", "风险分层", tuple(items), source, diagnosis_id, patient_id)
def _medication_visual(raw: Any, diagnosis_id: int, patient_id: int) -> ReportVisual | None:
if isinstance(raw, Mapping):
if not _owned(raw, diagnosis_id, patient_id):
return None
patient_id = patient_id or raw.get("patient_id", 0)
rows = _rows(_first(raw, "items", "records", "lists"))
else:
rows = _rows(raw)
items = []
for raw_row in rows:
row = _mapping(raw_row)
if not _owned(row, diagnosis_id, patient_id):
continue
name = _plain(_first(row, "prescription_name", "prescription_summary", "summary", "name"))
if not name:
names = [_plain(_mapping(herb).get("name")) for herb in _rows(row.get("herbs"))]
name = "、".join(value for value in names if value)
recorded = _recorded_at({"date": _first(row, "prescription_date", "create_time")})
status = _plain(_first(row, "status_text", "audit_status_text"))
if not status:
audit = row.get("audit_status")
status = (
{0: "待审核", 1: "已通过", 2: "已驳回"}.get(audit, "") if type(audit) is int else ""
)
if type(row.get("void_status")) is int and row["void_status"] == 1:
status = f"{status} · 已作废" if status else "已作废"
if not name or recorded is None or not status:
continue
timestamp, has_time = recorded
time_label = (
timestamp.isoformat(sep=" ", timespec="seconds" if timestamp.second else "minutes")
if has_time
else timestamp.date().isoformat()
)
items.append(
VisualDatum(name, status, recorded_at=timestamp, time_label=time_label, status=status)
)
if not items:
return None
items.sort(key=lambda item: item.recorded_at or datetime.min)
return ReportVisual(
"medications",
"处方记录时间线",
tuple(items),
f"本诊单 #{diagnosis_id} 的处方开具事件 · 日期、方名和状态来自原始处方。",
diagnosis_id,
patient_id,
)
def build_report_visuals(
prompt: str,
reply: str,
*,
sections: Mapping[str, Any],
diagnosis_id: int,
patient_id: int = 0,
) -> tuple[GlucoseChartData | ReportVisual, ...]:
"""Select only relevant, usable source visuals. Empty input makes no shell."""
if (
type(diagnosis_id) is not int
or diagnosis_id <= 0
or type(patient_id) is not int
or patient_id < 0
):
return ()
if not isinstance(sections, Mapping) or not _declared_owners_match(
sections, diagnosis_id, patient_id
):
return ()
detail = _mapping(_section(sections, "detail"))
if detail:
diagnosis = _mapping(detail.get("diagnosis"))
if (
not _exact(diagnosis.get("id"), diagnosis_id)
or not _declared_owners_match(diagnosis, diagnosis_id, patient_id)
or not _declared_owners_match(detail, diagnosis_id, patient_id)
):
return ()
patient = _mapping(detail.get("patient"))
patient_id = patient_id or diagnosis.get("patient_id", 0) or detail.get("patient_id", 0)
if "id" in patient and not _exact(patient["id"], patient_id or patient["id"]):
return ()
patient_id = patient_id or patient.get("id", 0)
if not all(_patient_matches(source, patient_id) for source in (detail, diagnosis, patient)):
return ()
text = f"{prompt}\n{reply}"
topics = (
set(_TOPICS)
if _OVERVIEW.search(text)
else {topic for topic, pattern in _TOPICS.items() if re.search(pattern, text, re.I)}
)
result: list[GlucoseChartData | ReportVisual] = []
tracking = _section(sections, "tracking")
if "glucose" in topics:
glucose = build_glucose_chart_data(
tracking, diagnosis_id=diagnosis_id, patient_id=patient_id
)
if glucose.available:
result.append(glucose)
pressure = (
_tracking_visual(tracking, diagnosis_id=diagnosis_id, patient_id=patient_id)
if "blood_pressure" in topics
else None
)
if pressure:
result.append(pressure)
metrics = _snapshot_items(
detail,
topics,
diagnosis_id,
patient_id,
glucose_trend=any(isinstance(item, GlucoseChartData) for item in result),
pressure_trend=pressure is not None,
)
if metrics:
result.append(
ReportVisual(
"metrics",
"相关指标快照",
metrics,
f"本诊单 #{diagnosis_id} 的病历记录 · 红色异常、绿色正常、灰色未记录/未标注;各指标独立展示。",
diagnosis_id,
patient_id,
)
)
if "risk" in topics and (
risk := _risk_visual(_section(sections, "analysis"), diagnosis_id, patient_id)
):
result.append(risk)
if "medication" in topics and (
medication := _medication_visual(
_section(sections, "prescriptions"), diagnosis_id, patient_id
)
):
result.append(medication)
if "activity" in topics and (
activity := _tracking_visual(
tracking, diagnosis_id=diagnosis_id, patient_id=patient_id, activity=True
)
):
result.append(activity)
return tuple(result)
class ReportPlot(QWidget):
"""Small native charts with exact record tooltips and accessible readouts."""
def __init__(self, data: ReportVisual, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.data = data
self.setObjectName("AiConsultReportPlot")
self.setMouseTracking(True)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.setMinimumWidth(0)
self.setFixedHeight(214 if self._trend else len(data.items) * self._row_height)
self.setAccessibleName(data.title)
legend = "红色异常、绿色正常、灰色未记录/未标注。"
if data.kind == "blood_pressure":
legend += "收缩压实线圆点,舒张压虚线方点。"
self.setAccessibleDescription(legend + ";".join(self._readout(item) for item in data.items))
@property
def _trend(self) -> bool:
return self.data.kind in {"blood_pressure", "exercise"}
@property
def _row_height(self) -> int:
return 88 if self.data.kind == "metrics" else 78
@property
def _columns(self) -> int:
return 2 if self.data.kind == "metrics" and self.width() >= 520 else 1
def resizeEvent(self, event: Any) -> None: # noqa: N802
super().resizeEvent(event)
if self.data.kind == "metrics":
rows = math.ceil(len(self.data.items) / self._columns)
height = rows * self._row_height
if self.height() != height:
self.setFixedHeight(height)
def sizeHint(self) -> QSize: # noqa: N802
return QSize(480, self.height())
def minimumSizeHint(self) -> QSize: # noqa: N802
return QSize(0, self.height())
@staticmethod
def _readout(item: VisualDatum) -> str:
text = " · ".join(part for part in (item.time_label, item.label, item.value_text) if part)
if item.interval:
text += "(原始记录区间)"
label = _status_label(item)
text += f" · 状态 {label}"
if item.status and label != item.status:
text += f"(原始:{item.status})"
if item.reference:
text += f" · 记录参考区间 {_number_text(item.reference[0])}–{_number_text(item.reference[1])} {item.unit}"
return text
def _geometry(self) -> tuple[QRectF, datetime, float, float, float]:
items = [item for item in self.data.items if item.value is not None and item.recorded_at]
origin = min(item.recorded_at for item in items)
span = (max(item.recorded_at for item in items) - origin).total_seconds()
low, high = min(item.value for item in items), max(item.value for item in items)
# Normalize first to keep finite, even for malformed but finite huge inputs.
scale = max(high, 1.0)
low, high = low / scale, high / scale
pad = max((high - low) * 0.18, 0.05)
upper = (high + pad) * scale
return (
QRectF(self.rect()).adjusted(43, 33, -12, -35),
origin,
span,
max(0, low - pad) * scale,
upper if math.isfinite(upper) else high * scale,
)
def _position(self, item: VisualDatum) -> QPointF:
plot, origin, span, low, high = self._geometry()
x = (
plot.left() + plot.width() * (item.recorded_at - origin).total_seconds() / span
if span
else plot.center().x()
)
scale = max(high, 1.0)
y = plot.bottom() - plot.height() * (
(item.value / scale - low / scale) / (high / scale - low / scale)
)
return QPointF(x, y)
def _point_tooltip(self, position: QPointF) -> str:
if self._trend:
return "\n\n".join(
self._readout(item)
for item in self.data.items
if item.value is not None
and (self._position(item) - position).manhattanLength() < 12
)
column_width = (self.width() + 24) / self._columns
column = min(self._columns - 1, max(0, int(position.x() // column_width)))
index = int(position.y() // self._row_height) * self._columns + column
return self._readout(self.data.items[index]) if 0 <= index < len(self.data.items) else ""
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
if tip := self._point_tooltip(event.position()):
QToolTip.showText(event.globalPosition().toPoint(), tip, self)
else:
QToolTip.hideText()
super().mouseMoveEvent(event)
def leaveEvent(self, event: Any) -> None: # noqa: N802
QToolTip.hideText()
super().leaveEvent(event)
def _text(
self, painter: QPainter, rect: QRectF, text: str, *, color: str = _NEUTRAL, size: int = 12
) -> None:
font = painter.font()
font.setPixelSize(size)
painter.setFont(font)
painter.setPen(QColor(color))
painter.drawText(
rect,
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
painter.fontMetrics().elidedText(
text, Qt.TextElideMode.ElideRight, max(0, int(rect.width()))
),
)
def _paint_trend(self, painter: QPainter) -> None:
plot, origin, span, low, high = self._geometry()
self._text(painter, QRectF(0, 0, 65, 22), self.data.items[0].unit, size=11)
series = tuple(dict.fromkeys(item.series for item in self.data.items))
for index, key in enumerate(series):
item = next(item for item in self.data.items if item.series == key)
style = Qt.PenStyle.DashLine if key == "diastolic_pressure" else Qt.PenStyle.SolidLine
left = 65 + index * 100
painter.setPen(QPen(QColor(_NEUTRAL), 2, style))
painter.setBrush(QColor(_NEUTRAL))
painter.drawLine(QPointF(left, 11), QPointF(left + 17, 11))
_draw_marker(painter, QPointF(left + 8, 11), key)
self._text(
painter,
QRectF(left + 23, 0, 76, 22),
item.label,
size=11,
)
for tick in range(4):
y = plot.bottom() - plot.height() * tick / 3
painter.setPen(QPen(QColor("#EDEDEE"), 1))
painter.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y))
self._text(
painter,
QRectF(0, y - 9, 40, 18),
f"{low * (1 - tick / 3) + high * tick / 3:.0f}",
size=11,
)
for key in series:
previous = None
style = Qt.PenStyle.DashLine if key == "diastolic_pressure" else Qt.PenStyle.SolidLine
for item in self.data.items:
if item.series != key:
continue
if item.value is None:
previous = None
continue
point = self._position(item)
if previous is not None:
painter.setPen(QPen(QColor(_NEUTRAL), 2, style))
painter.drawLine(previous, point)
previous = point
for item in self.data.items:
if item.series == key and item.value is not None:
painter.setPen(QPen(QColor(item.color), 2))
painter.setBrush(QColor(item.color))
_draw_marker(painter, self._position(item), key)
self._text(
painter,
QRectF(plot.left(), plot.bottom() + 8, 104, 20),
origin.date().isoformat(),
size=11,
)
if span:
last = max(item.recorded_at for item in self.data.items if item.value is not None)
self._text(
painter,
QRectF(plot.right() - 91, plot.bottom() + 8, 100, 20),
last.date().isoformat(),
size=11,
)
def _paint_snapshot(
self, painter: QPainter, item: VisualDatum, top: int, width: float
) -> None:
self._text(painter, QRectF(0, top, width, 21), item.label, color="#1A1C1F", size=12)
self._text(
painter, QRectF(0, top + 22, width, 24), item.value_text, color=item.color, size=17
)
note = f"记录状态:{_status_label(item)}" if item.status else "记录未提供状态"
if item.interval:
note = f"原始记录区间 · {note}"
if item.reference:
low, high = item.reference
values = [low, high, *(item.interval or (item.value,))]
scale = max(value for value in values if value is not None)
lower, upper = (
min(value / scale for value in values if value is not None),
max(value / scale for value in values if value is not None),
)
span = upper - lower
def x(value: float) -> float:
return 8 + (width - 16) * ((value / scale - lower) / span if span else 0.5)
painter.setPen(QPen(QColor("#E4E7EC"), 5))
painter.drawLine(QPointF(8, top + 54), QPointF(width - 8, top + 54))
painter.setPen(QPen(QColor(_NEUTRAL), 5))
painter.drawLine(QPointF(x(low), top + 54), QPointF(x(high), top + 54))
painter.setPen(QPen(QColor(item.color), 2))
painter.setBrush(QColor(item.color))
if item.interval:
painter.drawLine(
QPointF(x(item.interval[0]), top + 54), QPointF(x(item.interval[1]), top + 54)
)
else:
painter.drawEllipse(QPointF(x(item.value), top + 54), 4, 4)
note = f"{note} · 参考 {low:g}–{high:g} {item.unit}"
self._text(painter, QRectF(0, top + 65, width, 17), note, color=item.color, size=10)
else:
self._text(painter, QRectF(0, top + 53, width, 22), note, color=item.color, size=11)
def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802
super().paintEvent(event)
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
if self._trend:
self._paint_trend(painter)
else:
for index, item in enumerate(self.data.items):
top = index * self._row_height
if self.data.kind == "metrics":
width = (self.width() - 24 * (self._columns - 1)) / self._columns
painter.save()
painter.translate((index % self._columns) * (width + 24), 0)
self._paint_snapshot(painter, item, (index // self._columns) * self._row_height, width)
painter.restore()
elif self.data.kind == "risks":
self._text(
painter, QRectF(0, top, self.width(), 23), item.label, color="#1A1C1F"
)
width = (self.width() - 9) / 4
for offset, (level, label) in enumerate(_RISK_LABELS.items()):
rect = QRectF(offset * (width + 3), top + 29, width, 28)
active = level == item.status
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(item.color if active else "#F1F3F6"))
painter.drawRoundedRect(rect, 4, 4)
self._text(
painter,
rect.adjusted(6, 0, -3, 0),
label,
color="#FFFFFF" if active else _NEUTRAL,
size=11,
)
else:
painter.setPen(QPen(QColor("#E0E4EF"), 1))
painter.drawLine(QPointF(6, top + 10), QPointF(6, top + 78))
painter.setBrush(QColor(_NEUTRAL))
painter.drawEllipse(QPointF(6, top + 12), 4, 4)
for line, text in enumerate((item.time_label, item.label, item.raw_value)):
self._text(
painter,
QRectF(21, top + line * 22, self.width() - 21, 22),
text,
color="#1A1C1F" if line == 1 else _NEUTRAL,
)
painter.end()
class ReportVisualCard(QFrame):
def __init__(self, data: ReportVisual, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.data = data
self.setObjectName("AiConsultReportVisual")
self.setProperty("visualKind", data.kind)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
self.setMinimumWidth(0)
self.setStyleSheet("""
QFrame#AiConsultReportVisual {background:#FFFFFF; border:1px solid #EDEDEE; border-radius:10px;}
QFrame#AiConsultReportVisual QLabel {border:0; background:transparent; color:#697386; font-size:12px;}
QFrame#AiConsultReportVisual QLabel#AiConsultReportVisualTitle {color:#1A1C1F; font-size:15px; font-weight:600;}
QFrame#AiConsultReportVisual QPushButton {color:#4F63D9; background:#F7F8FC; border:1px solid #E4E7F4; border-radius:6px; padding:5px 9px; font-size:12px;}
QFrame#AiConsultReportVisual QTableWidget {background:#FFFFFF; color:#1A1C1F; border:1px solid #EDEDEE; font-size:12px;}
QFrame#AiConsultReportVisual QHeaderView::section {background:#F7F8FC; color:#697386; border:0; padding:5px;}
""")
root = QVBoxLayout(self)
root.setContentsMargins(14, 12, 14, 12)
root.setSpacing(8)
title = QLabel(data.title, self)
title.setObjectName("AiConsultReportVisualTitle")
title.setWordWrap(True)
root.addWidget(title)
self.chart = ReportPlot(data, self)
root.addWidget(self.chart)
self.toggle_button = QPushButton("查看原始记录", self)
self.toggle_button.setCheckable(True)
root.addWidget(self.toggle_button, alignment=Qt.AlignmentFlag.AlignLeft)
self.table = QTableWidget(len(data.items), 5, self)
self.table.setObjectName("AiConsultReportVisualTable")
self.table.setHorizontalHeaderLabels(
["记录日期 / 时间", "指标 / 方名", "记录值", "状态", "记录参考区间"]
)
self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.table.setWordWrap(True)
self.table.setMinimumWidth(0)
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
self.table.verticalHeader().hide()
self.table.setMaximumHeight(230)
for index, item in enumerate(data.items):
reference = (
f"{item.reference[0]:g}–{item.reference[1]:g} {item.unit}"
if item.reference
else "—"
)
values = (
item.time_label or "未提供日期",
item.label,
item.value_text + ("(原始记录区间)" if item.interval else ""),
_status_label(item) or "未提供",
reference,
)
for column, value in enumerate(values):
cell = QTableWidgetItem(value)
cell.setToolTip(ReportPlot._readout(item))
if value in {"—", "未提供", "未提供日期", "未记录", "未标注"}:
cell.setForeground(QColor(_NEUTRAL))
elif column in {2, 3}:
cell.setForeground(QColor(item.color))
self.table.setItem(index, column, cell)
self.table.hide()
root.addWidget(self.table)
self.toggle_button.toggled.connect(self._toggle_table)
source = QLabel(data.source, self)
source.setObjectName("AiConsultReportVisualSource")
source.setTextFormat(Qt.TextFormat.PlainText)
source.setWordWrap(True)
root.addWidget(source)
def _toggle_table(self, visible: bool) -> None:
self.table.setVisible(visible)
self.toggle_button.setText("收起原始记录" if visible else "查看原始记录")
def create_report_visual(
data: GlucoseChartData | ReportVisual,
parent: QWidget | None = None,
) -> QWidget:
return (
GlucoseReportCard(data, parent)
if isinstance(data, GlucoseChartData)
else ReportVisualCard(data, parent)
)
@@ -717,19 +717,21 @@ class OrderDetailDrawer(QDialog):
QTimer.singleShot(0, self.sync_to_owner)
def sync_to_owner(self) -> None:
owner = self._owner
if owner is not None:
# The scrim is an overlay of its owner, including when that owner is
# a standalone diagnosis window rather than the workstation itself.
origin = owner.mapToGlobal(QPoint(0, 0))
self.setGeometry(QRect(origin, owner.size()))
self.drawer_panel.setFixedWidth(max(1, round(owner.width() * self.drawer_ratio)))
return
target = main_window_target_rect(self)
if target is not None:
self.setGeometry(target)
self.drawer_panel.setFixedWidth(max(1, round(target.width() * self.drawer_ratio)))
return
owner = self._owner
if owner is None:
self.resize(1152, 720)
width = round(self.width() * self.drawer_ratio)
else:
origin = owner.mapToGlobal(QPoint(0, 0))
self.setGeometry(origin.x(), origin.y(), owner.width(), owner.height())
width = round(owner.width() * self.drawer_ratio)
self.resize(1152, 720)
width = round(self.width() * self.drawer_ratio)
self.drawer_panel.setFixedWidth(max(1, width))
def eventFilter(self, watched: object, event: QEvent) -> bool: # noqa: N802 - Qt API
@@ -1842,11 +1844,17 @@ class DiagnosisDialog(QDialog):
def _sync_host_geometry(self) -> None:
if self._embedded:
return
owner = self._owner
if not self._standalone_readonly and owner is not None and owner is not self:
# Ordinary windows use the centered 85% rectangle. A drawer's
# translucent scrim must cover the complete live owner client area.
origin = owner.mapToGlobal(QPoint(0, 0))
self.setGeometry(QRect(origin, owner.size()))
return
target = main_window_target_rect(self)
if target is not None:
self.setGeometry(target)
return
owner = self._owner
if owner is None:
if self.width() < 760 or self.height() < 520:
self.resize(1024, 640)
@@ -1935,6 +1943,7 @@ class DiagnosisDialog(QDialog):
QEvent.Type.Resize,
QEvent.Type.Move,
QEvent.Type.Show,
QEvent.Type.WindowStateChange,
}:
self._sync_host_geometry()
self._update_drawer_geometry()
+5
View File
@@ -228,6 +228,11 @@ def _message(p: QPainter, w: float) -> None:
# --- Shell chrome ---------------------------------------------------------
@_glyph("more", "ellipsis")
def _more(p: QPainter, w: float) -> None:
for x in (5.0, 12.0, 19.0):
_dot(p, x, 12.0, 1.5)
@_glyph("fold", "panel_close")
def _fold(p: QPainter, w: float) -> None:
@@ -348,16 +348,16 @@ class PrescriptionLibraryPage(QWidget):
table_layout.setSpacing(0)
self.table = LibraryTable(
[
TableColumn("id", "ID", 62),
TableColumn("prescription_name", "处方名称", 162),
TableColumn("formula_type", "处方类型", 88, _formula_text),
TableColumn("herbs", "药材数量", 84, _herb_count),
TableColumn("herbs", "药材组成(部分)", 296, _herbs_detail),
TableColumn("efficacy", "功效主治", 170, _efficacy_text),
TableColumn("is_public", "公开范围", 135, _visibility_text),
TableColumn("creator_name", "创建人", 100),
TableColumn("create_time", "创建时间", 178, _create_time_cell),
TableColumn("__actions__", "操作", 160, lambda _value, _row: ""),
TableColumn("id", "ID", 72),
TableColumn("prescription_name", "处方名称", 170),
TableColumn("formula_type", "处方类型", 76, _formula_text),
TableColumn("herbs", "药材数量", 76, _herb_count),
TableColumn("herbs", "药材组成(部分)", 260, _herbs_detail),
TableColumn("efficacy", "功效主治", 90, _efficacy_text),
TableColumn("is_public", "公开范围", 134, _visibility_text),
TableColumn("creator_name", "创建人", 136),
TableColumn("create_time", "创建时间", 122, _create_time_cell),
TableColumn("__actions__", "操作", 150, lambda _value, _row: ""),
]
)
self.table.setObjectName("PrescriptionLibraryTable")
@@ -371,8 +371,6 @@ class PrescriptionLibraryPage(QWidget):
self.table.horizontalHeader().setMinimumSectionSize(36)
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
self.table.horizontalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
for column, width in enumerate((54, 170, 76, 76, 260, 90, 134, 136, 122, 150)):
self.table.setColumnWidth(column, width)
for column in (0, 2, 3, 5, 9):
self.table.horizontalHeaderItem(column).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
self.table.setWordWrap(False)
@@ -1694,8 +1694,8 @@ class PrescriptionsPage(QWidget):
def _set_ai_columns(self, enabled: bool) -> None:
changed = enabled != self._ai_enabled
self._ai_enabled = enabled
self.table.setColumnHidden(11, not enabled)
self.table.setColumnHidden(12, not (enabled and self._agreement_visible))
for column in (11, 12):
self.table.setColumnHidden(column, not (enabled and self._agreement_visible))
if enabled:
header = self.table.horizontalHeader()
header.moveSection(header.visualIndex(11), header.visualIndex(4) + 1)
@@ -1708,7 +1708,8 @@ class PrescriptionsPage(QWidget):
def _set_agreement_visible(self, visible: bool) -> None:
self._agreement_visible = visible
self.table.setColumnHidden(12, not (self._ai_enabled and visible))
for column in (11, 12):
self.table.setColumnHidden(column, not (self._ai_enabled and visible))
self.ai_statistics_button.setVisible(
visible and has_permission(self.permissions, "tcm.prescriptionAi/statistics", default=False)
and callable(getattr(self.repository, "prescription_ai_statistics", None)))
+219 -78
View File
@@ -89,6 +89,7 @@ from ..dialogs.prescription_ai import (
)
from ..filter_disclosure import FilterDisclosure
from ..reception_style import body_family, heading_family, number_family
from ..reception_workspace import RECEPTION_WORKSPACE_QSS, ReceptionWorkbench
from ..report_provenance import report_provenance_lines
from ..theme import mark_business_dialog
from ..widgets import (
@@ -1182,6 +1183,7 @@ QWidget#ReceptionPage QPushButton#ReceptionCompleteButton {
border-radius: 5px;
}
QWidget#ReceptionPage QPushButton#ReceptionCompleteButton:enabled { background-color: #FFFFFF; }
QWidget#ReceptionPage QPushButton#ReceptionMoreButton { padding: 0 6px; }
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs {
border-top-left-radius: 0;
border-top-right-radius: 0;
@@ -1924,6 +1926,30 @@ def _queue_glucose_value(record: Any) -> object:
)
def _is_numeric_reading(value: object) -> bool:
"""Separate a scalar measurement from a patient's free-text description."""
return bool(re.fullmatch(
r"(?:空腹(?:血糖)?[::]?\s*)?[-+]?\d+(?:\.\d+)?\s*(?:mmol/l|mg/l|mg/g|%)?",
str("" if value is None else value).strip(), re.IGNORECASE,
))
def _reading_text(value: object, unit: str) -> str:
text = display_text(value)
if _is_numeric_reading(value) and unit.lower() not in text.lower():
return f"{text} {unit}"
return text
def _history_fact(text: str, *captions: str) -> str | None:
"""Lift an explicitly labelled fact into the overview; retain its source text."""
for line in text.splitlines():
caption, separator, value = re.sub(r"[::]", ":", line).partition(":")
if separator and caption.strip() in captions and value.strip():
return value.strip()
return None
def _glucose_tone(value: object) -> str:
number = _as_float(value)
if number is None:
@@ -2474,6 +2500,13 @@ class _ReceptionHero(QFrame):
if layout.direction() != direction:
layout.setDirection(direction)
self.updateGeometry()
action_group = getattr(self, "action_group", None)
if action_group is not None:
action_group.setDirection(
QBoxLayout.Direction.LeftToRight
if direction == QBoxLayout.Direction.TopToBottom and self.width() >= 620
else QBoxLayout.Direction.TopToBottom
)
actions = getattr(self, "actions_layout", None)
if actions is not None:
compact = self.width() < 520
@@ -2488,21 +2521,7 @@ class _ReceptionHero(QFrame):
class _ClinicalInfoPanel(QWidget):
"""Stack history and measurements before their text gets squeezed."""
def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt override
super().resizeEvent(event)
layout = self.layout()
if not isinstance(layout, QBoxLayout):
return
stacked = self.width() < 760
direction = (
QBoxLayout.Direction.TopToBottom if stacked else QBoxLayout.Direction.LeftToRight
)
if layout.direction() != direction:
layout.setDirection(direction)
layout.setStretch(0, 0 if stacked else 42)
layout.setStretch(1, 0 if stacked else 58)
"""Let the clinical history use the full reading column."""
class _ClinicalPageStack(QStackedWidget):
@@ -3760,13 +3779,13 @@ class QueueRow(QWidget):
super().__init__(parent)
self.setObjectName("ReceptionQueueRow")
self._selected = False
self.setFixedHeight(104)
self.setFixedHeight(82)
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, False)
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 17, 16, 17)
layout.setSpacing(10)
layout.setContentsMargins(14, 12, 12, 12)
layout.setSpacing(8)
top = QHBoxLayout()
top.setSpacing(14)
top.setSpacing(8)
name = QLabel(
display_text(first_value(record, "patient_name", "name", default="未命名患者"))
)
@@ -3814,23 +3833,27 @@ class QueueRow(QWidget):
layout.addLayout(top)
bottom = QHBoxLayout()
bottom.setSpacing(8)
subline = QLabel(_queue_condition_summary(record))
summary = _queue_condition_summary(record)
subline = QLabel("" if summary == "暂无病情摘要" else summary)
subline.setToolTip(summary if summary != "暂无病情摘要" else "")
subline.setObjectName("ReceptionQueueSubline")
subline.setMinimumWidth(0)
subline.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
bottom.addWidget(subline, 1)
metric = _queue_glucose_value(record)
drop = _GlucoseDropIcon(_glucose_tone(metric), self)
drop.setVisible(metric not in (None, ""))
drop.setVisible(metric not in (None, "") and _is_numeric_reading(metric))
self.glucose_drop = drop
bottom.addWidget(drop, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
metric_label = QLabel(
f"{display_text(metric)} mmol/L" if metric not in (None, "") else "",
(_reading_text(metric, "mmol/L") if _is_numeric_reading(metric) else "血糖有描述")
if metric not in (None, "") else "",
self,
)
metric_label.setObjectName("ReceptionQueueMetric")
tone = _glucose_tone(metric)
tone = _glucose_tone(metric) if _is_numeric_reading(metric) else "description"
metric_label.setProperty("tone", tone)
metric_label.setToolTip(display_text(metric))
metric_label.setVisible(metric not in (None, ""))
bottom.addWidget(metric_label, 0, Qt.AlignmentFlag.AlignRight)
layout.addLayout(bottom)
@@ -4080,7 +4103,7 @@ class ReceptionPage(QWidget):
super().__init__(parent)
self.setObjectName("ReceptionPage")
self.setStyleSheet(
RECEPTION_QSS.replace("$body_family", body_family())
(RECEPTION_QSS + RECEPTION_WORKSPACE_QSS).replace("$body_family", body_family())
.replace("$heading_family", heading_family())
.replace("$number_family", number_family())
)
@@ -4180,7 +4203,7 @@ class ReceptionPage(QWidget):
)
root = QVBoxLayout(self)
root.setContentsMargins(11, 16, 11, 20)
root.setContentsMargins(12, 16, 12, 12)
root.setSpacing(0)
splitter = QSplitter(Qt.Orientation.Horizontal)
@@ -4191,8 +4214,8 @@ class ReceptionPage(QWidget):
splitter.addWidget(detail_panel)
splitter.setStretchFactor(0, 0)
splitter.setStretchFactor(1, 1)
splitter.setHandleWidth(10)
splitter.setSizes([399, 1072])
splitter.setHandleWidth(12)
splitter.setSizes([286, 1185])
root.addWidget(splitter, 1)
self.poll_timer = QTimer(self)
@@ -4209,7 +4232,7 @@ class ReceptionPage(QWidget):
super().resizeEvent(event)
panel = getattr(self, "queue_panel", None)
if panel is not None:
width = 340 if self.width() < 1000 else 399
width = 272 if self.width() < 1100 else 286
if panel.minimumWidth() != width:
panel.setFixedWidth(width)
@@ -4225,9 +4248,9 @@ class ReceptionPage(QWidget):
panel = QFrame()
panel.setObjectName("ReceptionQueuePanel")
self.queue_panel = panel
panel.setFixedWidth(399)
panel.setFixedWidth(286)
layout = QVBoxLayout(panel)
layout.setContentsMargins(14, 14, 12, 14)
layout.setContentsMargins(10, 14, 10, 10)
layout.setSpacing(10)
header = QWidget(panel)
@@ -4279,7 +4302,7 @@ class ReceptionPage(QWidget):
search_row.addWidget(self.search_edit, 1)
filter_layout.addLayout(search_row)
filter_row = QHBoxLayout()
filter_row = QGridLayout()
filter_row.setSpacing(6)
for status, label in ((None, "全部"), (1, "待接诊"), (2, "问诊中"), (3, "已完成")):
button = QPushButton(label, self.queue_filter_panel)
@@ -4290,7 +4313,8 @@ class ReceptionPage(QWidget):
lambda _checked=False, value=status: self._set_queue_filter(value)
)
self._queue_filter_buttons[status] = button
filter_row.addWidget(button, 1)
position = len(self._queue_filter_buttons) - 1
filter_row.addWidget(button, position // 2, position % 2)
self._queue_filter_buttons[1].setChecked(True)
filter_layout.addLayout(filter_row)
layout.addWidget(self.queue_filter_panel)
@@ -4334,7 +4358,7 @@ class ReceptionPage(QWidget):
def _build_detail_panel(self) -> QWidget:
panel = QFrame()
panel.setObjectName("ReceptionDetailPanel")
panel.setMinimumWidth(430)
panel.setMinimumWidth(390)
panel_layout = QVBoxLayout(panel)
panel_layout.setContentsMargins(0, 0, 0, 0)
panel_layout.setSpacing(0)
@@ -4350,7 +4374,7 @@ class ReceptionPage(QWidget):
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
content = QWidget(scroll)
content.setMinimumWidth(390)
content.setMinimumWidth(0)
content.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
detail_layout = QVBoxLayout(content)
detail_layout.setContentsMargins(0, 0, 0, 0)
@@ -4358,9 +4382,9 @@ class ReceptionPage(QWidget):
hero = _ReceptionHero(content)
hero.setObjectName("ReceptionHero")
hero.setMinimumHeight(112)
hero.setMinimumHeight(96)
hero_layout = QVBoxLayout(hero)
hero_layout.setContentsMargins(16, 22, 16, 22)
hero_layout.setContentsMargins(18, 16, 18, 16)
hero_layout.setSpacing(4)
self.detail_banner = MessageBanner(parent=hero)
hero_layout.addWidget(self.detail_banner)
@@ -4373,7 +4397,7 @@ class ReceptionPage(QWidget):
self.patient_avatar_label = QLabel("患", hero)
self.patient_avatar_label.setObjectName("ReceptionAvatar")
self.patient_avatar_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.patient_avatar_label.setFixedSize(64, 64)
self.patient_avatar_label.setFixedSize(48, 48)
identity_head.addWidget(self.patient_avatar_label)
identity = QVBoxLayout()
identity.setSpacing(8)
@@ -4400,6 +4424,7 @@ class ReceptionPage(QWidget):
actions.setSpacing(14)
actions.addStretch(1)
action_group = QVBoxLayout()
hero.action_group = action_group
action_group.setContentsMargins(0, 0, 0, 0)
action_group.setSpacing(6)
self.current_assistant_label = QLabel("当前医助:—", hero)
@@ -4428,7 +4453,9 @@ class ReceptionPage(QWidget):
self.video_button.setProperty("variant", "primary")
self.video_button.clicked.connect(self._request_video)
actions.addWidget(self.video_button)
self.more_button = QPushButton("···", hero)
self.more_button = QPushButton(hero)
self.more_button.setIcon(icons.icon("more", "#5D6B80", 16))
self.more_button.setIconSize(QSize(16, 16))
self.more_button.setToolTip("更多操作")
self.more_button.setAccessibleName("更多操作")
self.more_button.setObjectName("ReceptionMoreButton")
@@ -4472,7 +4499,7 @@ class ReceptionPage(QWidget):
clinical_card = QFrame(content)
clinical_card.setObjectName("ReceptionClinicalCard")
clinical_card.setMinimumHeight(526)
clinical_card.setMinimumHeight(0)
clinical_card.setSizePolicy(
QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Minimum,
@@ -4510,15 +4537,18 @@ class ReceptionPage(QWidget):
QSizePolicy.Policy.Minimum,
)
consultation_layout = QHBoxLayout(consultation_page)
consultation_layout.setContentsMargins(12, 22, 12, 13)
consultation_layout.setContentsMargins(18, 18, 18, 18)
consultation_layout.setSpacing(10)
self.clinical_info_group = consultation_page
history_card = QFrame(consultation_page)
history_card.setObjectName("ReceptionHistoryCard")
history_layout = QVBoxLayout(history_card)
history_layout.setContentsMargins(8, 4, 18, 0)
history_layout.setSpacing(15)
history_layout.setContentsMargins(0, 0, 0, 0)
history_layout.setSpacing(14)
history_title = QLabel("病情与用药", history_card)
history_title.setObjectName("ReceptionCaseHeading")
history_layout.addWidget(history_title)
self.case_labels: dict[str, QLabel] = {}
def add_case_field(
@@ -4528,7 +4558,8 @@ class ReceptionPage(QWidget):
*,
stacked: bool = False,
) -> None:
field = QWidget(history_card)
field = QFrame(history_card)
field.setObjectName("ReceptionCaseField")
if stacked:
field_layout = QVBoxLayout(field)
field_layout.setContentsMargins(0, 0, 0, 0)
@@ -4555,8 +4586,10 @@ class ReceptionPage(QWidget):
self.case_labels[key] = value_label
target.addWidget(field)
add_case_field(history_layout, "chief", "主诉", stacked=True)
add_case_field(history_layout, "present", "现病史", stacked=True)
add_case_field(history_layout, "chief", "本次主诉", stacked=True)
add_case_field(history_layout, "medication", "当前用药", stacked=True)
add_case_field(history_layout, "course", "患病时长")
add_case_field(history_layout, "present", "现病史原文", stacked=True)
add_case_field(history_layout, "past", "既往史")
add_case_field(history_layout, "family", "家族史")
add_case_field(history_layout, "allergy", "过敏史")
@@ -4594,20 +4627,35 @@ class ReceptionPage(QWidget):
add_case_field(history_layout, "diet", "饮食习惯")
history_layout.addStretch(1)
consultation_layout.addWidget(history_card, 42)
consultation_layout.addWidget(history_card, 1)
right_clinical = QWidget(consultation_page)
right_layout = QVBoxLayout(right_clinical)
right_layout.setContentsMargins(0, 0, 0, 0)
right_layout.setSpacing(10)
self.patient_summary_card, self.patient_summary_labels = self._field_card(
"患者基本信息",
(("性别 / 年龄", "gender_age"), ("联系方式", "phone"),
("患病时长", "course"), ("已记录诊断", "diagnosis")),
)
self.patient_summary_card.setObjectName("ReceptionPatientSummaryCard")
self.patient_summary_card.setAccessibleName("患者基本信息")
for label in self.patient_summary_labels.values():
label.setObjectName("ReceptionPatientSummaryValue")
label.setStyleSheet("")
label.setTextFormat(Qt.TextFormat.PlainText)
label.setMinimumWidth(0)
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
right_layout.addWidget(self.patient_summary_card)
vitals_card = QFrame(right_clinical)
vitals_card.setObjectName("ReceptionVitalsCard")
vitals_card.setMinimumHeight(152)
vitals_card.setMinimumHeight(0)
vitals_card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
vitals_layout = QVBoxLayout(vitals_card)
vitals_layout.setContentsMargins(12, 4, 2, 18)
vitals_layout.setSpacing(12)
vitals_layout.setContentsMargins(14, 14, 14, 14)
vitals_layout.setSpacing(8)
vitals_title = QLabel("生命体征", vitals_card)
vitals_title.setProperty("receptionBlockTitle", True)
vitals_layout.addWidget(vitals_title)
@@ -4661,7 +4709,9 @@ class ReceptionPage(QWidget):
cell_layout.addStretch(1)
self.vital_labels[key] = value_label
self.vital_unit_labels[key] = unit_label
vitals_grid.addWidget(cell, 0, column)
row, position, span = ((0, 0, 1), (0, 1, 1), (0, 2, 1), (1, 0, 2), (1, 2, 1))[column]
vitals_grid.addWidget(cell, row, position, 1, span)
for column in range(3):
vitals_grid.setColumnStretch(column, 1)
vitals_layout.addLayout(vitals_grid)
right_layout.addWidget(vitals_card)
@@ -4669,12 +4719,15 @@ class ReceptionPage(QWidget):
labs_card = QFrame(right_clinical)
labs_card.setObjectName("ReceptionLabsCard")
labs_layout = QVBoxLayout(labs_card)
labs_layout.setContentsMargins(12, 3, 2, 0)
labs_layout.setContentsMargins(14, 14, 14, 14)
labs_layout.setSpacing(9)
labs_title = QLabel("检查结果", labs_card)
labs_title.setProperty("receptionBlockTitle", True)
labs_layout.addWidget(labs_title)
labs_grid = QGridLayout()
self.lab_grid = labs_grid
self.lab_cells: dict[str, QFrame] = {}
self._show_missing_labs = False
labs_grid.setContentsMargins(0, 0, 0, 0)
labs_grid.setHorizontalSpacing(7)
labs_grid.setVerticalSpacing(7)
@@ -4694,7 +4747,7 @@ class ReceptionPage(QWidget):
cell = QFrame(labs_card)
cell.setObjectName("ReceptionLabCell")
cell_layout = QVBoxLayout(cell)
cell_layout.setContentsMargins(10, 10, 8, 6)
cell_layout.setContentsMargins(0, 6, 0, 8)
cell_layout.setSpacing(6)
caption_label = QLabel(caption, cell)
caption_label.setProperty("receptionMetricCaption", True)
@@ -4711,13 +4764,20 @@ class ReceptionPage(QWidget):
cell_layout.addStretch(1)
self.lab_labels[key] = value_label
self.lab_state_labels[key] = state_label
row, column = divmod(index, 4)
self.lab_cells[key] = cell
row, column = divmod(index, 2)
labs_grid.addWidget(cell, row, column)
labs_grid.setRowStretch(row, 1)
labs_grid.setColumnStretch(column, 1)
labs_layout.addLayout(labs_grid, 1)
right_layout.addWidget(labs_card, 1)
consultation_layout.addWidget(right_clinical, 58)
labs_layout.addLayout(labs_grid)
self.labs_empty_label = QLabel("暂未录入检查结果", labs_card)
self.labs_empty_label.setProperty("role", "muted")
labs_layout.addWidget(self.labs_empty_label)
self.lab_missing_button = QPushButton("", labs_card)
self.lab_missing_button.setObjectName("ReceptionMissingLabsButton")
self.lab_missing_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.lab_missing_button.clicked.connect(self._toggle_missing_labs)
labs_layout.addWidget(self.lab_missing_button)
right_layout.addWidget(labs_card)
self.clinical_pages.addWidget(consultation_page)
appointment_card, self.appointment_labels = self._field_card(
@@ -5021,7 +5081,6 @@ class ReceptionPage(QWidget):
health_layout.addWidget(self.health_summary_label)
self.health_scroll = add_scrolling_page(health_card)
detail_layout.addWidget(clinical_card)
detail_layout.addSpacing(10)
ai_panels = _ReceptionAiPanels(content)
ai_panels.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
@@ -5301,7 +5360,7 @@ class ReceptionPage(QWidget):
assistant_header.addStretch(1)
assistant_layout.addLayout(assistant_header)
assistant_hint = QLabel(
"您好,我是 AI 问诊助手,有什么可以帮助您了解患者情况的吗?",
"结合当前患者资料,快速核对问诊要点。",
assistant_card,
)
assistant_hint.setObjectName("ReceptionAiAssistantHint")
@@ -5315,8 +5374,10 @@ class ReceptionPage(QWidget):
self.ai_prompt_buttons: list[QPushButton] = []
def prompt_button(label: str) -> QPushButton:
def prompt_button(label: str, question: str) -> QPushButton:
button = QPushButton(label, assistant_card)
button.setToolTip(question)
button.setAccessibleName(question)
button.setProperty("receptionAiPrompt", True)
button.setMinimumWidth(0)
button.setSizePolicy(
@@ -5324,20 +5385,20 @@ class ReceptionPage(QWidget):
QSizePolicy.Policy.Fixed,
)
button.clicked.connect(
lambda _checked=False, prompt=label: self._open_ai_report_for_prompt(prompt)
lambda _checked=False, prompt=question: self._open_ai_report_for_prompt(prompt)
)
self.ai_prompt_buttons.append(button)
return button
prompt_host = _AiFlowHost(assistant_card, horizontal_spacing=8, vertical_spacing=8)
prompt_host = _AiFlowHost(assistant_card, horizontal_spacing=6, vertical_spacing=6)
prompt_host.setObjectName("ReceptionAiPrompts")
for label in (
"基于当前病史,下一步检查建议?",
"该患者的用药调整建议?",
"糖尿病教育要点有哪些?",
"并发症筛查建议?",
for label, question in (
("检查建议", "基于当前病史,下一步检查建议?"),
("用药核对", "该患者的用药调整建议?"),
("健康教育", "糖尿病教育要点有哪些?"),
("并发症筛查", "并发症筛查建议?"),
):
prompt_host.flow.addWidget(prompt_button(label))
prompt_host.flow.addWidget(prompt_button(label, question))
assistant_layout.addWidget(prompt_host)
assistant_layout.addStretch(1)
@@ -5355,17 +5416,65 @@ class ReceptionPage(QWidget):
assistant_input_row.addWidget(self.ai_send_button)
assistant_input_host.hide()
ai_row.addWidget(assistant_card, 23)
detail_layout.addWidget(ai_panels)
insights = QWidget()
insights_layout = QVBoxLayout(insights)
insights_layout.setContentsMargins(0, 0, 0, 0)
insights_layout.setSpacing(12)
insights_layout.addWidget(right_clinical)
insights_layout.addWidget(ai_panels)
insights_layout.addStretch(1)
self.detail_tabs.currentChanged.connect(self._detail_tab_changed)
self._detail_tab_changed(0)
scroll.setWidget(content)
self.detail_stack.addWidget(scroll)
detail_layout.removeWidget(hero)
detail_page = QWidget()
workspace_layout = QVBoxLayout(detail_page)
workspace_layout.setContentsMargins(0, 0, 0, 0)
workspace_layout.setSpacing(12)
workspace_layout.addWidget(hero)
self.workbench = ReceptionWorkbench(scroll, insights, detail_page)
self.insights_scroll = self.workbench.insights_scroll
workspace_layout.addWidget(self.workbench, 1)
self.detail_stack.addWidget(detail_page)
panel_layout.addWidget(self.detail_stack)
self._reset_detail_content()
return panel
def _toggle_missing_labs(self) -> None:
self._show_missing_labs = not self._show_missing_labs
self._sync_lab_rows()
def _sync_lab_rows(self) -> None:
recorded = 0
row = column = 0
for key, cell in self.lab_cells.items():
self.lab_grid.removeWidget(cell)
text = self.lab_labels[key].text().strip()
has_value = text not in {"", "—", "正在加载…"}
recorded += int(has_value)
visible = has_value or self._show_missing_labs
cell.setVisible(visible)
if not visible:
continue
wide = bool(cell.property("description")) and has_value
if wide and column:
row += 1
column = 0
self.lab_grid.addWidget(cell, row, column, 1, 2 if wide else 1)
if wide or column:
row += 1
column = 0
else:
column = 1
missing = len(self.lab_cells) - recorded
self.labs_empty_label.setVisible(recorded == 0 and not self._show_missing_labs)
self.lab_missing_button.setVisible(missing > 0)
self.lab_missing_button.setText(
"收起未记录项" if self._show_missing_labs else f"显示 {missing} 项未记录"
)
def _detail_tab_changed(self, index: int) -> None:
if not 0 <= index < self.detail_tabs.count():
return
@@ -7043,7 +7152,7 @@ class ReceptionPage(QWidget):
def _add_queue_row(self, record: Any) -> None:
item = QListWidgetItem()
item.setData(Qt.ItemDataRole.UserRole, record)
item.setSizeHint(QSize(0, 120))
item.setSizeHint(QSize(0, 88))
self.queue_list.addItem(item)
self.queue_list.setItemWidget(item, QueueRow(record))
@@ -7348,6 +7457,7 @@ class ReceptionPage(QWidget):
self._pending_tongue_images.clear()
self._pending_report_files.clear()
self._render_pending_attachments()
self.insights_scroll.verticalScrollBar().setValue(0)
self._selected_record = record
self._selected_appointment_id = appointment_id
self._selected_detail = None
@@ -8009,6 +8119,12 @@ class ReceptionPage(QWidget):
)
self.patient_labels["customer"].setText(display_text(customer))
self.patient_labels["prescription"].setText("已开具" if has_prescription else "暂未开具")
demographics = " · ".join(
part for part in (gender if gender != "—" else "",
f"{age}岁" if age not in (None, "") else "") if part
)
self._set_patient_summary_value("gender_age", demographics)
self._set_patient_summary_value("phone", self.patient_labels["phone"].text())
systolic = first_value(
diagnosis,
@@ -8099,6 +8215,15 @@ class ReceptionPage(QWidget):
"0",
}
def _set_patient_summary_value(self, key: str, value: Any) -> None:
label = self.patient_summary_labels[key]
text = self._case_display_text(value)
text = "未记录" if text == "—" else text
label.setText(text)
label.setProperty("missing", text in {"未记录", "正在加载…"})
label.style().unpolish(label)
label.style().polish(label)
def _set_case_metric(self, key: str, value: Any, *, alert: bool = False) -> None:
label = self.case_metric_labels[key]
caption = {
@@ -8326,8 +8451,7 @@ class ReceptionPage(QWidget):
blood_sugar_text = self._case_display_text(blood_sugar)
if blood_sugar_text.startswith("空腹"):
blood_sugar_text = blood_sugar_text[2:].lstrip(":: ")
if "mmol/l" not in blood_sugar_text.lower():
blood_sugar_text = f"{blood_sugar_text} mmol/L"
blood_sugar_text = _reading_text(blood_sugar_text, "mmol/L")
case_items["空腹血糖"] = blood_sugar_text
lines.append(f"空腹血糖:{blood_sugar_text}")
@@ -8386,6 +8510,10 @@ class ReceptionPage(QWidget):
)
case_values = {
"chief": chief,
"medication": case_value("current_medications", "current_medicine", "current_medication")
or _history_fact(str(present or ""), "在用药物", "当前用药", "用药情况"),
"course": case_value("disease_course_text", "disease_course", "course_text", "diabetes_discovery_year_text")
or _history_fact(str(present or ""), "患病时长", "病程", "患病时间"),
"present": present,
"past": past,
"family": family,
@@ -8395,6 +8523,10 @@ class ReceptionPage(QWidget):
}
for key, value in case_values.items():
self.case_labels[key].setText(display_text(value))
self._set_patient_summary_value("course", case_values["course"])
self._set_patient_summary_value(
"diagnosis", case_value("clinical_diagnosis", "diagnosis_name", "disease_name")
)
lab_definitions: dict[str, tuple[tuple[str, ...], str, tuple[str, ...]]] = {
"fasting": (
@@ -8433,17 +8565,17 @@ class ReceptionPage(QWidget):
health_lines: list[str] = []
for key, (value_keys, unit, status_keys) in lab_definitions.items():
value = case_value(*value_keys)
text = display_text(value)
if value not in (None, "") and unit.lower() not in str(value).lower():
text = f"{text} {unit}"
numeric = _is_numeric_reading(value)
text = _reading_text(value, unit)
self.lab_labels[key].setText(text)
self.lab_cells[key].setProperty("description", value not in (None, "") and not numeric)
status_value = case_value(*status_keys)
computed = _lab_status_for_value(key, value)
computed = _lab_status_for_value(key, value) if numeric else None
status_label = self.lab_state_labels[key]
status_label.setProperty(
"warning", key in {"fasting", "postprandial"} and _glucose_tone(value) == "warn"
)
if status_value not in (None, ""):
if status_value not in (None, "") and numeric:
status_text = display_text(status_value)
if status_text.strip().lower() in {"正常", "normal", "0", "阴性"}:
status_text = "正常"
@@ -8478,6 +8610,7 @@ class ReceptionPage(QWidget):
status_label.setVisible(False)
if value not in (None, ""):
health_lines.append(f"{self.lab_labels[key].parentWidget().findChild(QLabel).text()}:{text}")
self._sync_lab_rows()
clinical_diagnosis = case_value("clinical_diagnosis", "diagnosis")
health_header = (
@@ -8847,6 +8980,8 @@ class ReceptionPage(QWidget):
label.setText("—")
for label in getattr(self, "patient_labels", {}).values():
label.setText("—")
for key in self.patient_summary_labels:
self._set_patient_summary_value(key, "正在加载…" if seed else None)
if hasattr(self, "diagnosis_text"):
self._set_case_placeholder(
"正在加载病例…" if seed else "尚未填写病例信息"
@@ -8897,6 +9032,8 @@ class ReceptionPage(QWidget):
for key, label in self.lab_labels.items():
label.setText("—")
self.lab_state_labels[key].setVisible(False)
self._show_missing_labs = False
self._sync_lab_rows()
self._render_notes([])
self._update_action_state(seed or {}, {})
@@ -8909,6 +9046,8 @@ class ReceptionPage(QWidget):
self.patient_meta_label.setToolTip("")
self.current_assistant_label.setText("当前医助:—")
self.current_assistant_label.setToolTip("")
for key in self.patient_summary_labels:
self._set_patient_summary_value(key, None)
self._set_case_placeholder(message)
self.prescription_hint.setText("处方:患者详情加载失败")
self.prescription_hint.setProperty("casePrescriptionState", "unknown")
@@ -8937,6 +9076,8 @@ class ReceptionPage(QWidget):
for key, label in self.lab_labels.items():
label.setText("—")
self.lab_state_labels[key].setVisible(False)
self._show_missing_labs = False
self._sync_lab_rows()
def _update_action_state(self, appointment: Any, diagnosis: Any) -> None:
appointment_id = _record_id(appointment) or self._selected_appointment_id
@@ -2,11 +2,11 @@
from __future__ import annotations
from collections.abc import Iterable
from collections.abc import Iterable, Sequence
from string import Template
from typing import Any
from PySide6.QtCore import QModelIndex, QRectF, QSize, Qt
from PySide6.QtCore import QEvent, QModelIndex, QRectF, QSize, Qt, QTimer
from PySide6.QtGui import QColor, QFont, QFontMetrics, QIcon, QPainter
from PySide6.QtWidgets import (
QComboBox,
@@ -18,7 +18,7 @@ from PySide6.QtWidgets import (
)
from .reception_style import body_family, heading_family
from .widgets import SortableTable, first_value
from .widgets import SortableTable, TableColumn, first_value
def library_stylesheet() -> str:
@@ -58,7 +58,58 @@ class LibraryComboBox(QComboBox):
class LibraryTable(SortableTable):
"""Repaint existing action widgets and restore selection by template ID."""
"""Fit readable columns while preserving actions and selected template IDs."""
_FLEX_COLUMNS = ((1, 2), (4, 5), (5, 2))
def __init__(self, columns: Sequence[TableColumn], parent: QWidget | None = None) -> None:
super().__init__(columns, parent)
self.horizontalHeader().setStretchLastSection(False)
self._minimum_widths = tuple(column.width for column in self.columns)
self._manual_widths: dict[int, int] = {}
self._fitting_columns = False
self._fit_timer = QTimer(self)
self._fit_timer.setSingleShot(True)
self._fit_timer.timeout.connect(self._fit_columns)
self.horizontalHeader().sectionResized.connect(self._column_resized)
self.viewport().installEventFilter(self)
def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802
if watched is self.viewport() and event.type() in {QEvent.Type.Resize, QEvent.Type.Show}:
self._schedule_column_fit()
return super().eventFilter(watched, event)
def _schedule_column_fit(self) -> None:
if not self._fit_timer.isActive():
self._fit_timer.start(0)
def _column_resized(self, column: int, _old_size: int, size: int) -> None:
if self._fitting_columns:
return
self._manual_widths[column] = max(self._minimum_widths[column], size)
self._schedule_column_fit()
def _fit_columns(self) -> None:
widths = [self._manual_widths.get(column, minimum)
for column, minimum in enumerate(self._minimum_widths)]
extra = max(0, self.viewport().width() - sum(widths))
flexible = [(column, weight) for column, weight in self._FLEX_COLUMNS
if column not in self._manual_widths]
# If every text column was manually sized, keep those preferences as
# minimums and let the herb preview absorb any remaining wide-screen space.
flexible = flexible or [(4, 1)]
total_weight = sum(weight for _column, weight in flexible)
for column, weight in flexible:
widths[column] += extra * weight // total_weight
widths[flexible[0][0]] += max(0, self.viewport().width() - sum(widths))
if widths == [self.columnWidth(column) for column in range(self.columnCount())]:
return
self._fitting_columns = True
try:
for column, width in enumerate(widths):
self.setColumnWidth(column, width)
finally:
self._fitting_columns = False
def set_rows(self, rows: Iterable[Any]) -> None:
selected_id = first_value(self.current_data(), "id", "template_id", default=None)
@@ -1,15 +1,10 @@
"""Palette and real font families for the approved reception page only."""
"""Shared palette and typography for the technology-blue workstation pages."""
from __future__ import annotations
import os
import sys
from pathlib import Path
from PySide6.QtGui import QFontDatabase
from PySide6.QtWidgets import QApplication
from doctor_workstation.resources import resource_path
from .theme import _register_preferred_cjk_fonts
TECH_BLUE = {
"accent": "#1769E8",
@@ -30,7 +25,7 @@ TECH_BLUE = {
def _families() -> dict[str, str]:
"""Resolve after Qt starts; font registration does not change its theme."""
"""Use the application face for Chinese, Latin text and numbers alike."""
app = QApplication.instance()
if app is None:
@@ -39,68 +34,28 @@ def _families() -> dict[str, str]:
if cached is not None:
return cached
heading = getattr(app, "_doctor_bundled_font_family", None)
if not heading:
font_path = resource_path("fonts", "NotoSansSC-VF.ttf")
if font_path.is_file():
font_id = QFontDatabase.addApplicationFont(str(font_path))
registered = QFontDatabase.applicationFontFamilies(font_id) if font_id >= 0 else []
if registered:
heading = registered[0]
app._doctor_bundled_font_family = heading
available = set(QFontDatabase.families())
# Qt's offscreen platform does not enumerate Windows fonts automatically.
# Register only files already installed on this machine, never substitutes
# downloaded or installed into the user's Windows font registry.
if sys.platform == "win32":
font_dir = (
Path(os.environ.get("SYSTEMROOT") or os.environ.get("WINDIR") or "C:/Windows") / "Fonts"
)
for family, filenames in (
("Microsoft YaHei UI", ("msyh.ttc",)),
("Segoe UI", ("segoeui.ttf", "seguisb.ttf")),
):
if family in available:
continue
for filename in filenames:
font_path = font_dir / filename
if not font_path.is_file():
continue
font_id = QFontDatabase.addApplicationFont(str(font_path))
if font_id >= 0:
available.update(QFontDatabase.applicationFontFamilies(font_id))
fallback = heading or next(
(
family
for family in ("Noto Sans SC", "Noto Sans CJK SC", "PingFang SC")
if family in available
),
app.font().family(),
)
resolved = {
"body": "Microsoft YaHei UI" if "Microsoft YaHei UI" in available else fallback,
"heading": heading or fallback,
"number": "Segoe UI" if "Segoe UI" in available else fallback,
}
# The bundled variable font supplies real Regular, Medium and Semibold
# weights. Keep the same glyph shapes in controls and custom-painted cells;
# hierarchy comes from size and weight within this one family.
family = _register_preferred_cjk_fonts()
resolved = dict.fromkeys(("body", "heading", "number"), family)
app._reception_font_families = resolved
return resolved
def body_family() -> str:
"""Regular Chinese body copy; YaHei UI has no genuine Medium face."""
"""Shared reading face for controls and table cells."""
return _families()["body"]
def heading_family() -> str:
"""Bundled Noto Sans SC supplies genuine Medium and Semibold faces."""
"""The same reading face, with genuine Medium and Semibold weights."""
return _families()["heading"]
def number_family() -> str:
"""Segoe UI supplies Regular and Semibold for numeric labels."""
"""Keep numbers and adjacent Chinese text in the same family."""
return _families()["number"]
@@ -0,0 +1,408 @@
"""Responsive, presentation-only containers for the reception workspace."""
from __future__ import annotations
from PySide6.QtCore import QSize, Qt
from PySide6.QtGui import QResizeEvent
from PySide6.QtWidgets import (
QAbstractScrollArea,
QFrame,
QHBoxLayout,
QLayout,
QScrollArea,
QSizePolicy,
QStackedWidget,
QTabBar,
QVBoxLayout,
QWidget,
)
class ReceptionWorkbench(QWidget):
"""Keep clinical material and insights available at every supported width.
The two scroll areas are moved between layouts when the workspace changes
mode. Their contents, signal connections and selected clinical pages remain
the same objects throughout the lifetime of the workbench.
"""
_WIDE_BREAKPOINT = 760
_LARGE_RAIL_BREAKPOINT = 1100
_UNRESTRICTED_WIDTH = 16_777_215
def __init__(
self,
clinical_scroll: QScrollArea,
insights: QWidget,
parent: QWidget | None = None,
) -> None:
super().__init__(parent)
self.setObjectName("ReceptionWorkbench")
self.setMinimumSize(0, 0)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.clinical_scroll = clinical_scroll
self._wide_mode: bool | None = None
self._relayout_in_progress = False
self.insights_scroll = QScrollArea(self)
self.insights_scroll.setObjectName("ReceptionInsightsScroll")
self.insights_scroll.setAccessibleName("患者资料与 AI 辅助滚动区域")
self.insights_scroll.setWidgetResizable(True)
self.insights_scroll.setFrameShape(QFrame.Shape.NoFrame)
self.insights_scroll.setHorizontalScrollBarPolicy(
Qt.ScrollBarPolicy.ScrollBarAlwaysOff
)
self.insights_scroll.setVerticalScrollBarPolicy(
Qt.ScrollBarPolicy.ScrollBarAsNeeded
)
self.insights_scroll.setWidget(insights)
for scroll in (self.clinical_scroll, self.insights_scroll):
scroll.setMinimumSize(0, 0)
scroll.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
)
scroll.setSizeAdjustPolicy(QAbstractScrollArea.SizeAdjustPolicy.AdjustIgnored)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(8)
# Scroll contents can be arbitrarily tall. They must never dictate the
# outer page's minimum height when the parent layout recalculates.
layout.setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint)
self.mode_tabs = QTabBar(self)
self.mode_tabs.setObjectName("ReceptionWorkspaceTabs")
self.mode_tabs.setAccessibleName("接诊工作区视图")
self.mode_tabs.setDrawBase(False)
self.mode_tabs.setExpanding(False)
self.mode_tabs.addTab("病历资料")
self.mode_tabs.addTab("患者资料与 AI")
self.mode_tabs.currentChanged.connect(self._select_narrow_tab)
layout.addWidget(self.mode_tabs)
self._wide_container = QWidget(self)
self._wide_container.setObjectName("ReceptionWideWorkspace")
self._wide_container.setMinimumSize(0, 0)
self._wide_container.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
)
self._wide_layout = QHBoxLayout(self._wide_container)
self._wide_layout.setContentsMargins(0, 0, 0, 0)
self._wide_layout.setSpacing(12)
self._wide_layout.setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint)
layout.addWidget(self._wide_container, 1)
self._narrow_stack = QStackedWidget(self)
self._narrow_stack.setObjectName("ReceptionNarrowWorkspace")
self._narrow_stack.setMinimumSize(0, 0)
self._narrow_stack.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
)
self._narrow_stack.layout().setSizeConstraint(
QLayout.SizeConstraint.SetNoConstraint
)
layout.addWidget(self._narrow_stack, 1)
self._update_mode()
def minimumSizeHint(self) -> QSize: # noqa: N802 - Qt override
return QSize(390, 220)
def sizeHint(self) -> QSize: # noqa: N802 - Qt override
return QSize(980, 600)
def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt override
super().resizeEvent(event)
self._update_mode()
def _select_narrow_tab(self, index: int) -> None:
if self._wide_mode is False and 0 <= index < self._narrow_stack.count():
self._narrow_stack.setCurrentIndex(index)
def _update_mode(self) -> None:
if self._relayout_in_progress:
return
wide = self.width() >= self._WIDE_BREAKPOINT
rail_width = 360 if self.width() >= self._LARGE_RAIL_BREAKPOINT else 320
if self._wide_mode is wide:
if wide and self.insights_scroll.width() != rail_width:
self.insights_scroll.setFixedWidth(rail_width)
return
self._relayout_in_progress = True
try:
self._wide_mode = wide
self._wide_container.hide()
self._narrow_stack.hide()
self.mode_tabs.setVisible(not wide)
if wide:
for scroll in (self.clinical_scroll, self.insights_scroll):
self._narrow_stack.removeWidget(scroll)
self.clinical_scroll.setMinimumWidth(0)
self.insights_scroll.setFixedWidth(rail_width)
self._wide_layout.addWidget(self.clinical_scroll, 1)
self._wide_layout.addWidget(self.insights_scroll, 0)
self.clinical_scroll.show()
self.insights_scroll.show()
self._wide_container.show()
else:
for scroll in (self.clinical_scroll, self.insights_scroll):
self._wide_layout.removeWidget(scroll)
self.insights_scroll.setMinimumWidth(0)
self.insights_scroll.setMaximumWidth(self._UNRESTRICTED_WIDTH)
self._narrow_stack.addWidget(self.clinical_scroll)
self._narrow_stack.addWidget(self.insights_scroll)
self._narrow_stack.setCurrentIndex(self.mode_tabs.currentIndex())
self._narrow_stack.show()
self.updateGeometry()
finally:
self._relayout_in_progress = False
# Append this after RECEPTION_QSS so the page keeps all existing interaction,
# loading and semantic alert states while adopting the workspace's hierarchy.
RECEPTION_WORKSPACE_QSS = r"""
QWidget#ReceptionPage QWidget#ReceptionWorkbench,
QWidget#ReceptionPage QWidget#ReceptionWideWorkspace,
QWidget#ReceptionPage QStackedWidget#ReceptionNarrowWorkspace {
background: transparent;
border: 0;
}
QWidget#ReceptionPage QFrame#ReceptionQueuePanel {
background-color: #FFFFFF;
border: 1px solid #E5ECF6;
border-radius: 8px;
}
QWidget#ReceptionPage QLabel#ReceptionQueueTitle {
font-size: 18px;
font-weight: 600;
}
QWidget#ReceptionPage QLabel#ReceptionQueueName {
font-size: 15px;
font-weight: 500;
}
QWidget#ReceptionPage QLabel#ReceptionQueueMeta,
QWidget#ReceptionPage QLabel#ReceptionQueueTime,
QWidget#ReceptionPage QLabel#ReceptionQueueSubline,
QWidget#ReceptionPage QLabel#ReceptionQueueSummary {
color: #5D6B80;
font-size: 12px;
font-weight: 400;
}
QWidget#ReceptionPage QLabel#ReceptionQueueMetric {
font-size: 13px;
}
QWidget#ReceptionPage QLabel#ReceptionQueueMetric[tone="description"] {
color: #5D6B80;
font-size: 12px;
}
QWidget#ReceptionPage QFrame#ReceptionHero,
QWidget#ReceptionPage QFrame#ReceptionClinicalCard {
min-height: 0;
background-color: #FFFFFF;
border: 1px solid #E5ECF6;
border-radius: 8px;
}
QWidget#ReceptionPage QLabel#ReceptionPatientName {
font-size: 20px;
font-weight: 600;
}
QWidget#ReceptionPage QLabel#ReceptionPatientMeta {
color: #5D6B80;
font-size: 13px;
}
QWidget#ReceptionPage QLabel#ReceptionAvatar {
color: #1555B6;
background-color: #EAF2FF;
border-radius: 12px;
font-size: 20px;
font-weight: 600;
}
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs,
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs {
background-color: #FFFFFF;
border: 0;
border-bottom: 1px solid #E5ECF6;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
}
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab,
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab {
min-height: 40px;
margin: 0;
padding: 0 14px;
color: #5D6B80;
background-color: transparent;
border: 0;
border-bottom: 2px solid transparent;
border-radius: 0;
font-size: 13px;
font-weight: 400;
}
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:first {
margin-left: 0;
padding-left: 14px;
}
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:hover,
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab:hover {
color: #1769E8;
background-color: #F3F7FD;
}
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:selected,
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab:selected {
color: #1769E8;
background-color: transparent;
border-bottom: 2px solid #1769E8;
font-weight: 500;
}
QWidget#ReceptionPage QFrame#ReceptionHistoryCard {
background-color: #FFFFFF;
border: 0;
border-radius: 0;
}
QWidget#ReceptionPage QWidget#ReceptionCaseField {
background-color: transparent;
border: 0;
border-bottom: 1px solid #EDF1F7;
border-radius: 0;
}
QWidget#ReceptionPage QLabel#ReceptionCaseHeading {
color: #202C3F;
font-size: 16px;
font-weight: 600;
}
QWidget#ReceptionPage QLabel[receptionBlockTitle="true"] {
color: #5D6B80;
font-size: 13px;
font-weight: 500;
}
QWidget#ReceptionPage QLabel[receptionBlockValue="true"] {
font-size: 14px;
font-weight: 400;
}
QWidget#ReceptionPage QLabel[receptionInlineCaption="true"] {
min-width: 0;
color: #5D6B80;
font-size: 12px;
font-weight: 400;
}
QWidget#ReceptionPage QLabel[receptionInlineValue="true"],
QWidget#ReceptionPage QLabel[receptionLifestyleChip="true"] {
font-size: 13px;
font-weight: 400;
}
QWidget#ReceptionPage QFrame#ReceptionPatientSummaryCard,
QWidget#ReceptionPage QFrame#ReceptionVitalsCard,
QWidget#ReceptionPage QFrame#ReceptionLabsCard {
background-color: #FFFFFF;
border: 1px solid #E5ECF6;
border-radius: 8px;
}
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue {
color: #24334A;
font-size: 13px;
font-weight: 500;
}
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue[missing="true"] {
color: #697386;
font-weight: 400;
}
QWidget#ReceptionPage QFrame#ReceptionMetricCell,
QWidget#ReceptionPage QFrame#ReceptionMetricCell[firstMetric="true"] {
background-color: transparent;
border: 0;
border-radius: 0;
}
QWidget#ReceptionPage QLabel[receptionMetricCaption="true"],
QWidget#ReceptionPage QLabel[receptionMetricUnit="true"],
QWidget#ReceptionPage QLabel[receptionBmiState="true"] {
color: #5D6B80;
font-size: 12px;
font-weight: 400;
}
QWidget#ReceptionPage QFrame#ReceptionMetricCell QLabel[receptionMetricValue="true"] {
font-size: 18px;
font-weight: 500;
}
QWidget#ReceptionPage QFrame#ReceptionLabCell {
min-height: 0;
padding: 0;
background-color: #FFFFFF;
border: 0;
border-bottom: 1px solid #EDF1F7;
border-radius: 0;
}
QWidget#ReceptionPage QFrame#ReceptionLabCell QLabel[receptionMetricValue="true"] {
font-size: 13px;
font-weight: 400;
}
QWidget#ReceptionPage QPushButton#ReceptionMissingLabsButton {
min-height: 28px;
max-height: 28px;
padding: 0;
color: #1769E8;
background: transparent;
border: 0;
text-align: left;
font-size: 12px;
}
QWidget#ReceptionPage QLabel[receptionMetricState="true"] {
min-height: 18px;
padding: 0 5px;
background-color: #F0F5FD;
border: 0;
border-radius: 4px;
font-size: 12px;
font-weight: 400;
}
QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"] {
color: #BE4B58;
background-color: #FFF4F5;
}
QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"][warning="true"] {
color: #A9691D;
background-color: #FFF9EF;
border-radius: 4px;
}
QWidget#ReceptionPage QFrame#ReceptionAiAnalysisCard,
QWidget#ReceptionPage QFrame#ReceptionAiAssistantCard {
background-color: #FFFFFF;
border: 1px solid #DCE5F0;
border-radius: 8px;
}
QWidget#ReceptionPage QLabel#ReceptionAiTitle,
QWidget#ReceptionPage QPushButton#ReceptionAiTitle {
font-size: 14px;
font-weight: 500;
}
QWidget#ReceptionPage QLabel#ReceptionAiAssistantHint {
color: #5D6B80;
font-size: 13px;
font-weight: 400;
}
QWidget#ReceptionPage QPushButton[receptionAiPrompt="true"] {
min-height: 28px;
max-height: 28px;
padding: 0 8px;
font-size: 12px;
border-radius: 6px;
}
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll {
background-color: transparent;
border: 0;
}
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar:vertical {
width: 8px;
margin: 4px 2px;
background: transparent;
}
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::handle:vertical {
min-height: 32px;
background-color: #C4D2E5;
border-radius: 4px;
}
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::add-line:vertical,
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::sub-line:vertical {
height: 0;
}
"""
+31 -25
View File
@@ -72,7 +72,7 @@ from .pages import (
ReceptionPage,
)
from .reception_style import TECH_BLUE, body_family, heading_family, number_family
from .theme import COLORS, crisp_pixmap
from .theme import COLORS, TYPE, crisp_pixmap
from .widgets import (
EmptyState,
StatusBadge,
@@ -506,13 +506,14 @@ class _AssistantRobot(QWidget):
painter.setPen(Qt.PenStyle.NoPen)
if self.property("receptionTechBlue"):
painter.setBrush(QColor(TECH_BLUE["accent"]))
painter.drawRoundedRect(QRectF(7, 7, 44, 44), 6, 6)
tile = QRectF(6, 6, 36, 36)
painter.drawRoundedRect(tile, 6, 6)
painter.setPen(QColor(TECH_BLUE["surface"]))
font = QFont(number_family())
font.setPixelSize(21)
font.setPixelSize(18)
font.setWeight(QFont.Weight.DemiBold)
painter.setFont(font)
painter.drawText(QRectF(7, 7, 44, 44), Qt.AlignmentFlag.AlignCenter, "AI")
painter.drawText(tile, Qt.AlignmentFlag.AlignCenter, "AI")
return
painter.setBrush(QColor(COLORS["indigo_pale"]))
painter.drawEllipse(QRectF(1, 1, 54, 54))
@@ -562,14 +563,12 @@ class _AssistantStatus(QLabel):
color = QColor(online_color if self._online else "#EC5266")
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(color)
diameter = 9 if reception else 6
diameter = 6
painter.drawEllipse(QRectF(1, (self.height() - diameter) / 2, diameter, diameter))
painter.setPen(color)
font = QFont(self.font())
font.setPixelSize(13 if reception else 10)
painter.setFont(font)
painter.setFont(self.font())
painter.drawText(
QRectF(17 if reception else 12, 0, self.width() - (17 if reception else 12), self.height()),
QRectF(12, 0, self.width() - 12, self.height()),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
self.text(),
)
@@ -1085,7 +1084,7 @@ class ShellWindow(QMainWindow):
font-weight: 600;
}
QLabel#ShellAssistantName { color: #1A1C1F; font-size: 13px; font-weight: 500; }
QLabel#ShellAssistantStatus { color: #287B65; font-size: 13px; }
QLabel#ShellAssistantStatus { color: #287B65; font-size: 12px; }
QPushButton#ShellAssistantButton {
min-height: 34px;
color: #FFFFFF;
@@ -1592,15 +1591,16 @@ class ShellWindow(QMainWindow):
self.brand_layout.setSpacing(13 if active else 10)
self.brand_mark.setFixedSize(38 if active else 36, 38 if active else 36)
self.nav_layout.setContentsMargins(*self._navigation_margins())
self.nav_layout.setSpacing(6 if active else 0)
self.assistant_card.setFixedHeight(171 if active else 157)
self.assistant_layout.setContentsMargins(*(13, 19, 13, 20) if active else (12, 12, 12, 20))
self.nav_layout.setSpacing(4 if active else 0)
self.assistant_card.setFixedHeight(132 if active else 157)
self.assistant_layout.setContentsMargins(*(13, 12, 13, 12) if active else (12, 12, 12, 20))
self.assistant_head_layout.setContentsMargins(4 if active else 0, 0, 0, 0)
self.assistant_head_layout.setSpacing(8 if active else 9)
self.assistant_glyph.setFixedSize(48 if active else 56, 48 if active else 56)
self.assistant_outer_layout.setContentsMargins(*(20, 0, 20, 0) if active else (13, 0, 13, 0))
self.assistant_status.setFixedHeight(22 if active else 18)
self.assistant_button.setFixedHeight(46 if active else 34)
self.upload_settings_button.setFixedHeight(94 if active else 44)
self.assistant_status.setFixedHeight(18)
self.assistant_button.setFixedHeight(36 if active else 34)
self.upload_settings_button.setFixedHeight(52 if active else 44)
self.upload_settings_button.setIcon(_painted_shell_icon("settings", 20, reception=True) if active else QIcon())
self.upload_settings_button.setIconSize(QSize(20, 20) if active else QSize(16, 16))
self.upload_settings_button.setText("设置 ›" if active else "设置 ›")
@@ -1686,15 +1686,15 @@ class ShellWindow(QMainWindow):
}}
QLabel#ShellBrandName {{
font-family: "{heading_family()}"; font-weight: 600;
color: {TECH_BLUE['heading']}; font-size: 18px;
color: {TECH_BLUE['heading']}; font-size: {TYPE['fs_section']};
}}
QLabel#ShellBrandSubtitle {{ color: {TECH_BLUE['text']}; font-size: 13px; }}
QLabel#ShellBrandSubtitle {{ color: {TECH_BLUE['muted']}; font-size: {TYPE['fs_small']}; }}
QPushButton#ShellNavButton {{
font-family: "{body_family()}"; font-weight: 400;
min-height: 52px; max-height: 52px;
min-height: 44px; max-height: 44px;
border: 0; border-left: 5px solid transparent;
border-radius: 6px;
padding: 0 16px; font-size: 15px;
padding: 0 16px; font-size: {TYPE['fs_body']};
color: {TECH_BLUE['text']};
}}
QPushButton#ShellNavButton:checked,
@@ -1715,13 +1715,19 @@ class ShellWindow(QMainWindow):
border: 1px solid {_RECEPTION_CHROME_LINE};
}}
QLabel#ShellAssistantName {{
font-family: "{heading_family()}"; font-weight: 500; font-size: 16px;
font-family: "{heading_family()}"; font-weight: 500; font-size: {TYPE['fs_body']};
}}
QLabel#ShellAssistantStatus {{
font-size: {TYPE['fs_small']};
}}
QPushButton#ShellAssistantButton, QPushButton#ShellSettingsButton {{
font-family: "{body_family()}"; font-weight: 400; font-size: 15px;
font-family: "{body_family()}"; font-weight: 400; font-size: {TYPE['fs_body']};
}}
QPushButton#ShellAssistantButton {{ border-radius: 6px; }}
QPushButton#ShellSettingsButton {{ text-align: left; padding: 0 32px; }}
QPushButton#ShellSettingsButton {{
min-height: 50px; max-height: 50px;
text-align: left; padding: 0 32px;
}}
QPushButton#ShellAssistantButton:focus {{
border: 2px solid {TECH_BLUE['focus']};
}}
@@ -1735,12 +1741,12 @@ class ShellWindow(QMainWindow):
QFrame#ShellGlobalSearch {{ border: 1px solid {_RECEPTION_CHROME_LINE}; border-radius: 5px; }}
QFrame#ShellUserSeparator {{ background: {_RECEPTION_CHROME_LINE}; border: 0; }}
QLabel#ShellShortcutHint {{
font-family: "{number_family()}"; font-size: 13px;
font-family: "{number_family()}"; font-size: {TYPE['fs_small']};
padding: 4px 9px; border-radius: 4px;
border: 1px solid {_RECEPTION_CHROME_LINE};
}}
QLineEdit#ShellGlobalSearchInput {{
color: {TECH_BLUE['text']}; font-size: 15px;
color: {TECH_BLUE['text']}; font-size: {TYPE['fs_body']};
min-height: 40px; max-height: 40px;
}}
QPushButton#ShellAiEntry:pressed {{ background: {TECH_BLUE['selection']}; }}
+2 -1
View File
@@ -85,10 +85,11 @@ COLORS = {
# --- Type scale -----------------------------------------------------------
# Six steps, tuned for 简体中文 at Windows 100%–150% scaling. CJK glyphs carry
# Seven steps, tuned for 简体中文 at Windows 100%–150% scaling. CJK glyphs carry
# more ink than Latin at the same pixel size, so the steps are spaced widely
# enough that two adjacent levels are always distinguishable.
TYPE = {
"fs_small": "12px", # secondary shell copy, status, keyboard hints
"fs_caption": "13px", # table headers, hints, badges, timestamps
"fs_body": "14px", # default UI text
"fs_strong": "15px", # emphasised body, dialog prompts
+431
View File
@@ -0,0 +1,431 @@
from __future__ import annotations
import os
from copy import deepcopy
from dataclasses import FrozenInstanceError
from datetime import datetime
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QPoint, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel, QToolTip
from doctor_workstation.ui.dialogs.ai_consult_charts import (
GlucoseReportCard,
build_glucose_chart_data,
)
from doctor_workstation.ui.dialogs.ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
UNKNOWN_COLOR,
)
@pytest.fixture(scope="module")
def application() -> QApplication:
return QApplication.instance() or QApplication([])
def _row(day: str = "2026-08-18", **changes: Any) -> dict[str, Any]:
return {
"diagnosis_id": 501,
"patient_id": 1501,
"record_date": day,
"fasting_blood_sugar": 6.8,
**changes,
}
def _tracking(*rows: Any, **changes: Any) -> dict[str, Any]:
return {"diagnosis_id": 501, "patient_id": 1501, "blood_records": list(rows), **changes}
def _build(tracking: Any):
return build_glucose_chart_data(tracking, diagnosis_id=501, patient_id=1501)
def test_real_dto_is_immutable_chronological_and_does_not_average_same_day() -> None:
tracking = _tracking(
_row("2026-08-20", record_time="09:10", fasting_blood_sugar="7.2 mmol/L"),
_row("2026-08-18", record_time="09:00", fasting_blood_sugar=6.1),
_row("2026-08-18", record_time="08:00", fasting_blood_sugar=5.9),
_row("2026-08-19", fasting_blood_sugar=None, postprandial_blood_sugar="9.1"),
)
before = deepcopy(tracking)
data = _build(tracking)
assert tracking == before
assert data.available and data.readout_count == 4 and data.record_count == 4
assert [reading.fasting for reading in data.readings] == [5.9, 6.1, None, 7.2]
assert data.readings[2].postprandial == 9.1
assert data.readings[0].recorded_at == datetime(2026, 8, 18, 8)
assert data.readings[0].time_label == "2026-08-18 08:00"
assert data.readings[2].time_label == "2026-08-19"
assert data.date_range is not None
assert tuple(day.isoformat() for day in data.date_range) == ("2026-08-18", "2026-08-20")
assert data.excluded_count == 0
with pytest.raises(FrozenInstanceError):
data.readings[0].fasting = 99 # type: ignore[misc]
tracking["blood_records"][0]["fasting_blood_sugar"] = 99
assert data.readings[-1].fasting == 7.2
@pytest.mark.parametrize("owner", [None, True, 501.0, "501", 502, 0])
def test_tracking_root_requires_exact_diagnosis_owner(owner: Any) -> None:
data = _build(_tracking(_row(), diagnosis_id=owner))
assert not data.available and data.readings == ()
assert "归属" in data.unavailable_reason
def test_ownerless_root_is_rejected() -> None:
tracking = _tracking(_row())
del tracking["diagnosis_id"]
assert not _build(tracking).available
@pytest.mark.parametrize("owner", [None, True, 501.0, "501", 502, 0])
def test_rows_require_exact_diagnosis_owner(owner: Any) -> None:
data = _build(_tracking(_row(diagnosis_id=owner), _row("2026-08-19")))
assert data.record_count == 1
assert data.readings[0].recorded_at.day == 19
assert data.excluded_count == 1
@pytest.mark.parametrize("owner", [None, True, 1501.0, "1501", 1502, 0])
def test_declared_patient_owner_is_strict_at_root_and_row(owner: Any) -> None:
assert not _build(_tracking(_row(), patient_id=owner)).available
data = _build(_tracking(_row(patient_id=owner)))
assert not data.available and data.readings == ()
assert data.excluded_count == 1
def test_diagnosis_owned_rows_may_omit_patient_id_but_not_diagnosis_id() -> None:
row = _row()
del row["patient_id"]
assert _build(_tracking(row)).readout_count == 1
del row["diagnosis_id"]
assert not _build(_tracking(row)).available
def test_root_patient_owner_is_used_when_the_caller_has_no_patient_id() -> None:
data = build_glucose_chart_data(_tracking(_row(patient_id=1502)), diagnosis_id=501)
assert not data.available and data.excluded_count == 1
@pytest.mark.parametrize(
"value",
[
True,
False,
float("nan"),
float("inf"),
-float("inf"),
-1,
"-1",
"6-9",
"约 6.8",
"~6.8",
"<6.8",
"6.8±0.2",
"6.8 mg/dL",
"血糖6.8",
{"value": 6.8},
"Infinity",
],
)
def test_ambiguous_readings_stay_gaps_and_are_never_guessed(value: Any) -> None:
data = _build(_tracking(_row(fasting_blood_sugar=value)))
assert not data.available and data.readout_count == 0
assert len(data.readings) == 1 and data.readings[0].fasting is None
assert data.excluded_count == 1
@pytest.mark.parametrize("value", [None, "", "—", "未填写", 0, 0.0, "0", "0.0 mmol/L"])
def test_daily_zero_and_missing_defaults_are_absent_without_ambiguous_warning(value: Any) -> None:
data = _build(
_tracking(
_row(
fasting_blood_sugar=value,
postprandial_blood_sugar=0,
other_blood_sugar=0,
remark="继续观察",
)
)
)
assert not data.available and data.readout_count == 0
assert data.excluded_count == 0
assert all(reading.readout_count == 0 for reading in data.readings)
@pytest.mark.parametrize("value", ["6.80", "6.8 mmol/L", " 6.8 MMOL / l ", 6.8])
def test_exact_mmol_readings_are_accepted(value: Any) -> None:
data = _build(_tracking(_row(fasting_blood_sugar=value)))
assert data.readings[0].fasting == 6.8
assert data.excluded_count == 0
def test_partial_ambiguous_row_preserves_verified_series_and_records_one_exclusion() -> None:
data = _build(
_tracking(
_row(fasting_blood_sugar="6-9", postprandial_blood_sugar=9.3, other_blood_sugar="约7")
)
)
assert data.available and data.readout_count == 1
assert data.readings[0].fasting is None
assert data.readings[0].postprandial == 9.3
assert data.excluded_count == 1
@pytest.mark.parametrize(
"day", [None, "", "2026-02-30", "08-18", "2026-8-18", "2026-08-18 大约", 1787040000]
)
def test_missing_or_ambiguous_date_never_becomes_today(day: Any) -> None:
data = _build(_tracking(_row(day)))
assert data.readings == () and data.excluded_count == 1
@pytest.mark.parametrize("clock", ["25:10", "8:30", "上午", True])
def test_invalid_declared_record_time_is_excluded(clock: Any) -> None:
assert _build(_tracking(_row(record_time=clock))).excluded_count == 1
def test_legacy_entries_require_owners_and_keep_periods_distinct() -> None:
tracking = {
"diagnosis_id": 501,
"blood_sugar": {
"entries": [
{"diagnosis_id": 501, "date": "2026-08-18", "value": "6.2", "period": "空腹"},
{"diagnosis_id": 501, "date": "2026-08-19", "value": "9.1", "period": "餐后"},
{
"diagnosis_id": 501,
"measured_at": "2026-08-19T20:10:00",
"value": "7.4",
"period": "睡前",
},
{"date": "2026-08-20", "value": "20.2", "period": "空腹"},
]
},
}
data = _build(tracking)
assert data.readout_count == 3 and data.excluded_count == 1
assert data.readings[0].fasting == 6.2
assert data.readings[1].postprandial == 9.1
assert data.readings[2].other == 7.4
assert data.readings[2].time_label == "2026-08-19 20:10"
tracking["blood_sugar"]["diagnosis_id"] = 502
assert not _build(tracking).available
def test_unit_metadata_cannot_relabel_mg_dl_as_mmol() -> None:
assert not _build(_tracking(_row(), unit="mg/dL")).available
assert not _build(_tracking(_row(unit="mg/dL"))).available
assert _build(_tracking(_row(unit="mmol/L"))).available
def test_production_source_takes_precedence_to_avoid_duplicate_representations() -> None:
tracking = _tracking(
_row(), blood_sugar={"entries": [{"diagnosis_id": 501, "date": "2026-08-18", "value": 9.9}]}
)
assert _build(tracking).readout_count == 1
def test_source_states_are_immutable_and_require_the_same_owned_row() -> None:
tracking = _tracking(
_row(fasting_glucose_status="normal", postprandial_glucose=9.3,
postprandial_glucose_status="low", other_glucose=7.1, other_glucose_status="warning"),
_row("2026-08-19", diagnosis_id=502, fasting_blood_sugar_status="high"),
fasting_blood_sugar_status="high",
)
before = deepcopy(tracking)
data = _build(tracking)
assert tracking == before and data.excluded_count == 1
assert len(data.readings) == 1
reading = data.readings[0]
assert (reading.fasting_status, reading.postprandial_status, reading.other_status) == (
"normal", "low", "warning",
)
tracking["blood_records"][0]["fasting_glucose_status"] = "high"
assert reading.fasting_status == "normal"
with pytest.raises(FrozenInstanceError):
reading.fasting_status = "high" # type: ignore[misc]
@pytest.mark.parametrize("status", [None, True, False, ["normal"], {"status": "normal"}])
def test_untyped_glucose_states_stay_unclassified(status: Any) -> None:
data = _build(_tracking(_row(fasting_blood_sugar_status=status)))
assert data.readings[0].fasting_status == ""
def test_glucose_points_tables_and_accessibility_share_explicit_states(application) -> None:
data = _build(_tracking(
_row("2026-08-18", fasting_blood_sugar=20, fasting_blood_sugar_status="normal",
postprandial_blood_sugar=3, postprandial_blood_sugar_status="low",
other_blood_sugar=12, other_blood_sugar_status="unclassified"),
_row("2026-08-19", fasting_blood_sugar=30),
_row("2026-08-20", fasting_blood_sugar=0, fasting_blood_sugar_status="normal"),
))
card = GlucoseReportCard(data)
card.resize(650, 420)
card.show()
application.processEvents()
assert card.chart is not None
chart = card.chart
image = chart.grab().toImage()
first = data.readings[0]
for column, field, color, status in (
(1, "fasting", NORMAL_COLOR, "normal"),
(2, "postprandial", ABNORMAL_COLOR, "low"),
(3, "other", UNKNOWN_COLOR, "unclassified"),
):
point = chart._position(first, getattr(first, field))
assert chart._point_color(first, field) == color
assert image.pixelColor(point.toPoint()).name().casefold() == color.casefold()
assert card.table.item(0, column).foreground().color().name().casefold() == color.casefold()
assert status in card.table.item(0, column).toolTip()
assert status in chart._point_tooltip(point)
assert status in chart.accessibleDescription()
assert card.table.item(1, 1).foreground().color().name() == UNKNOWN_COLOR.casefold()
assert "未标注" in card.table.item(1, 1).toolTip()
assert card.table.item(2, 1).text() == "—"
assert card.table.item(2, 1).foreground().color().name() == UNKNOWN_COLOR.casefold()
assert "未记录" in card.table.item(2, 1).toolTip()
assert "空腹血糖 — · 状态 未记录" in chart.accessibleDescription()
assert "红色异常、绿色正常、灰色未记录/未标注" in chart.accessibleDescription()
card.close()
def test_glucose_connection_is_gray_between_explicit_normal_points(application) -> None:
data = _build(_tracking(
_row("2026-08-18", fasting_blood_sugar=5, fasting_blood_sugar_status="normal"),
_row("2026-08-20", fasting_blood_sugar=5, fasting_blood_sugar_status="normal"),
))
card = GlucoseReportCard(data)
card.resize(640, 420)
card.show()
application.processEvents()
assert card.chart is not None
left, right = [card.chart._position(reading, 5) for reading in data.readings]
midpoint = (left + right) / 2
image = card.chart.grab().toImage()
center = midpoint.toPoint()
assert UNKNOWN_COLOR.casefold() in {
image.pixelColor(center.x() + dx, center.y() + dy).name()
for dx in (-1, 0, 1) for dy in (-1, 0, 1)
}
assert image.pixelColor(left.toPoint()).name() == NORMAL_COLOR.casefold()
card.close()
def test_explicit_missing_series_preserve_gaps_and_actual_date_spacing(
application: QApplication,
) -> None:
data = _build(
_tracking(
_row("2026-08-01", fasting_blood_sugar=5.8),
_row("2026-08-02", fasting_blood_sugar="6-9"),
_row("2026-08-11", fasting_blood_sugar=7.1),
)
)
assert [reading.fasting for reading in data.readings] == [5.8, None, 7.1]
card = GlucoseReportCard(data)
card.resize(700, 400)
card.show()
application.processEvents()
assert card.chart is not None
first = card.chart._position(data.readings[0], 5.8)
gap = card.chart._position(data.readings[1], 5.8)
last = card.chart._position(data.readings[2], 5.8)
assert (gap.x() - first.x()) / (last.x() - first.x()) == pytest.approx(0.1)
assert not card.grab().isNull()
card.close()
def test_single_point_hover_and_original_records_toggle(
application: QApplication, monkeypatch: pytest.MonkeyPatch
) -> None:
data = _build(_tracking(_row(record_time="08:15", fasting_blood_sugar=6.83)))
card = GlucoseReportCard(data)
card.resize(500, 420)
card.show()
application.processEvents()
assert card.objectName() == "AiConsultGlucoseReport"
assert card.chart is not None and card.chart.data is data
assert card.chart.objectName() == "AiConsultGlucoseChart"
assert card.toggle_button is not None
assert card.table.isHidden()
assert card.table.item(0, 0).text() == "2026-08-18 08:15"
assert card.table.item(0, 1).text() == "6.83"
assert card.table.item(0, 2).text() == "—"
assert "6.83 mmol/L" in card.chart.accessibleDescription()
tooltips: list[str] = []
monkeypatch.setattr(QToolTip, "showText", lambda _position, text, *_args: tooltips.append(text))
point = card.chart._position(data.readings[0], 6.83)
QTest.mouseMove(card.chart, QPoint(round(point.x()), round(point.y())))
application.processEvents()
assert tooltips and "2026-08-18 08:15" in tooltips[-1] and "6.83 mmol/L" in tooltips[-1]
QTest.mouseClick(card.toggle_button, Qt.MouseButton.LeftButton)
assert not card.table.isHidden() and card.toggle_button.isChecked()
assert card.toggle_button.text() == "收起原始记录"
QTest.mouseClick(card.toggle_button, Qt.MouseButton.LeftButton)
assert card.table.isHidden()
card.close()
def test_overlapping_observations_remain_separate_in_hover_and_table(
application: QApplication,
) -> None:
data = _build(_tracking(_row(record_time="08:15"), _row(record_time="08:15")))
card = GlucoseReportCard(data)
card.resize(500, 420)
card.show()
application.processEvents()
assert card.chart is not None
tip = card.chart._point_tooltip(card.chart._position(data.readings[0], 6.8))
assert "记录 1" in tip and "记录 2" in tip
assert card.table.rowCount() == 2
card.close()
@pytest.mark.parametrize("width", [320, 580, 880])
def test_report_card_fits_narrow_and_wide_columns(application: QApplication, width: int) -> None:
data = _build(
_tracking(
_row(other_blood_sugar=8.2, postprandial_blood_sugar=9.1),
_row("2026-08-19", fasting_blood_sugar="6-9"),
)
)
card = GlucoseReportCard(data)
card.resize(width, card.sizeHint().height())
card.show()
application.processEvents()
assert card.width() == width
assert card.chart is not None and card.chart.height() >= 210
assert card.chart.geometry().right() < width
for label in card.findChildren(QLabel):
assert label.geometry().right() < width
assert not card.grab().isNull()
assert card.toggle_button is not None
card.toggle_button.click()
application.processEvents()
assert card.table.geometry().right() < width
assert not card.grab().isNull()
card.close()
@pytest.mark.parametrize(
"tracking", [None, {}, _tracking(), _tracking(_row(fasting_blood_sugar=0, remark="仅有备注"))]
)
def test_unavailable_state_has_no_fabricated_chart_or_empty_toggle(
application: QApplication, tracking: Any
) -> None:
card = GlucoseReportCard(_build(tracking))
card.resize(380, card.sizeHint().height())
card.show()
application.processEvents()
assert card.chart is None and card.toggle_button is None and card.table.isHidden()
assert card.height() < 210
assert any("暂无可绘制" in label.text() for label in card.findChildren(QLabel))
assert not card.grab().isNull()
card.close()
+407
View File
@@ -0,0 +1,407 @@
from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtGui import QTextCursor, QTextDocument
from PySide6.QtWidgets import QApplication
from doctor_workstation.ui.dialogs.ai_consult_metric_text import (
MetricTextState,
metric_text_context,
metric_text_html,
)
@pytest.fixture(scope="module", autouse=True)
def application() -> QApplication:
return QApplication.instance() or QApplication([])
def _document(text: str, *, metric_label: str = "") -> QTextDocument:
document = QTextDocument()
document.setHtml(metric_text_html(text, metric_label=metric_label))
assert document.toPlainText() == text.replace("\r\n", "\n").replace("\r", "\n")
return document
def _color(document: QTextDocument, phrase: str, offset: int = 0) -> str:
position = document.toPlainText().index(phrase) + offset
cursor = QTextCursor(document)
cursor.setPosition(position)
cursor.movePosition(QTextCursor.MoveOperation.NextCharacter, QTextCursor.MoveMode.KeepAnchor)
return cursor.charFormat().foreground().color().name().upper()
@pytest.mark.parametrize(
"text,measurement",
[
("空腹血糖6-7 mmol/L,餐后8-9mmol/L", "6-7 mmol/L"),
("空腹血糖6-7 mmol/L,餐后8-9mmol/L", "8-9mmol/L"),
("血糖<7.0 mmol/L", "<7.0 mmol/L"),
("血糖≤ 7.0 mmol/L", "≤ 7.0 mmol/L"),
("血糖<= 7.0 mmol/L", "<= 7.0 mmol/L"),
("血糖<7.0 mmol/L", "<7.0 mmol/L"),
("血糖3.9~6.1 mmol/L", "3.9~6.1 mmol/L"),
("血糖4.4至7.0 mmol/L", "4.4至7.0 mmol/L"),
("BP140/90mmHg", "140/90mmHg"),
("血压140 / 90 mmHg", "140 / 90 mmHg"),
("HbA1c7.2%", "7.2%"),
("糖化血红蛋白(HbA1c)7.2%", "7.2%"),
("BMI26.1", "26.1"),
("BMI26.1kg/m²", "26.1kg/m²"),
("体质量指数:26.1", "26.1"),
("身高175cm,体重80 kg", "175cm"),
("身高175cm,体重80 kg", "80 kg"),
("身高1.75m", "1.75m"),
("height175cm,weight80kg", "175cm"),
("height175cm,weight80kg", "80kg"),
("LDL-C130mg/dL", "130mg/dL"),
("TC:5.8mmol/L", "5.8mmol/L"),
("eGFR 85 ml/min/1.73m²", "85 ml/min/1.73m²"),
("eGFR:85", "85"),
("eGFR 85 mL/min/1.73 m2", "85 mL/min/1.73 m2"),
("ACR30mg/g", "30mg/g"),
("尿白蛋白肌酐比值30mg/gCr", "30mg/gCr"),
("肌酐88 μmol/L", "88 μmol/L"),
("尿酸300µmol/L", "300µmol/L"),
("heart_rate:72", "72"),
("heart_rate72bpm", "72bpm"),
("心率72次/分", "72次/分"),
("HR72bpm", "72bpm"),
("血氧饱和度98%", "98%"),
("体温36.8℃", "36.8℃"),
("ALT35U/L", "35U/L"),
("血红蛋白130g/L", "130g/L"),
],
)
def test_clinical_values_are_semibold_gray_and_preserve_all_characters(
text: str, measurement: str
) -> None:
document = _document(text)
for offset in range(len(measurement)):
assert _color(document, measurement, offset) == "#697386"
cursor = QTextCursor(document)
cursor.setPosition(document.toPlainText().index(measurement))
cursor.movePosition(QTextCursor.MoveOperation.NextCharacter, QTextCursor.MoveMode.KeepAnchor)
assert cursor.charFormat().fontWeight() >= 600
@pytest.mark.parametrize("cue", ["目标", "参考", "理想", "阈值"])
def test_targets_and_reference_ranges_stay_gray(cue: str) -> None:
document = _document(f"当前血糖8.2 mmol/L,{cue}:<7.0 mmol/L")
assert _color(document, "8.2 mmol/L") == "#697386"
for offset in range(len("<7.0 mmol/L")):
assert _color(document, "<7.0 mmol/L", offset) == "#697386"
def test_percent_targets_inherit_only_a_clinical_percent_label() -> None:
document = _document("HbA1c7.2%,目标<7.0%;总体完成率80%,风险降低20%")
assert _color(document, "7.2%") == "#697386"
assert _color(document, "<7.0%") == "#697386"
assert _color(document, "80%") != "#697386"
assert _color(document, "20%") != "#697386"
def test_current_readings_after_targets_do_not_keep_reference_color() -> None:
document = _document("目标<7.0 mmol/L;当前8.2 mmol/L,6.8 mmol/L(参考值)")
assert _color(document, "<7.0 mmol/L") == "#697386"
assert _color(document, "8.2 mmol/L") == "#697386"
assert _color(document, "6.8 mmol/L") == "#697386"
@pytest.mark.parametrize(
"text",
[
"诊单ID:123456;patient_id=1501;流水ABC123456;电话13800138000",
"2026-08-18,2026/08/19,08:30,第1章,1. 检查,2. 处理",
"病程3年,持续2周,随访7天,每次30分钟",
"二甲双胍500mg,每日2次;胰岛素10U;阿司匹林100 mg",
"剂量0.2mg/kg、浓度5mg/mL,外用2%利多卡因",
"统计显示80%的患者改善20%,目标完成率90%,报销比例50%",
"BMI2026-08-18;eGFR2026/08/19;heart_rate2026-08-18",
"not_BMI26.1;abceGFR85;ID7mmol/L;abc72bpm",
],
)
def test_unrelated_numbers_and_drug_doses_remain_unemphasized(text: str) -> None:
rendered = metric_text_html(text)
_document(text)
assert "color:" not in rendered
def test_explicit_statuses_are_emphasized_without_classifying_the_numbers() -> None:
document = _document("血糖6.0 mmol/L未达标;血压140/90mmHg正常;血糖偏高;检查异常")
assert _color(document, "6.0 mmol/L") == "#BD4B58"
assert _color(document, "140/90mmHg") == "#287B65"
assert _color(document, "未达标") == "#BD4B58"
assert _color(document, "正常") == "#287B65"
assert _color(document, "偏高") == "#BD4B58"
assert _color(document, "异常") == "#BD4B58"
@pytest.mark.parametrize(
"status,color",
[
("未达标", "#BD4B58"),
("不达标", "#BD4B58"),
("尚未完全达标", "#BD4B58"),
("未见异常", "#287B65"),
("无异常", "#287B65"),
("未见明显异常", "#287B65"),
("没有显著异常", "#287B65"),
("不正常", "#BD4B58"),
("非正常", "#BD4B58"),
("未恢复正常", "#BD4B58"),
("已达标", "#287B65"),
],
)
def test_negated_statuses_do_not_color_a_misleading_substring(status: str, color: str) -> None:
document = _document(status)
for offset in range(len(status)):
assert _color(document, status, offset) == color
@pytest.mark.parametrize(
"text",
[
"建议复查以排除异常",
"警惕血糖偏低风险",
"可能偏高,需结合进一步检查",
"若仍未达标,应复查",
"不能排除血糖异常",
"是否正常有待检查",
"未见升高;无明显升高;不偏高",
"无法达标;未达到正常;不能完全达标",
"正常值与正常范围;达标率80%",
"如血糖升高或不达标,应随访",
"需使血糖达标",
"建议控制至正常,争取早日达标",
],
)
def test_uncertain_conditional_or_recommended_statuses_stay_neutral(text: str) -> None:
_document(text)
assert "color:" not in metric_text_html(text)
@pytest.mark.parametrize(
"text",
[
"",
" 原文 保留\t制表符\n\n最后 ",
"\n首行前换行\r\n血糖<7.0 mmol/L\r末行\n",
'<script>alert("test")</script>\n<a href="https://example.com">6-7 mmol/L</a>',
'<img src="x" onerror="alert(1)">HbA1c7.2% &lt;7% &nbsp; & custom',
'<span style="color:red">正常</span> & \'" < >',
],
)
def test_html_is_literal_and_plain_text_and_whitespace_are_preserved(text: str) -> None:
document = _document(text)
html = metric_text_html(text)
assert "<script>" not in html
assert "<a " not in html
assert "<img " not in html
assert '<span style="color:red">' not in html
assert not document.find("https://example.com").charFormat().isAnchor()
assert "\n" not in html
@pytest.mark.parametrize(
"label,text,reading",
[
("空腹血糖", "FPG6.0mmol/L", "6.0mmol/L"),
("FPG", "空腹6.0 mmol/L", "6.0 mmol/L"),
("fasting_glucose", "空腹血糖6.0 mmol/L", "6.0 mmol/L"),
("HbA1c", "糖化血红蛋白7.2%", "7.2%"),
("糖化血红蛋白", "glycated hemoglobin 7.2%", "7.2%"),
("glycated haemoglobin", "HbA1c7.2%", "7.2%"),
("血压", "BP140/90mmHg", "140/90mmHg"),
("LDL-C", "低密度脂蛋白胆固醇3.2 mmol/L", "3.2 mmol/L"),
("尿素氮", "尿素氮6.0 mmol/L", "6.0 mmol/L"),
],
)
def test_recorded_states_match_field_aliases(label: str, text: str, reading: str) -> None:
with metric_text_context([MetricTextState(label, reading, "high")]):
assert _color(_document(text), reading) == "#BD4B58"
@pytest.mark.parametrize(
"status,color",
[
("high", "#BD4B58"),
("low", "#BD4B58"),
("warning", "#BD4B58"),
("未达标", "#BD4B58"),
("偏低", "#BD4B58"),
("normal", "#287B65"),
("达标", "#287B65"),
("unknown", "#697386"),
("", "#697386"),
("未记录", "#697386"),
("unexpected", "#697386"),
],
)
def test_value_only_widgets_use_the_supplied_field(status: str, color: str) -> None:
with metric_text_context([MetricTextState("FPG", "6.0 mmol/L", status)]):
document = _document("6.0 mmol/L", metric_label="空腹血糖")
assert _color(document, "6.0 mmol/L") == color
assert _color(_document("6.0 mmol/L"), "6.0 mmol/L") == "#697386"
def test_unitless_value_only_widgets_bind_without_classifying_other_numbers() -> None:
with metric_text_context([MetricTextState("BMI", "26.1", "normal")]):
assert _color(_document("26.1", metric_label="体质指数"), "26.1") == "#287B65"
assert "color:" not in metric_text_html("2026-08-18", metric_label="BMI")
def test_context_restores_outer_state_after_nested_scope_and_exception() -> None:
text = "空腹血糖6.0 mmol/L"
reading = "6.0 mmol/L"
with metric_text_context([MetricTextState("FPG", reading, "high")]):
assert _color(_document(text), reading) == "#BD4B58"
with (
pytest.raises(RuntimeError),
metric_text_context([MetricTextState("空腹", reading, "normal")]),
):
assert _color(_document(text), reading) == "#287B65"
raise RuntimeError("restore scope")
assert _color(_document(text), reading) == "#BD4B58"
assert _color(_document(text), reading) == "#697386"
def test_context_snapshots_input_sequence() -> None:
states = [MetricTextState("空腹", "6.0 mmol/L", "high")]
with metric_text_context(states):
states.clear()
assert _color(_document("空腹6.0 mmol/L"), "6.0 mmol/L") == "#BD4B58"
@pytest.mark.parametrize("statuses", [("high", "normal"), ("unknown", "normal"), ("high", "")])
def test_conflicting_same_field_and_reading_states_stay_gray(statuses: tuple[str, str]) -> None:
with metric_text_context(
[
MetricTextState("FPG", "6.0 mmol/L", statuses[0]),
MetricTextState("空腹血糖", "6.0mmol/L", statuses[1]),
]
):
assert _color(_document("空腹血糖6.0 mmol/L正常"), "6.0 mmol/L") == "#697386"
def test_equivalent_abnormal_source_flags_do_not_conflict() -> None:
with metric_text_context(
[
MetricTextState("FPG", "6.0 mmol/L", "high"),
MetricTextState("空腹血糖", "6.0mmol/L", "warning"),
]
):
assert _color(_document("空腹血糖6.0 mmol/L"), "6.0 mmol/L") == "#BD4B58"
@pytest.mark.parametrize(
"text",
[
"餐后血糖6.0 mmol/L",
"血糖6.0 mmol/L",
"空腹血糖6.1 mmol/L",
"空腹血糖6.0 mg/dL",
"空腹血糖<6.0 mmol/L",
"空腹血糖6.0-7.0 mmol/L",
],
)
def test_matching_value_cannot_leak_between_fields_units_or_readings(text: str) -> None:
with metric_text_context([MetricTextState("FPG", "6.0 mmol/L", "normal")]):
assert "#287B65" not in metric_text_html(text)
def test_range_source_requires_whole_range_and_comparator() -> None:
reading = "≤ 4.4至7.0 mmol/L"
with metric_text_context([MetricTextState("空腹", reading, "warning")]):
assert _color(_document(f"空腹血糖{reading}"), reading) == "#BD4B58"
assert _color(_document("空腹血糖4.4 mmol/L"), "4.4 mmol/L") == "#697386"
def test_known_source_state_takes_precedence_over_ai_assertion() -> None:
with metric_text_context([MetricTextState("空腹血糖", "6.0 mmol/L", "high")]):
document = _document("空腹血糖6.0 mmol/L正常")
assert _color(document, "6.0 mmol/L") == "#BD4B58"
assert _color(document, "正常") == "#287B65"
@pytest.mark.parametrize("hint", ["", "空腹血糖", "空腹血糖目标"])
def test_targets_never_inherit_source_state_even_when_value_matches(hint: str) -> None:
with metric_text_context([MetricTextState("空腹血糖", "6.0 mmol/L", "high")]):
document = _document("目标空腹血糖6.0 mmol/L", metric_label=hint)
assert _color(document, "6.0 mmol/L") == "#697386"
document = _document("6.0 mmol/L(参考值)", metric_label=hint)
assert _color(document, "6.0 mmol/L") == "#697386"
def test_percent_reference_and_same_value_source_are_separated() -> None:
with metric_text_context([MetricTextState("HbA1c", "7.2%", "high")]):
document = _document("糖化血红蛋白7.2%,目标7.2%")
assert _color(document, "7.2%") == "#BD4B58"
cursor = document.find("目标7.2%")
cursor.setPosition(cursor.selectionEnd() - 2)
cursor.movePosition(
QTextCursor.MoveOperation.NextCharacter, QTextCursor.MoveMode.KeepAnchor
)
assert cursor.charFormat().foreground().color().name().upper() == "#697386"
def test_percent_body_uses_its_separate_label_without_coloring_unrelated_percentages() -> None:
with metric_text_context([MetricTextState("HbA1c", "7.2%", "high")]):
document = _document("7.2%,目标7.2%;完成率80%,风险下降20%", metric_label="HbA1c")
assert _color(document, "7.2%") == "#BD4B58"
assert _color(document, "80%") != "#697386"
assert _color(document, "20%") != "#697386"
@pytest.mark.parametrize("cue", ["正常范围", "target", "reference range"])
def test_reference_phrases_always_stay_gray(cue: str) -> None:
with metric_text_context([MetricTextState("HbA1c", "7.2%", "high")]):
document = _document(f"HbA1c {cue}: 7.2%")
assert _color(document, "7.2%") == "#697386"
@pytest.mark.parametrize(
"text,reading,color",
[
("血糖6.0 mmol/L未达标", "6.0 mmol/L", "#BD4B58"),
("血压140/90mmHg正常", "140/90mmHg", "#287B65"),
("血糖偏高:6.0 mmol/L", "6.0 mmol/L", "#BD4B58"),
("空腹6.0 mmol/L偏低", "6.0 mmol/L", "#BD4B58"),
("BMI26.1达标", "26.1", "#287B65"),
("FPG6.0mmol/L high", "6.0mmol/L", "#BD4B58"),
("血糖6.0 mmol/L可能偏高", "6.0 mmol/L", "#697386"),
("若血糖6.0 mmol/L未达标", "6.0 mmol/L", "#697386"),
("血糖6.0 mmol/L无明显升高", "6.0 mmol/L", "#697386"),
("血糖6.0 mmol/L血压正常", "6.0 mmol/L", "#697386"),
("血糖6.0 mmol/L血压140/90mmHg正常", "6.0 mmol/L", "#697386"),
],
)
def test_local_assertion_colors_only_its_nearby_reading(
text: str, reading: str, color: str
) -> None:
assert _color(_document(text), reading) == color
@pytest.mark.parametrize(
"missing", ["未记录", "未检测", "未知", "暂无数据", "unknown", "N/A", "—", "--", "/"]
)
def test_missing_values_are_gray(missing: str) -> None:
with metric_text_context([MetricTextState("空腹血糖", missing, "normal")]):
assert _color(_document(missing, metric_label="空腹血糖"), missing) == "#697386"
@pytest.mark.parametrize(
"label,color", [("高风险", "#BD4B58"), ("中风险", "#BD4B58"), ("低风险", "#287B65")]
)
def test_asserted_risk_levels_use_the_chart_palette(label: str, color: str) -> None:
assert _color(_document(f"风险评估:{label}"), label) == color
@pytest.mark.parametrize("text", ["可能高风险", "排除高风险", "中风险参考标准", "若为低风险"])
def test_conditional_risk_or_reference_is_not_an_asserted_state(text: str) -> None:
assert "#BD4B58" not in metric_text_html(text)
assert "#287B65" not in metric_text_html(text)
@@ -0,0 +1,413 @@
"""Recorded glucose charts inside the actual AI report and streaming lifecycle."""
from __future__ import annotations
import os
from copy import deepcopy
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, QPoint, QTimer
from PySide6.QtGui import QTextDocument
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QComboBox, QLabel
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseReportCard
REPORT = """以下依据已加载的血糖记录梳理变化情况,请结合原始测量时间与当前病历逐项核对。
1. 血糖记录与趋势
- 记录核对:请区分空腹和餐后记录,并结合实际测量日期阅读图表,缺失的记录不能作为零值。
- 资料说明:文字中提及的数值仅用于说明,图表只能采用健康档案中的实际测量记录。
2. 随访资料核对
- 本次复诊:请保留完整记录,核对服药时间、进食时间与居家测量方式,补充尚未填写的资料。
"""
CLINICAL_REPORT = """基于当前病历,患者有血糖波动的描述,需结合完整的测量记录与四诊信息进一步核对。
### 1. 可能证候分析
- 病史待核对:现有记录反映的变化需与实际测量条件相互核对,尚不足以确认具体证候。
### 2. 关键矛盾与不足
- 资料缺口:需区分空腹及餐后记录,核对测量日期,保留未记录的部分而不补写数值。
### 3. 建议下一步
- 核对原始记录:将历史血糖记录与用药、进食情况一起核对,由医生结合资料作进一步判断。
"""
def _tracking(diagnosis_id=501, patient_id=1501):
return {
"diagnosis_id": diagnosis_id,
"blood_records": [
{"diagnosis_id": diagnosis_id, "patient_id": patient_id,
"record_date": "2026-10-17", "record_time": "07:30",
"fasting_blood_sugar": 6.2, "postprandial_blood_sugar": 8.4},
{"diagnosis_id": diagnosis_id, "patient_id": patient_id,
"record_date": "2026-10-18", "record_time": "07:40",
"fasting_blood_sugar": 6.8, "postprandial_blood_sugar": None},
],
}
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
def _settle(application):
for _ in range(6):
application.processEvents()
QTest.qWait(5)
@pytest.fixture
def dialog(application, monkeypatch):
instance = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(instance, "_load_workspace", lambda _generation: None)
instance.open_for(diagnosis_id=501, patient_id=1501)
instance._workspace_sections = {"tracking": {"value": _tracking()}}
instance.resize(1280, 820)
instance.show()
_settle(application)
yield instance
for timer in instance.findChildren(QTimer):
timer.stop()
instance.close()
instance.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
@pytest.mark.parametrize("reply, panel_type", [
(REPORT, module._StructuredReportPanel),
(CLINICAL_REPORT, module._ClinicalAnalysisPanel),
])
def test_completed_report_formats_use_observed_measurements(dialog, reply, panel_type):
bubble = dialog._append_bubble("ai", reply)
before = deepcopy(dialog._workspace_sections)
dialog._finalize_ai_bubble(bubble)
panel = bubble.findChild(panel_type)
assert panel is not None
card = panel.findChild(GlucoseReportCard)
assert card is not None and card.chart is not None
assert card.chart.data.readout_count == 3
assert [row.fasting for row in card.chart.data.readings] == [6.2, 6.8]
assert [row.postprandial for row in card.chart.data.readings] == [8.4, None]
assert dialog._workspace_sections == before
# The chart is above the textual interpretation, not a separate chat reply.
assert panel.layout().itemAt(1).widget() is card
assert bubble.body is not None and bubble.body.isHidden()
assert bubble._raw_payload == reply
def test_stream_builds_chart_on_done_once_and_keeps_timing_and_snapshot(dialog, application):
bubble = dialog._append_bubble("ai", "")
dialog._stream_bubble = bubble
dialog._stream_prompt = "请评估该患者的血糖控制情况与趋势。"
generation, stream = dialog._generation, dialog._stream_generation
dialog._stream_event(generation, stream, {"event": "delta", "text": REPORT})
dialog._flush_stream_chunks()
assert bubble.findChild(GlucoseReportCard) is None
dialog._stream_event(generation, stream, {"event": "done", "model_label": "千问"})
_settle(application)
cards = bubble.findChildren(GlucoseReportCard)
assert len(cards) == 1 and cards[0].chart is not None
assert cards[0].chart.data.readout_count == 3
panel = bubble.findChild(module._StructuredReportPanel)
assert panel is not None
dialog._stream_finished(generation, stream, object())
assert "千问" in panel.meta_label.text()
assert len(bubble.findChildren(GlucoseReportCard)) == 1
dialog._workspace_sections["tracking"]["value"]["blood_records"][0]["fasting_blood_sugar"] = 22
assert cards[0].chart.data.readings[0].fasting == 6.2
assert dialog.send_button.isEnabled()
def test_archived_and_saved_reports_receive_the_same_chart(dialog):
dialog._render_messages([{"diagnosis_id": 501, "role": "ai", "content": REPORT}])
archived = dialog.findChildren(GlucoseReportCard)
assert len(archived) == 1 and archived[0].chart is not None
dialog._render_analysis({"diagnosis_advice": "血糖记录需与实际进食时间核对。"})
charts = [card.chart for card in dialog.findChildren(GlucoseReportCard)]
assert len(charts) == 2
assert all(chart is not None and chart.data.readout_count == 3 for chart in charts)
def test_no_measurements_keeps_full_report_without_fabricated_prose_values(dialog):
dialog._workspace_sections = {"tracking": {"value": None, "error": "记录不可用"}}
reply = REPORT + "\nAI 文本举例:空腹血糖 5.6 mmol/L,餐后 8.2 mmol/L。"
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
card = bubble.findChild(GlucoseReportCard)
assert card is None
assert bubble._raw_payload == reply
assert bubble.findChild(module._StructuredReportPanel) is not None
assert bubble.findChild(module.QFrame, "AiConsultReportVisual") is None
def test_plain_answer_gets_chart_but_irrelevant_answer_stays_text_only(dialog):
bubble = dialog._append_bubble("ai", "请核对原始血糖记录。")
dialog._finalize_ai_bubble(bubble)
assert bubble.findChild(GlucoseReportCard) is not None
assert bubble.body is not None and not bubble.body.isHidden()
unrelated = dialog._append_bubble("ai", "请携带既往处方核对具体药物名称。")
dialog._finalize_ai_bubble(unrelated)
assert unrelated.findChild(GlucoseReportCard) is None
def test_switching_patient_clears_chart_context_before_loading_and_ignores_old_stream(dialog):
old_generation, old_stream = dialog._generation, dialog._stream_generation
dialog.open_for(diagnosis_id=502, patient_id=1502)
assert dialog._workspace_sections == {}
assert dialog._detail == {}
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
card = bubble.findChild(GlucoseReportCard)
assert card is None
dialog._stream_bubble = bubble
dialog._stream_event(old_generation, old_stream, {"event": "done", "answer": REPORT})
assert bubble.findChild(GlucoseReportCard) is card
# A delayed response for the previous diagnosis cannot repopulate data.
dialog._workspace_loaded(old_generation, {"diagnosis_id": 501, "tracking": {"value": _tracking()}})
assert dialog._workspace_sections == {}
def test_changed_authoritative_patient_cannot_enable_old_chart_data(dialog):
dialog.patient_id = 1999
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
card = bubble.findChild(GlucoseReportCard)
assert card is None
@pytest.mark.parametrize("width", [1080, 1600])
def test_report_chart_and_end_of_report_remain_reachable(dialog, application, width):
dialog.resize(width, 820)
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
_settle(application)
card = bubble.findChild(GlucoseReportCard)
assert card is not None and card.chart is not None
assert card.chart.width() > 200 and card.chart.height() > 150
assert dialog.chat_scroll.horizontalScrollBar().maximum() == 0
assert card.chart.width() <= card.width()
assert bubble._clinical_panel is not None
final_label = bubble._clinical_panel.findChildren(QLabel, "AiConsultReportBody")[-1]
dialog.chat_scroll.verticalScrollBar().setValue(dialog.chat_scroll.verticalScrollBar().maximum())
_settle(application)
bottom = final_label.mapTo(dialog.chat_scroll.viewport(), QPoint(0, final_label.height() - 1))
assert dialog.chat_scroll.viewport().rect().contains(bottom)
def test_blood_pressure_answer_automatically_chooses_pressure_instead_of_glucose(dialog):
for index, row in enumerate(dialog._workspace_sections["tracking"]["value"]["blood_records"]):
row.update(systolic_pressure=142 - index * 4, diastolic_pressure=90 - index * 2)
reply = """以下根据本诊单实际录入的血压记录梳理近期变化,需结合原始测量时间核对。
1. 血压记录与变化
- 记录核对:当前已有连续日期的收缩压和舒张压记录,图表应按实际日期显示,保留原有测量单位。
2. 随访资料核对
- 测量条件:请核对测量时的休息状态、服药时间与设备,结合完整资料由医生进一步评估。
"""
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble, prompt="请分析血压变化。")
assert bubble.findChild(GlucoseReportCard) is None
cards = bubble.findChildren(module.QFrame, "AiConsultReportVisual")
assert cards and any(card.property("visualKind") == "blood_pressure" for card in cards)
assert all(card.data.kind == card.property("visualKind") for card in cards)
def test_numeric_ranges_and_status_are_colored_without_changing_report_text(dialog):
reply = """以下根据患者描述核对现有血糖记录,本段数字范围需要保留原文,不能自动改成精确测量点。
1. 当前控制水平:未达标
- 空腹血糖:记录为 6-7 mmol/L,需结合原始测量时间核对。
- 餐后血糖:记录为 8-9 mmol/L,当前资料尚需进一步核对。
2. 参考目标与复诊资料
- 目标说明:目标 <7.0 mmol/L 仅为报告中引用的参考内容,应与实际记录区分。
"""
dialog._workspace_sections = {}
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
assert bubble.findChild(GlucoseReportCard) is None
panel = bubble.findChild(module._StructuredReportPanel)
assert panel is not None
documents = []
for label in panel.findChildren(QLabel):
doc = QTextDocument()
doc.setHtml(label.text())
documents.append(doc)
for value in ("6-7 mmol/L", "8-9 mmol/L", "<7.0 mmol/L"):
document = next(doc for doc in documents if value in doc.toPlainText())
color = document.find(value).charFormat().foreground().color().name()
assert color not in {"#000000", "#1a1c1f"}
heading = next(doc for doc in documents if "当前控制水平" in doc.toPlainText())
assert heading.find("未达标").charFormat().foreground().color().name() == "#bd4b58"
assert bubble._raw_payload == reply
def test_refinalizing_answer_replaces_visuals_without_duplicate_cards(dialog, application):
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
assert len(bubble.findChildren(GlucoseReportCard)) == 1
dialog._finalize_ai_bubble(bubble)
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
assert len(bubble.findChildren(GlucoseReportCard)) == 1
dialog._workspace_sections = {}
dialog._finalize_ai_bubble(bubble)
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
assert bubble.findChild(GlucoseReportCard) is None
def test_short_answer_colors_values_without_replacing_markdown_or_original_payload(dialog):
reply = "**复核记录**:血压 142/90 mmHg,HbA1c 7.2%,请结合实际资料核对。"
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
assert bubble.body is not None
document = bubble.body.document()
assert document.find("142/90 mmHg").charFormat().foreground().color().name() == "#697386"
assert document.find("复核记录").charFormat().fontWeight() >= 600
assert bubble._raw_payload == reply
def test_clinical_evidence_keeps_ranges_and_does_not_shorten_approximate_readings():
evidence = module._clinical_evidence("患者空腹血糖 6-7 mmol/L,其他资料待补充。")
assert evidence[0].value == "6-7 mmol/L"
approximate = module._clinical_evidence("患者空腹血糖有时6点多,尚未携带原始记录。")
assert not any(item.label == "空腹血糖" for item in approximate)
def test_multitopic_reports_switch_charts_without_hiding_or_rebuilding_analysis(dialog, application):
dialog._workspace_sections["detail"] = {"value": {"diagnosis": {
"id": 501, "patient_id": 1501, "hba1c": 7.2, "hba1c_status": "high",
}, "patient": {"id": 1501, "weight": 68, "height": 168}}}
for index, row in enumerate(dialog._workspace_sections["tracking"]["value"]["blood_records"]):
row.update(systolic_pressure=142 - index * 4, diastolic_pressure=90 - index * 2)
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble, prompt="请综合分析血糖、血压和体重。")
_settle(application)
selector = bubble.findChild(QComboBox, "AiConsultReportVisualSelector")
assert selector is not None and selector.count() == 3
group = selector.parentWidget()
cards = [item.widget() for index in range(1, group.layout().count())
if (item := group.layout().itemAt(index)).widget() is not None]
assert len(cards) == 3
identities = [id(card) for card in cards]
for index in range(selector.count()):
selector.setCurrentIndex(index)
_settle(application)
assert not cards[index].isHidden()
assert all(card.isHidden() for position, card in enumerate(cards) if position != index)
assert [id(card) for card in cards] == identities
assert dialog.chat_scroll.horizontalScrollBar().maximum() == 0
assert bubble._raw_payload == REPORT
assert bubble.findChild(module._StructuredReportPanel) is not None
def _label_color(widget, reading, object_name=""):
documents = []
for label in widget.findChildren(QLabel, object_name):
document = QTextDocument()
document.setHtml(label.text())
if reading in document.toPlainText():
documents.append(document)
assert documents, f"No rendered label contains {reading!r}"
return {doc.find(reading).charFormat().foreground().color().name() for doc in documents}
def _colored_snapshot():
return {"detail": {"value": {"diagnosis": {
"id": 501, "patient_id": 1501,
"fasting_blood_sugar": "6-7", "fasting_blood_sugar_status": "high",
"postprandial_blood_sugar": "8-9", "postprandial_blood_sugar_status": "normal",
"hba1c": 7.2, "bmi": 26.1, "bmi_status": "high",
}, "patient": {"id": 1501}}}}
def test_streamed_snapshot_uses_same_colors_in_body_chart_and_raw_records(dialog):
dialog._workspace_sections = _colored_snapshot()
before = deepcopy(dialog._workspace_sections)
reply = """以下根据本诊单录入的指标核对资料,范围保留原文,由医生结合原始记录评估。
1. 本次指标记录
- 空腹血糖:记录为 6-7 mmol/L,保留原始范围。
- 餐后血糖:记录为 8-9 mmol/L,保留原始范围。
- 糖化血红蛋白:7.2%,记录未标注状态。
2. 补充资料
- 参考目标:空腹血糖目标 6-7 mmol/L,仅供核对报告中的参考内容。
"""
bubble = dialog._append_bubble("ai", "")
dialog._stream_bubble = bubble
dialog._stream_prompt = "综合分析血糖"
generation, stream = dialog._generation, dialog._stream_generation
dialog._stream_event(generation, stream, {"event": "delta", "text": reply})
dialog._stream_event(generation, stream, {"event": "done"})
panel = bubble.findChild(module._StructuredReportPanel)
assert panel is not None
assert _label_color(panel, "6-7 mmol/L", "AiConsultReportBody") == {"#bd4b58", "#697386"}
assert _label_color(panel, "8-9 mmol/L", "AiConsultReportBody") == {"#287b65"}
assert _label_color(panel, "7.2%", "AiConsultReportBody") == {"#697386"}
card = next(card for card in panel.findChildren(module.QFrame, "AiConsultReportVisual")
if card.data.kind == "metrics")
for label, color in [("空腹血糖", "#bd4b58"), ("餐后血糖", "#287b65"), ("糖化血红蛋白", "#697386")]:
index, item = next((i, item) for i, item in enumerate(card.data.items) if item.label == label)
assert item.color.lower() == color
assert card.table.item(index, 2).foreground().color().name() == color
assert bubble._raw_payload == reply
assert dialog._workspace_sections == before
def test_trend_states_also_color_short_markdown_and_combined_pressure(dialog):
rows = dialog._workspace_sections["tracking"]["value"]["blood_records"]
rows[0].update(fasting_blood_sugar_status="high", postprandial_blood_sugar_status="normal",
systolic_pressure=142, diastolic_pressure=90,
systolic_pressure_status="normal", diastolic_pressure_status="high")
reply = "**核对记录**:空腹血糖 6.2 mmol/L,餐后血糖 8.4 mmol/L,血压 142/90 mmHg。"
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
document = bubble.body.document()
for reading, color in [("6.2 mmol/L", "#bd4b58"), ("8.4 mmol/L", "#287b65"), ("142/90 mmHg", "#bd4b58")]:
assert document.find(reading).charFormat().foreground().color().name() == color
assert document.toPlainText() == "核对记录:空腹血糖 6.2 mmol/L,餐后血糖 8.4 mmol/L,血压 142/90 mmHg。"
assert document.find("核对记录").charFormat().fontWeight() >= 600
# Rendering a different record cannot inherit the previous report's source flags.
dialog._workspace_sections = {}
other = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(other)
assert other.body.document().find("6.2 mmol/L").charFormat().foreground().color().name() == "#697386"
assert document.find("6.2 mmol/L").charFormat().foreground().color().name() == "#bd4b58"
def test_saved_summary_and_key_facts_share_source_state_and_missing_palette(dialog):
dialog._workspace_sections = _colored_snapshot()
dialog._workspace_sections["detail"]["value"]["diagnosis"]["hba1c_status"] = "high"
dialog._apply_header(dialog._workspace_sections["detail"]["value"])
facts = dialog.findChildren(QLabel, "AiConsultKeyValue")
assert next(label for label in facts if label.text() == "26.1").styleSheet() == "color: #bd4b58;"
assert all(label.styleSheet() == "color: #697386;" for label in facts if label.text() == "未记录")
dialog._render_analysis({
"diagnosis_advice": "空腹血糖 6-7 mmol/L,餐后血糖 8-9 mmol/L。HbA1c 7.2%。",
"risk_assessment": [{"label": "随访风险", "level": "medium"}],
})
assert _label_color(dialog, "6-7 mmol/L", "AiConsultInsightText") == {"#bd4b58"}
assert _label_color(dialog, "8-9 mmol/L", "AiConsultInsightText") == {"#287b65"}
assert _label_color(dialog, "7.2%", "AiConsultInsightText") == {"#bd4b58"}
badge = next(label for label in dialog.findChildren(QLabel, "AiConsultTag") if label.text() == "中风险")
assert "#BD4B58" in badge.styleSheet()
@pytest.mark.parametrize("text", ["HbA1c 7.2%", "7.2 mmol/L 为原始记录", "指标:7.2%"])
def test_sidebar_does_not_split_decimal_measurements_into_list_markers(text):
segments = module._split_insight_segments(text)
assert len(segments) == 1
assert segments[0].kind != "list" and "7.2" in segments[0].text
def test_numbered_sidebar_summary_preserves_decimals_and_actual_list_structure():
segments = module._split_insight_segments("建议:1. 复核 HbA1c 7.2% 2. 核对空腹血糖 6.8 mmol/L")
numbered = [item for item in segments if item.kind == "list"]
assert [(item.marker, item.text) for item in numbered] == [
("1.", "复核 HbA1c 7.2%"), ("2.", "核对空腹血糖 6.8 mmol/L"),
]
+571
View File
@@ -0,0 +1,571 @@
from __future__ import annotations
import os
from copy import deepcopy
from dataclasses import FrozenInstanceError, replace
from datetime import datetime
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QPointF, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel, QToolTip
from doctor_workstation.core.models import Prescription
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseChartData, GlucoseReportCard
from doctor_workstation.ui.dialogs.ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
UNKNOWN_COLOR,
)
from doctor_workstation.ui.dialogs.ai_consult_report_visuals import (
ReportVisualCard,
build_report_visuals,
create_report_visual,
)
@pytest.fixture(scope="module")
def application() -> QApplication:
return QApplication.instance() or QApplication([])
def _row(day: str = "2026-08-18", **changes: Any) -> dict[str, Any]:
return {
"diagnosis_id": 501,
"patient_id": 1501,
"record_date": day,
"fasting_blood_sugar": 6.8,
"systolic_pressure": 146,
"diastolic_pressure": 92,
**changes,
}
def _sections(*rows: Any, **diagnosis: Any) -> dict[str, Any]:
return {
"detail": {"value": {"diagnosis": {"id": 501, "patient_id": 1501, **diagnosis}}},
"tracking": {
"value": {"diagnosis_id": 501, "patient_id": 1501, "blood_records": list(rows)}
},
}
def _build(sections: dict[str, Any], prompt: str = "分析血压", reply: str = ""):
return build_report_visuals(prompt, reply, sections=sections, diagnosis_id=501, patient_id=1501)
def _kind(data: Any) -> str:
return "glucose" if isinstance(data, GlucoseChartData) else data.kind
def test_selects_actual_topics_in_prompt_or_reply_without_unrelated_charts() -> None:
sections = _sections(_row(), weight=60, hba1c=7.2)
assert [_kind(item) for item in _build(sections)] == ["blood_pressure"]
assert [_kind(item) for item in _build(sections, "", "检查空腹血糖")] == ["glucose", "metrics"]
assert _build(sections, "解释睡眠质量") == ()
assert [_kind(item) for item in _build(sections, "综合分析")] == [
"glucose",
"blood_pressure",
"metrics",
]
@pytest.mark.parametrize(
"topic", ["血糖", "血压", "血脂", "体重", "肾功能", "风险", "用药", "运动", "综合分析"]
)
def test_no_actual_data_never_produces_chart_shell(topic: str) -> None:
assert _build({}, topic, "目标血压 120/80,HbA1c 6.5%,每日运动30分钟") == ()
assert _build(_sections(), topic) == ()
def test_ai_prose_goals_and_approximate_numbers_never_become_observations() -> None:
sections = _sections(
_row(systolic_pressure="约146", diastolic_pressure="90-95", fasting_blood_sugar="~6.8")
)
assert _build(sections, "分析血压和血糖", "今天146/92,目标120/80,血糖7.0") == ()
@pytest.mark.parametrize("owner", [None, True, "501", 501.0, 0, 502])
def test_tracking_root_and_rows_need_exact_diagnosis_owner(owner: Any) -> None:
root = _sections(_row())
root["tracking"]["value"]["diagnosis_id"] = owner
assert _build(root) == ()
rows = _sections(_row(diagnosis_id=owner), _row("2026-08-19"))
visual = _build(rows)[0]
assert len(visual.items) == 2
assert all(item.recorded_at.day == 19 for item in visual.items)
@pytest.mark.parametrize("owner", [None, True, "1501", 1501.0, 0, 1502])
def test_declared_patient_owner_is_checked_at_tracking_root_and_row(owner: Any) -> None:
root = _sections(_row())
root["tracking"]["value"]["patient_id"] = owner
assert _build(root) == ()
assert _build(_sections(_row(patient_id=owner))) == ()
@pytest.mark.parametrize("owner", [None, True, "501", 501.0, 502])
def test_mismatched_detail_disables_linked_visuals(owner: Any) -> None:
sections = _sections(_row(), id=owner, hba1c=7.2)
assert _build(sections, "综合分析") == ()
def test_detail_patient_conflicts_and_section_errors_fail_closed() -> None:
assert _build(_sections(_row(), patient_id=1502)) == ()
sections = _sections(_row(), weight=60)
sections["detail"]["value"]["patient"] = {"id": 1502}
assert _build(sections, "综合分析") == ()
sections = _sections(_row())
sections["tracking"]["error"] = "接口失败"
assert _build(sections) == ()
def test_dto_snapshot_is_immutable_and_keeps_dates_gaps_and_duplicate_rows() -> None:
sections = _sections(
_row("2026-08-21", systolic_pressure=150),
_row("2026-08-18", systolic_pressure=140),
_row("2026-08-18", systolic_pressure=141),
_row("2026-08-19", systolic_pressure=None, diastolic_pressure=None),
)
before = deepcopy(sections)
data = _build(sections)[0]
assert sections == before
assert [item.value for item in data.items if item.series == "systolic_pressure"] == [
140,
141,
None,
150,
]
assert data.items[0].recorded_at == datetime(2026, 8, 18)
with pytest.raises(FrozenInstanceError):
data.items[0].value = 100 # type: ignore[misc]
sections["tracking"]["value"]["blood_records"][1]["systolic_pressure"] = 999
assert data.items[0].value == 140
@pytest.mark.parametrize(
"value", [True, "约 130", "120-140", "<140", float("nan"), float("inf"), 0, -1]
)
def test_ambiguous_pressure_readings_are_not_plotted(value: Any) -> None:
assert _build(_sections(_row(systolic_pressure=value, diastolic_pressure=None))) == ()
def test_no_dated_pressure_is_replaced_by_a_snapshot_only_when_detail_is_real() -> None:
sections = _sections(_row("不是日期"), systolic_pressure=130, diastolic_pressure=80)
data = _build(sections)[0]
assert data.kind == "metrics"
assert [item.value for item in data.items] == [130, 80]
assert all(item.recorded_at is None and item.reference is None for item in data.items)
def test_status_colors_come_only_from_source_and_units_are_separate() -> None:
data = _build(
_sections(
hba1c=12.5,
hba1c_status="normal",
cholesterol=5.2,
cholesterol_status="high",
microalbumin=12,
microalbumin_status="low",
weight=100,
bmi=35,
),
"综合分析",
)[0]
assert data.kind == "metrics"
metrics = {item.label: item for item in data.items}
assert metrics["糖化血红蛋白"].color == NORMAL_COLOR
assert metrics["总胆固醇"].color == ABNORMAL_COLOR
assert metrics["尿微量白蛋白"].color == ABNORMAL_COLOR
assert metrics["体重"].color == metrics["BMI"].color == UNKNOWN_COLOR
assert [
(metrics[key].unit) for key in ("糖化血红蛋白", "总胆固醇", "尿微量白蛋白", "体重", "BMI")
] == ["%", "mmol/L", "mg/L", "kg", "kg/m²"]
assert all(item.reference is None for item in data.items)
assert metrics["BMI"].value == 35
def test_source_units_override_defaults_without_conversion_or_shared_scale() -> None:
data = _build(
_sections(creatinine="1.1 mg/dL", creatinine_unit="mg/dL", weight="60 kg"), "肾功能与体重"
)[0]
assert [(item.value, item.unit) for item in data.items] == [(1.1, "mg/dL"), (60, "kg")]
assert all(item.reference is None for item in data.items)
def test_recorded_interval_is_distinct_from_exact_points_and_has_no_invented_date() -> None:
data = _build(
_sections(fasting_blood_sugar="6-7", postprandial_blood_sugar="8~9 mmol/L"), "血糖"
)[0]
assert data.kind == "metrics"
assert [item.interval for item in data.items] == [(6, 7), (8, 9)]
assert all(
item.value is None and item.recorded_at is None and item.reference is None
for item in data.items
)
assert data.items[1].value_text == "8~9 mmol/L"
def test_owned_patient_body_measurements_are_used_when_not_repeated_in_diagnosis() -> None:
sections = _sections()
sections["detail"]["value"]["patient"] = {"id": 1501, "weight": 68, "height": 168}
data = _build(sections, "体重与BMI")[0]
assert [(item.label, item.value, item.unit) for item in data.items] == [
("体重", 68, "kg"), ("身高", 168, "cm"),
]
assert all(item.color == UNKNOWN_COLOR and not item.status for item in data.items)
assert not any(item.label == "BMI" for item in data.items)
def test_metric_snapshot_uses_two_columns_on_wide_reports_and_localizes_status(application):
data = _build(_sections(hba1c=7.2, hba1c_status="high", weight=68, bmi=24), "综合分析")[0]
card = create_report_visual(data)
card.resize(760, card.sizeHint().height())
card.show()
application.processEvents()
wide_height = card.chart.height()
assert card.chart._columns == 2
assert "偏高" in card.chart.accessibleDescription()
assert card.table.item(0, 3).text() == "偏高"
assert "体重" in card.chart._point_tooltip(QPointF(card.chart.width() / 2 + 20, 10))
card.resize(320, card.height())
application.processEvents()
assert card.chart._columns == 1
assert card.chart.height() > wide_height
card.close()
card.deleteLater()
def test_reference_scale_requires_actual_stored_limits_and_keeps_zero() -> None:
data = _build(
_sections(
microalbumin=18,
microalbumin_reference_range={"low": 0, "high": 30, "unit": "mg/L"},
hba1c=7.2,
hba1c_reference_range="4-6 %",
weight=60,
),
"综合分析",
)[0]
assert [item.reference for item in data.items] == [(4, 6), (0, 30), None]
incompatible = _build(
_sections(
creatinine=100, creatinine_reference_range={"low": 0, "high": 2, "unit": "mg/dL"}
),
"肾功能",
)[0]
assert incompatible.items[0].reference is None
def test_foreign_nested_lab_values_are_not_adopted() -> None:
sections = _sections()
sections["detail"]["value"]["labs"] = {"diagnosis_id": 502, "hba1c": 7.2}
assert _build(sections, "糖化血红蛋白") == ()
@pytest.mark.parametrize(
("status", "color"),
[("high", ABNORMAL_COLOR), ("low", ABNORMAL_COLOR), ("warning", ABNORMAL_COLOR),
("异常", ABNORMAL_COLOR), ("normal", NORMAL_COLOR), ("正常", NORMAL_COLOR),
("unknown", UNKNOWN_COLOR), ("unclassified", UNKNOWN_COLOR), (None, UNKNOWN_COLOR),
(True, UNKNOWN_COLOR), ({"normal": True}, UNKNOWN_COLOR)],
)
def test_snapshot_flags_use_the_shared_palette_without_thresholds(status, color) -> None:
data = _build(_sections(hba1c=40, hba1c_status=status), "糖化血红蛋白")[0]
assert data.items[0].value == 40
assert data.items[0].color == color
assert "蓝色" not in data.source and "橙" not in data.source
assert "灰色未记录/未标注" in data.source
def test_pressure_points_raw_cells_and_tooltips_keep_only_recorded_states(application) -> None:
data = _build(_sections(
_row("2026-08-18", systolic_pressure=200, systolic_pressure_status="normal",
diastolic_pressure=60, diastolic_status="low"),
_row("2026-08-19", systolic_pressure=220, diastolic_pressure=None,
diastolic_pressure_status="normal"),
_row("2026-08-20", systolic_pressure=210, systolic_status="warning",
diastolic_pressure=70, diastolic_pressure_status="unknown"),
))[0]
assert [(item.status, item.color) for item in data.items] == [
("normal", NORMAL_COLOR), ("low", ABNORMAL_COLOR),
("", UNKNOWN_COLOR), ("normal", UNKNOWN_COLOR),
("warning", ABNORMAL_COLOR), ("unknown", UNKNOWN_COLOR),
]
card = create_report_visual(data)
card.resize(650, card.sizeHint().height())
card.show()
application.processEvents()
image = card.chart.grab().toImage()
for index, item in enumerate(data.items):
for column in (2, 3):
cell = card.table.item(index, column)
assert cell.foreground().color().name() == item.color.casefold()
assert "状态" in cell.toolTip()
if item.status:
assert item.status in cell.toolTip()
if item.value is not None:
point = card.chart._position(item)
assert image.pixelColor(point.toPoint()).name() == item.color.casefold()
assert item.status in card.chart._point_tooltip(point)
assert card.table.item(3, 2).text() == "—"
assert card.table.item(3, 3).text() == "未记录"
assert "舒张压 · — · 状态 未记录" in card.chart.accessibleDescription()
assert "收缩压实线圆点,舒张压虚线方点" in card.chart.accessibleDescription()
card.close()
def test_pressure_statuses_cannot_be_borrowed_from_root_or_foreign_rows() -> None:
sections = _sections(
_row(systolic_pressure=200, diastolic_pressure=110),
_row("2026-08-19", diagnosis_id=502, systolic_pressure_status="normal"),
)
sections["tracking"]["value"]["systolic_pressure_status"] = "normal"
items = _build(sections)[0].items
assert len(items) == 2
assert all(item.status == "" and item.color == UNKNOWN_COLOR for item in items)
def test_pressure_connection_is_gray_between_explicit_abnormal_points(application) -> None:
data = _build(_sections(
_row("2026-08-18", systolic_pressure=140, systolic_pressure_status="high",
diastolic_pressure=None),
_row("2026-08-20", systolic_pressure=140, systolic_pressure_status="high",
diastolic_pressure=None),
))[0]
card = create_report_visual(data)
card.resize(640, card.sizeHint().height())
card.show()
application.processEvents()
points = [card.chart._position(item) for item in data.items if item.value is not None]
midpoint = (points[0] + points[1]) / 2
image = card.chart.grab().toImage()
assert image.pixelColor(midpoint.toPoint()).name() == UNKNOWN_COLOR.casefold()
assert image.pixelColor(points[0].toPoint()).name() == ABNORMAL_COLOR.casefold()
card.close()
def test_reference_band_is_neutral_and_never_assigns_normal_status(application) -> None:
data = _build(_sections(hba1c=5, hba1c_reference_range="4-6 %"), "糖化血红蛋白")[0]
assert data.items[0].color == UNKNOWN_COLOR and data.items[0].status == ""
card = create_report_visual(data)
card.resize(400, card.sizeHint().height())
card.show()
application.processEvents()
image = card.chart.grab().toImage()
assert image.pixelColor(20, 54).name() == UNKNOWN_COLOR.casefold()
assert card.table.item(0, 2).foreground().color().name() == UNKNOWN_COLOR.casefold()
assert card.table.item(0, 3).text() == "未标注"
assert "状态 未标注" in card.table.item(0, 2).toolTip()
card.close()
def test_risks_are_exact_categorical_annotations_not_numeric_scores() -> None:
sections = _sections()
sections["analysis"] = {
"value": {
"patient_id": 1501,
"source_diagnosis_ids": [499, 501],
"risk_assessment": [
{"label": level, "level": level, "score": 99, "probability": 0.9}
for level in ("high", "medium", "low", "unknown")
]
+ [{"label": "未核验", "level": "severe"}, {"label": "无等级", "level": None}],
}
}
data = _build(sections, "风险评估")[0]
assert data.kind == "risks"
assert [item.status for item in data.items] == ["high", "medium", "low", "unknown"]
assert [item.color for item in data.items] == [
ABNORMAL_COLOR, ABNORMAL_COLOR, NORMAL_COLOR, UNKNOWN_COLOR,
]
assert all(
item.value is None and item.reference is None and "%" not in item.raw_value
for item in data.items
)
assert "定性风险标注" in data.source and "#499、#501" in data.source
@pytest.mark.parametrize(
"metadata",
[
{},
{"patient_id": 1502, "source_diagnosis_ids": [501]},
{"patient_id": 1501, "source_diagnosis_ids": [502]},
{"diagnosis_id": "501"},
{"diagnosis_id": 502},
],
)
def test_unowned_and_foreign_risk_reports_do_not_get_visuals(metadata: Any) -> None:
sections = _sections()
sections["analysis"] = {
"value": {**metadata, "risk_assessment": [{"label": "风险项", "level": "high"}]}
}
assert _build(sections, "风险") == ()
def test_nested_saved_report_uses_its_original_owner_and_levels() -> None:
sections = _sections()
sections["analysis"] = {
"value": {
"latest_by_model": {
"qwen": {
"patient_id": 1501,
"source_diagnosis_ids": [499, 501],
"diagnosis_id": 499,
"report": {"risk_assessment": [{"label": "血糖波动", "level": "medium"}]},
}
}
}
}
assert _build(sections, "风险")[0].items[0].status == "medium"
sections["analysis"]["value"]["latest_by_model"]["qwen"]["report"]["patient_id"] = 1502
assert _build(sections, "风险") == ()
def test_prescription_timeline_accepts_dto_and_preserves_dates_name_status() -> None:
sections = _sections()
sections["prescriptions"] = {
"value": [
Prescription(
diagnosis_id=501,
prescription_date="2026-08-19",
herbs=[{"name": "黄芪"}],
audit_status=1,
),
{
"diagnosis_id": 501,
"patient_id": 1501,
"prescription_date": "2026-08-18",
"prescription_name": "益气方",
"status_text": "已审核",
},
{
"diagnosis_id": 502,
"prescription_date": "2026-08-17",
"prescription_name": "外国诊单",
"status_text": "已审核",
},
{"diagnosis_id": 501, "prescription_name": "没有日期", "status_text": "已审核"},
]
}
data = _build(sections, "用药合理性")[0]
assert data.kind == "medications"
assert [(item.time_label, item.label, item.status) for item in data.items] == [
("2026-08-18", "益气方", "已审核"),
("2026-08-19", "黄芪", "已通过"),
]
assert all(item.value is None for item in data.items)
def test_dto_coercion_does_not_hide_invalid_raw_prescription_ownership() -> None:
sections = _sections()
sections["prescriptions"] = {
"value": [
Prescription.from_dict(
{
"diagnosis_id": "501",
"prescription_date": "2026-08-18",
"prescription_name": "益气方",
"status_text": "已审核",
}
)
]
}
assert _build(sections, "用药") == ()
def test_unitless_bmi_state_remains_a_measurement_instead_of_a_risk_label(application) -> None:
data = _build(_sections(bmi=26.1, bmi_status="high"), "体重")[0]
data = replace(data, items=tuple(replace(item, unit="") for item in data.items))
card = ReportVisualCard(data)
try:
assert card.table.item(0, 3).text() == "偏高"
assert card.table.item(0, 3).foreground().color().name() == "#bd4b58"
finally:
card.deleteLater()
def test_exercise_uses_actual_duration_minutes_with_no_target_bars() -> None:
sections = _sections()
sections["tracking"]["value"]["exercise_records"] = [
_row("2026-08-18", duration=35),
_row("2026-08-19", duration="约40"),
_row("2026-08-20", duration=40, patient_id=1502),
]
data = _build(sections, "建议运动150分钟")[0]
assert data.kind == "exercise"
assert [item.value for item in data.items] == [35, None]
assert data.items[0].unit == "分钟"
def test_charts_render_at_320px_with_exact_hover_and_raw_data(application: QApplication) -> None:
sections = _sections(
_row("2026-08-18"), _row("2026-08-19"), _row("2026-08-21"), hba1c=7.2, hba1c_status="high"
)
sections["analysis"] = {
"value": {
"diagnosis_id": 501,
"risk_assessment": [{"label": "血压波动风险", "level": "medium"}],
}
}
sections["prescriptions"] = {
"value": [
{
"diagnosis_id": 501,
"prescription_date": "2026-08-19",
"prescription_name": "益气方",
"status_text": "已审核",
}
]
}
sections["tracking"]["value"]["exercise_records"] = [_row(duration=35)]
data = _build(sections, "综合分析")
assert {_kind(item) for item in data} == {
"glucose",
"blood_pressure",
"metrics",
"risks",
"medications",
"exercise",
}
for item in data:
card = create_report_visual(item)
card.resize(320, card.sizeHint().height())
card.show()
application.processEvents()
try:
assert card.width() == 320
assert card.minimumSizeHint().width() <= 320
assert not card.grab().isNull()
assert not any("暂无可绘制" in label.text() for label in card.findChildren(QLabel))
if isinstance(card, GlucoseReportCard):
continue
assert isinstance(card, ReportVisualCard)
assert (
card.objectName() == "AiConsultReportVisual"
and card.property("visualKind") == item.kind
)
QTest.mouseClick(card.toggle_button, Qt.MouseButton.LeftButton)
application.processEvents()
assert card.table.isVisible() and card.table.rowCount() == len(item.items)
assert card.table.item(0, 1).text() == item.items[0].label
position = card.chart._position(item.items[0]) if card.chart._trend else QPointF(20, 10)
assert item.items[0].label in card.chart._point_tooltip(position)
if item.kind == "blood_pressure":
first, middle, last = [
datum for datum in item.items if datum.series == "systolic_pressure"
]
positions = [card.chart._position(datum).x() for datum in (first, middle, last)]
assert (positions[1] - positions[0]) / (
positions[2] - positions[0]
) == pytest.approx(1 / 3)
QTest.mouseMove(card.chart, position.toPoint())
application.processEvents()
assert "146 mmHg" in QToolTip.text()
finally:
card.close()
card.deleteLater()
+5 -7
View File
@@ -1413,7 +1413,7 @@ def test_ask_sends_only_question_and_relies_on_server_full_context(
if widget.objectName() == "AiConsultBubbleText"
]
assert any("请结合资料分析当前证候" in text for text in all_bubble_texts)
assert any("服务端将按当前诊单实时附带患者全部纵向资料" in text for text in all_bubble_texts)
assert not any("服务端将按当前诊单实时附带患者全部纵向资料" in text for text in all_bubble_texts)
dialog.close()
@@ -1443,11 +1443,11 @@ def _silent_dialog(monkeypatch: pytest.MonkeyPatch) -> AiConsultDialog:
return dialog
def test_full_context_notice_is_shown_once_per_conversation(
def test_full_context_notice_is_not_displayed_in_conversations(
application: QApplication,
monkeypatch: pytest.MonkeyPatch,
) -> None:
# 每轮问答都重复同一句全量上下文说明会把真正的回答挤出可视区。
# 技术性的上下文说明不应占用对话区,包括首次提问和切换患者后。
dialog = _silent_dialog(monkeypatch)
dialog.show()
application.processEvents()
@@ -1458,13 +1458,12 @@ def test_full_context_notice_is_shown_once_per_conversation(
dialog._cancel_stream()
dialog._ask(question)
counts.append(sum(1 for text in _bubble_texts(dialog) if notice in text))
assert counts == [1, 1, 1]
assert counts == [0, 0, 0]
# 换患者视为新会话,需要重新提示一次。
dialog.open_for(diagnosis_id=502, patient_id=302)
application.processEvents()
dialog._ask("新患者的问题")
assert sum(1 for text in _bubble_texts(dialog) if notice in text) == 1
assert sum(1 for text in _bubble_texts(dialog) if notice in text) == 0
dialog.close()
@@ -1710,7 +1709,6 @@ def test_http_stream_paints_before_upstream_finishes_on_the_ui_thread(
)
dialog = AiConsultDialog(RemoteDoctorRepository(client))
dialog.diagnosis_id = 501
dialog._context_notice_shown = True
delivered_on = []
original_event = dialog._stream_event
+2
View File
@@ -11,6 +11,7 @@ from typing import Any
import httpx
import pytest
from doctor_workstation import __version__
from doctor_workstation.core.errors import (
ApiBusinessError,
ApiError,
@@ -47,6 +48,7 @@ def test_get_normalises_adminapi_and_sends_contract_headers() -> None:
)
assert request.headers["token"] == "secret-token"
assert request.headers["version"] == "1.9.4"
assert request.headers["user-agent"] == f"ZytDoctorWorkstation/{__version__}"
assert ApiClient.normalise_base_url("https://example.test/adminapi") == (
"https://example.test/adminapi/"
)
+206
View File
@@ -0,0 +1,206 @@
"""Archived IM events must be readable in the diagnosis drawer and AI history."""
from __future__ import annotations
import json
import os
from copy import deepcopy
from datetime import datetime
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, Qt
from PySide6.QtWidgets import QApplication, QFrame, QLabel, QPushButton
from doctor_workstation.ui.chat_items import format_chat_time, parse_chat_item
from doctor_workstation.ui.diagnosis_drawer import ChatPanel, _RemoteImageButton
STAMP = 1792454400
def _event(payload, **changes):
return {
"msg_type": "custom",
"content": json.dumps(payload, ensure_ascii=False),
"create_time": STAMP,
**changes,
}
def _rtc(command, *, seconds=None, call_type=2, encoded=True):
body = {
"version": 4,
"call_type": call_type,
"businessID": "rtc_call",
"data": {"cmd": command, "inviter": "doctor_synthetic"},
}
if seconds is not None:
body["call_end"] = seconds
return {
"businessID": 1,
"data": json.dumps(body) if encoded else body,
"actionType": 1,
"inviteID": "synthetic-private-invite",
}
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def panel(application):
widget = ChatPanel()
widget.resize(1100, 850)
widget.show()
yield widget
widget.close()
widget.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
@pytest.mark.parametrize(
"business,title",
[
("patient_opened_chat", "患者进入在线问诊"),
("patient_left_chat", "患者离开在线问诊"),
("doctor_entered_consult_room", "医生进入在线诊室"),
("consultation_complete", "本次问诊已完成"),
],
)
def test_drawer_recognizes_custom_events_in_content_and_formats_archive_time(
panel, business, title
):
row = _event(
{"businessID": business, "patientName": "示例患者", "patientId": "synthetic-private-id"}
)
before = deepcopy(row)
panel.set_messages([row])
assert panel.findChild(QLabel, "DiagnosisChatEventTitle").text() == title
assert panel.findChild(QLabel, "DiagnosisChatMeta").text() == datetime.fromtimestamp(
STAMP
).strftime("%Y-%m-%d %H:%M")
assert not panel.findChildren(QFrame, "DiagnosisChatBubble")
visible_text = " ".join(label.text() for label in panel.findChildren(QLabel))
assert "businessID" not in visible_text and "synthetic-private-id" not in visible_text
assert row == before
@pytest.mark.parametrize("encoded", [False, True])
@pytest.mark.parametrize(
"command,seconds,title,detail",
[
("videoCall", None, "发起视频问诊", "医生已向患者发起视频通话"),
("hangup", "116", "视频问诊已结束", "通话 1 分 56 秒"),
("hangup", "154", "视频问诊已结束", "通话 2 分 34 秒"),
],
)
def test_nested_rtc_signals_prefer_the_command_and_show_duration(
panel, encoded, command, seconds, title, detail
):
panel.set_messages([_event(_rtc(command, seconds=seconds, encoded=encoded))])
assert panel.findChild(QLabel, "DiagnosisChatEventTitle").text() == title
assert panel.findChild(QLabel, "DiagnosisChatEventDetail").text() == detail
visible_text = " ".join(label.text() for label in panel.findChildren(QLabel))
assert all(
token not in visible_text
for token in ("rtc_call", "inviteID", "call_end", "synthetic-private-invite")
)
@pytest.mark.parametrize("value", [STAMP, str(STAMP), STAMP * 1000, str(STAMP * 1000)])
def test_seconds_and_milliseconds_have_the_same_display_time(value):
expected = datetime.fromtimestamp(STAMP)
assert format_chat_time(value) == expected.strftime("%H:%M")
assert format_chat_time(value, include_date=True) == expected.strftime("%Y-%m-%d %H:%M")
def test_iso_and_payload_only_times_are_formatted_for_both_views():
assert format_chat_time("2026-10-20T08:30:45Z") == "08:30"
assert format_chat_time("2026-10-20T08:30:45Z", include_date=True) == "2026-10-20 08:30"
row = _event({"businessID": "patient_opened_chat", "time": STAMP * 1000}, create_time=None)
assert parse_chat_item(row, include_date=True).time_text == datetime.fromtimestamp(
STAMP
).strftime("%Y-%m-%d %H:%M")
assert parse_chat_item(
{"text": "普通消息", "timestamp": STAMP}
).time_text == datetime.fromtimestamp(STAMP).strftime("%H:%M")
@pytest.mark.parametrize("value", [None, "", 0, -1, float("nan"), float("inf"), True])
def test_missing_or_invalid_numeric_times_do_not_render_as_epoch_or_raw_numbers(value):
assert format_chat_time(value, include_date=True) == ""
def test_only_typing_signals_show_the_empty_state(panel, application):
panel.set_messages([_event({"businessID": "user_typing_status", "typing": True})])
application.processEvents()
assert panel.empty.isVisible()
assert not panel.findChildren(QFrame, "DiagnosisChatBubble")
assert not panel.findChildren(QFrame, "DiagnosisChatEvent")
def test_unknown_technical_payload_uses_readable_fallback_without_internal_ids(panel):
panel.set_messages([_event({"business_id": "new_private_signal", "inviteID": "private-token"})])
assert panel.findChild(QLabel, "DiagnosisChatEventTitle").text() == "系统状态已同步"
assert "private-token" not in " ".join(label.text() for label in panel.findChildren(QLabel))
def test_ordinary_chat_keeps_exact_multiline_content_and_sender_side(panel):
text = " 我已确认以下信息:\n1、本人确认已在线下确诊;\n2、本人已阅读告知书。\n<b>保留原文</b> "
panel.set_messages(
[
{"content": text, "is_from_doctor": "0", "time": STAMP},
{"text": "请补充资料", "from_account": "doctor_synthetic", "time": STAMP},
]
)
bubbles = panel.findChildren(QFrame, "DiagnosisChatBubble")
assert [bubble.property("side") for bubble in bubbles] == ["patient", "doctor"]
body = bubbles[0].findChild(QLabel, "DiagnosisChatText")
assert body.text() == text and body.textFormat() == Qt.TextFormat.PlainText
def test_mixed_events_and_attachments_preserve_image_preview_and_file_actions(panel, monkeypatch):
monkeypatch.setattr(_RemoteImageButton, "load_url", lambda *_args, **_kwargs: None)
image_url = "https://example.invalid/synthetic.jpg"
file_url = "https://example.invalid/synthetic.pdf"
opened = []
panel.open_attachment_requested.connect(opened.append)
panel.set_messages(
[
_event({"businessID": "doctor_entered_consult_room"}),
{"msg_type": "image", "image_url": image_url, "time": STAMP},
{"msg_type": "file", "file_url": file_url, "file_name": "示例报告.pdf", "time": STAMP},
]
)
panel.findChild(_RemoteImageButton, "DiagnosisChatImage").click()
next(
button for button in panel.findChildren(QPushButton) if button.text() == "示例报告.pdf"
).click()
assert opened == [image_url, file_url]
assert len(panel.findChildren(QFrame, "DiagnosisChatEvent")) == 1
def test_nested_duration_and_audio_command_are_not_misclassified():
ended = parse_chat_item(
_event(
{"businessID": "rtc_call", "call_type": 1, "data": {"cmd": "hangup", "call_end": 61}}
)
)
assert ended.title == "语音问诊已结束" and ended.detail == "通话 1 分 1 秒"
started = parse_chat_item(_event({"businessID": "rtc_call", "data": {"cmd": "audioCall"}}))
assert started.title == "发起语音问诊"
def test_text_field_has_the_same_priority_in_both_chat_views():
item = parse_chat_item({"text": "本条正文", "content": "旧字段"})
assert item.text == "本条正文"
def test_invalid_json_is_preserved_without_interrupting_other_messages(panel):
broken = '{"unfinished":'
panel.set_messages([{"content": broken}, _event({"businessID": "patient_opened_chat"})])
assert panel.findChild(QLabel, "DiagnosisChatText").text() == broken
assert panel.findChild(QLabel, "DiagnosisChatEventTitle").text() == "患者进入在线问诊"
+26
View File
@@ -619,6 +619,32 @@ def _select_tab(dialog: DiagnosisDialog, key: str) -> None:
QApplication.processEvents()
def test_chat_tab_recognizes_archived_system_events_in_the_actual_drawer(application: QApplication) -> None:
class ChatRepository(VisualRepository):
def list_im_chat_messages(self, diagnosis_id: int, *, only_archived: bool = True) -> dict[str, Any]:
assert diagnosis_id == 501 and only_archived
return {"lists": [
{"content": '{"businessID":"patient_opened_chat","patientName":"示例患者"}',
"create_time": 1792454400},
{"text": "我已确认问诊信息。", "create_time": 1792454401},
{"text": '{"businessID":"doctor_entered_consult_room"}',
"create_time": 1792454402},
]}
dialog = _open_dialog(application, (1440, 900), mode="edit", repository=ChatRepository())
try:
_select_tab(dialog, "chat")
panel = dialog._chat_panels[1]
assert panel.isVisibleTo(dialog)
assert [label.text() for label in panel.findChildren(QLabel, "DiagnosisChatEventTitle")] == [
"患者进入在线问诊", "医生进入在线诊室",
]
assert panel.findChild(QLabel, "DiagnosisChatText").text() == "我已确认问诊信息。"
assert all("17924544" not in label.text() for label in panel.findChildren(QLabel, "DiagnosisChatMeta"))
finally:
dialog.close()
@pytest.mark.parametrize("size", [(1024, 640), (1440, 900)])
def test_readonly_is_an_independent_vertical_page_flow(
application: QApplication,
+28 -1
View File
@@ -794,6 +794,33 @@ def test_revoked_agreement_cache_discards_flat_comparison_metadata() -> None:
assert value["models"]["qwen"]["reason"] == sentinel
@pytest.mark.parametrize("flag", [False, None, 1, "true"])
def test_unlisted_account_hides_ai_analysis_column_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 page.table.isColumnHidden(11) and page.table.isColumnHidden(12)
# Later status refreshes must not re-expose the analysis column.
page._set_ai_columns(True)
assert page.table.isColumnHidden(11) and page.table.isColumnHidden(12)
assert 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()
def test_list_capability_failure_revocation_and_late_status_cannot_restore_scores(
application: QApplication, immediate: None, monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -810,7 +837,7 @@ def test_list_capability_failure_revocation_and_late_status_cannot_restore_score
page._load_ai_capabilities()
page._ai_statuses_ready(old_statuses, [801, 802], old_token, page._generation)
page._ai_capabilities_ready({"agreement_visible": True}, old_capability_token, page._generation)
assert page.table.isColumnHidden(12) and not page.table.isColumnHidden(11)
assert page.table.isColumnHidden(12) and page.table.isColumnHidden(11)
assert page.ai_statistics_button.isHidden()
assert page.ai_report_button.isVisible()
assert page._ai_statuses
@@ -11,7 +11,7 @@ from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import Qt, QTimer
from PySide6.QtCore import QPoint, Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QPushButton
@@ -234,3 +234,60 @@ def test_row_action_permissions_and_foreign_public_management_are_preserved(
assert buttons["删除处方模板"].isEnabled() == can_edit_foreign
else:
assert page.edit_button.isHidden() and page.delete_button.isHidden()
def test_table_fills_viewport_after_window_and_scrollbar_changes(page_factory, application):
page, repository = page_factory()
table = page.table
page.resize(1024, 768)
settle(application)
minimums = [table.columnWidth(column) for column in range(table.columnCount())]
source = deepcopy(repository.rows[0])
for width, count in ((2048, 2), (2048, 70), (1024, 70), (1920, 0),
(1920, 2), (1366, 2), (2048, 2)):
page.resize(width, 768)
table.set_rows([{**deepcopy(source), "id": 10000 + index} for index in range(count)])
settle(application)
viewport = table.viewport()
if count:
assert table.fontMetrics().horizontalAdvance(table.item(0, 0).text()) + 24 <= table.columnWidth(0)
assert table.horizontalHeader().length() == max(sum(minimums), viewport.width())
assert all(table.columnWidth(column) >= minimum for column, minimum in enumerate(minimums))
if viewport.width() >= sum(minimums):
assert table.horizontalScrollBar().maximum() == 0
assert all(table.columnWidth(column) > minimums[column] for column in (1, 4, 5))
if count:
last_cell = table.visualItemRect(table.item(0, 9))
index = table.indexAt(QPoint(viewport.width() - 3, last_cell.center().y()))
assert (index.row(), index.column()) == (0, 9)
else:
assert table.horizontalScrollBar().maximum() > 0
table.horizontalScrollBar().setValue(table.horizontalScrollBar().maximum())
settle(application)
assert table.visualItemRect(table.item(0, 9)).right() < viewport.width()
def test_manual_column_width_survives_resize_and_refresh(page_factory, application):
page, _repository = page_factory()
table = page.table
page.resize(2048, 900)
settle(application)
table.sortItems(0, Qt.SortOrder.DescendingOrder)
table.selectRow(1)
selected_id = record_id(table.current_data())
action_host = table.cellWidget(1, 9)
requested_width = table.columnWidth(1) + 60
table.setColumnWidth(1, requested_width)
settle(application)
for width in (1024, 1920, 1366, 2048):
page.resize(width, 900)
settle(application)
assert table.columnWidth(1) == requested_width
assert record_id(table.current_data()) == selected_id
assert table.cellWidget(1, 9) is action_host
page.refresh()
settle(application)
assert table.columnWidth(1) == requested_width
assert record_id(table.current_data()) == selected_id
assert table.horizontalHeader().sortIndicatorOrder() == Qt.SortOrder.DescendingOrder
assert table.horizontalHeader().length() == table.viewport().width()
+1 -1
View File
@@ -55,7 +55,7 @@ def test_typography_preserves_regular_body_and_distinct_values(page):
body = page.case_labels["present"]
assert body.font().pixelSize() == 14
assert body.font().weight() == 400
assert page.patient_name_label.font().pixelSize() == 22
assert page.patient_name_label.font().pixelSize() == 20
assert page.patient_name_label.font().weight() == 600
assert page.vital_labels["height"].font().pixelSize() == 18
+8 -8
View File
@@ -261,15 +261,15 @@ def test_approved_shell_geometry_and_function_entries_restore(
assert window.centralWidget().layout().contentsMargins().isNull()
assert window.search_host.mapTo(window, QPoint()) == QPoint(234, 15)
assert window.search_host.size() == QSize(384, 44)
assert window.assistant_card.mapTo(window, QPoint()) == QPoint(20, 695)
assert window.assistant_card.size() == QSize(168, 171)
assert window.assistant_button.height() == 46
assert window.brand_name.font().pixelSize() == 18
assert window.brand_subtitle.font().pixelSize() == 13
assert window.assistant_card.mapTo(window, QPoint()) == QPoint(20, 776)
assert window.assistant_card.size() == QSize(168, 132)
assert window.assistant_button.height() == 36
assert window.brand_name.font().pixelSize() == 16
assert window.brand_subtitle.font().pixelSize() == 12
for index, button in enumerate(window.nav_buttons.values()):
assert button.mapTo(window, QPoint()).y() == 99 + 58 * index
assert button.height() == 52
assert button.font().pixelSize() == 15
assert button.mapTo(window, QPoint()).y() == 99 + 48 * index
assert button.height() == 44
assert button.font().pixelSize() == 14
assert button.iconSize() == QSize(20, 20)
assert not window.fold_button.isVisible()
assert not window.ai_top_button.isVisible()
+25 -19
View File
@@ -21,6 +21,7 @@ from PySide6.QtCore import (
QTimer,
)
from PySide6.QtGui import QPalette
from PySide6.QtTest import QTest
from PySide6.QtWidgets import (
QApplication,
QLabel,
@@ -378,7 +379,8 @@ def test_queue_condition_summary_never_exposes_raw_dict(
)
fallback_summary = fallback.findChild(QLabel, "ReceptionQueueSubline")
assert fallback_summary is not None
assert fallback_summary.text() == "暂无病情摘要"
assert fallback_summary.text() == ""
assert fallback_summary.toolTip() == ""
assert "{" not in fallback_summary.text()
row.close()
@@ -1045,14 +1047,17 @@ def test_medication_case_prioritizes_clinical_information_and_keeps_plain_summar
detail["patient"],
diagnosis,
)
application.processEvents()
for _ in range(12):
application.processEvents()
QTest.qWait(5)
assert page.diagnosis_card.objectName() == "ReceptionMedicationCaseCard"
assert page.diagnosis_card.accessibleName() == "完整病例"
assert page.medication_scroll.objectName() == "ReceptionMedicationScroll"
assert page.medication_scroll.accessibleName() == "用药记录与完整病例滚动区域"
assert page.medication_scroll.horizontalScrollBar().maximum() == 0
assert page.medication_scroll.verticalScrollBar().maximum() > 0
case_scrolls = (page.clinical_scroll, page.medication_scroll)
assert any(scroll.verticalScrollBar().maximum() > 0 for scroll in case_scrolls)
assert page.diagnosis_text.isHidden()
assert page.diagnosis_text.textFormat() == Qt.TextFormat.PlainText
@@ -1095,14 +1100,16 @@ def test_medication_case_prioritizes_clinical_information_and_keeps_plain_summar
assert value.textInteractionFlags() & Qt.TextInteractionFlag.TextSelectableByMouse
for _ in range(5):
page.medication_scroll.verticalScrollBar().setValue(
page.medication_scroll.verticalScrollBar().maximum()
)
for scroll in case_scrolls:
scroll.verticalScrollBar().setValue(scroll.verticalScrollBar().maximum())
application.processEvents()
assert (
page.medication_scroll.verticalScrollBar().value()
== page.medication_scroll.verticalScrollBar().maximum()
)
assert all(scroll.verticalScrollBar().value() == scroll.verticalScrollBar().maximum()
for scroll in case_scrolls)
final_note = page.case_section_frames["notes"].findChild(QLabel, "ReceptionCaseFieldValue")
assert final_note is not None
assert "【完整病例末尾】" in final_note.text()
viewport = page.clinical_scroll.viewport()
assert viewport.rect().contains(final_note.mapTo(viewport, final_note.rect().bottomLeft()))
page.close()
application.processEvents()
@@ -1446,12 +1453,14 @@ def test_phone_permission_and_ungated_notify_video_actions(
masked_page = ReceptionPage(Repository(), PermissionSet([]))
masked_page._select_record(detail["appointment"])
assert masked_page.patient_labels["phone"].text() == "138****8000"
assert masked_page.patient_summary_labels["phone"].text() == "138****8000"
assert not masked_page.notify_button.isHidden()
assert not masked_page.video_button.isHidden()
plain_page = ReceptionPage(Repository(), PermissionSet(["tcm.diagnosis/phonePlain"]))
plain_page._select_record(detail["appointment"])
assert plain_page.patient_labels["phone"].text() == "13800138000"
assert plain_page.patient_summary_labels["phone"].text() == "13800138000"
assert plain_page.appointment_labels["doctor"].text() == "张医生"
assert plain_page.appointment_labels["assistant"].text() == "李医助"
assert plain_page.patient_labels["region"].text() == "浙江省杭州市"
@@ -1524,8 +1533,8 @@ def test_notify_assistant_is_a_visible_header_action_not_a_more_menu_item(
for button in buttons:
assert hero.rect().contains(button.geometry())
assert button.width() >= button.sizeHint().width()
right = button.mapTo(page.detail_scroll.viewport(), QPoint(button.width(), 0)).x()
assert right <= page.detail_scroll.viewport().width()
right = button.mapTo(page.detail_stack, QPoint(button.width(), 0)).x()
assert right <= page.detail_stack.width()
for previous, following in zip(buttons, buttons[1:], strict=False):
assert previous.geometry().right() < following.geometry().left()
finally:
@@ -1700,10 +1709,7 @@ def test_reception_auto_loads_structured_ai_analysis_and_matches_reference_geome
assert [label.property("riskLevel") for label in chips] == ["high", "medium", "low"]
assert "千问" in page.ai_analysis_title.toolTip()
assert [button.text() for button in page.ai_prompt_buttons] == [
"基于当前病史,下一步检查建议?",
"该患者的用药调整建议?",
"糖尿病教育要点有哪些?",
"并发症筛查建议?",
"检查建议", "用药核对", "健康教育", "并发症筛查",
]
assert page.ai_send_button.text() == ""
assert page.ai_send_button.accessibleName() == "发送 AI 问诊问题"
@@ -1734,9 +1740,9 @@ def test_reception_auto_loads_structured_ai_analysis_and_matches_reference_geome
assert page.ai_analysis_card.minimumHeight() == 0
assert page.ai_analysis_card.maximumHeight() > 520
assert page.ai_analysis_card.findChildren(QScrollArea) == []
assert left.height() == right.height()
assert right.left() - left.right() - 1 == 10
assert abs(left.width() / (left.width() + right.width()) - 0.425) < 0.01
assert left.left() == right.left()
assert left.width() == right.width()
assert right.top() - left.bottom() - 1 == 10
assert page.ai_summary_label.width() <= page.ai_analysis_card.contentsRect().width()
assert page.ai_summary_label.minimumSizeHint().width() <= 48
@@ -0,0 +1,324 @@
"""Reachability and data preservation in the real reception shell."""
from __future__ import annotations
import os
import socket
from copy import deepcopy
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, QPoint, QRect, Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QFrame, QLabel, QPushButton
from doctor_workstation.ui import shell as shell_module
from doctor_workstation.ui.pages import reception as reception_module
from doctor_workstation.ui.pages.reception import QueueRow, ReceptionPage
from doctor_workstation.ui.shell import NavigationItem, ShellWindow
from doctor_workstation.ui.theme import apply_theme
def _settle(application: QApplication) -> None:
for _ in range(12):
application.processEvents()
QTest.qWait(5)
def _mapped_rect(widget, ancestor) -> QRect:
return QRect(widget.mapTo(ancestor, QPoint()), widget.size())
class _LocalRepository:
def __init__(self) -> None:
self.calls: list[str] = []
self.detail = {
"appointment": {
"id": 51, "patient_id": 151, "diagnosis_id": 251,
"patient_name": "本地测试患者", "status": 1,
"doctor_name": "测试医生", "assistant_name": "测试医助",
"appointment_time": "09:30", "appointment_type": "video",
},
"patient": {
"id": 151, "name": "本地测试患者", "gender": 2,
"age": 46, "height": 165, "weight": 60, "phone": "13800138000",
},
"diagnosis": {
"id": 251, "patient_id": 151, "chief_complaint": "反复口渴",
"present_illness": "近期口干,复诊时核对记录。",
"current_medications": "二甲双胍早晚服用,剂量待核对。",
"disease_course_text": "患病十年",
"clinical_diagnosis": "2 型糖尿病", "hba1c": 7.2,
},
}
def list_appointments(self, **_query: Any) -> dict[str, Any]:
self.calls.append("queue")
return {"lists": [deepcopy(self.detail["appointment"])], "count": 1}
def get_reception(self, appointment_id: int) -> dict[str, Any]:
assert appointment_id == 51
self.calls.append("detail")
return deepcopy(self.detail)
def get_diagnosis_ai_analysis(self, diagnosis_id: int, model: str) -> dict[str, Any]:
assert diagnosis_id == 251
self.calls.append(model)
return {
"diagnosis_advice": "结合当前病史复核血糖控制情况。",
"risk_assessment": [{"label": "血糖波动", "level": "medium"}],
"treatment_advice": "核对现有用药及近期检查。", "model_key": model,
}
@pytest.fixture(scope="module")
def application() -> QApplication:
app = QApplication.instance() or QApplication([])
apply_theme(app)
return app
@pytest.fixture
def shell_factory(application: QApplication, monkeypatch: pytest.MonkeyPatch):
def reject_network(*_args, **_kwargs):
pytest.fail("Reception workspace tests must remain local")
def immediate(function, *args, on_success=None, on_error=None, on_finished=None,
pool=None, priority=0, **kwargs):
del pool, priority
try:
result = function(*args, **kwargs)
except Exception as error:
if on_error:
on_error(error)
raise
else:
if on_success:
on_success(result)
finally:
if on_finished:
on_finished()
return object()
monkeypatch.setattr(socket.socket, "connect", reject_network)
monkeypatch.setattr(socket.socket, "connect_ex", reject_network)
monkeypatch.setattr(socket, "create_connection", reject_network)
monkeypatch.setattr(reception_module, "run_async", immediate)
monkeypatch.setattr(shell_module.motion, "reduced_motion", lambda: True)
item = NavigationItem("reception", "接诊台", "", ReceptionPage,
("doctor.appointment/lists",))
monkeypatch.setattr(shell_module, "_resolve_navigation",
lambda *_args, **_kwargs: [(item, item.title)])
opened = []
def create(width=1920, height=1080):
repository = _LocalRepository()
shell = ShellWindow(repository, {"user": {"id": 7, "name": "测试医生"}},
permissions={
"doctor.appointment/lists", "doctor.appointment/complete",
"doctor.appointment/addDoctorNote", "tcm.diagnosis/edit",
"tcm.diagnosis/aiAnalysis", "tcm.diagnosis/aiAssistant",
})
opened.append(shell)
shell.resize(width, height)
shell.show()
_settle(application)
page = shell.pages["reception"]
page.poll_timer.stop()
shell.chat_notifications.stop()
assert page._selected_appointment_id == 51
assert page.detail_stack.currentIndex() == 1
return shell, page, repository
yield create
for shell in opened:
for timer in shell.findChildren(QTimer):
timer.stop()
shell.close()
shell.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
@pytest.mark.parametrize("size", [(1366, 768), (1920, 1080)])
def test_real_shell_prioritizes_patient_facts_while_long_history_scrolls(
application, shell_factory, size,
):
shell, page, repository = shell_factory(*size)
assert (shell.width(), shell.height()) == size
assert not page.workbench.mode_tabs.isVisible()
hero = page.findChild(QFrame, "ReceptionHero")
hero_before = _mapped_rect(hero, page)
actions = (page.notify_button, page.history_button, page.video_button,
page.more_button, page.complete_button)
actions_before = [_mapped_rect(button, page) for button in actions]
for button in actions:
assert button.isVisibleTo(page)
assert hero.rect().contains(_mapped_rect(button, hero))
assert button.width() >= button.minimumSizeHint().width()
insights_viewport = page.insights_scroll.viewport()
summary = page.patient_summary_card
vitals = page.findChild(QFrame, "ReceptionVitalsCard")
labs = page.findChild(QFrame, "ReceptionLabsCard")
assert insights_viewport.rect().contains(_mapped_rect(summary, insights_viewport))
assert insights_viewport.rect().contains(_mapped_rect(vitals, insights_viewport))
assert _mapped_rect(summary, insights_viewport).top() == 0
assert summary.mapTo(page, QPoint()).y() < vitals.mapTo(page, QPoint()).y()
assert vitals.mapTo(page, QPoint()).y() < labs.mapTo(page, QPoint()).y()
assert labs.mapTo(page, QPoint()).y() < page.ai_analysis_card.mapTo(page, QPoint()).y()
assert {key: label.text() for key, label in page.patient_summary_labels.items()} == {
"gender_age": "女 · 46岁", "phone": "138****8000",
"course": "患病十年", "diagnosis": "2 型糖尿病",
}
assistant_title = page.ai_assistant_card.findChild(QPushButton, "ReceptionAiTitle")
insight_scroll_value = page.insights_scroll.verticalScrollBar().value()
fact_positions = [_mapped_rect(card, page) for card in (summary, vitals, labs)]
requests = list(repository.calls)
history = "完整病史:口干持续,携带记录复诊,核对既往用药。\n" * 40
page.case_labels["present"].setText(history)
_settle(application)
assert page.case_labels["present"].text() == history
assert page.case_labels["present"].height() >= page.case_labels["present"].heightForWidth(
page.case_labels["present"].width()
)
scrollbar = page.clinical_scroll.verticalScrollBar()
assert scrollbar.maximum() > 0
scrollbar.setValue(scrollbar.maximum())
_settle(application)
assert scrollbar.value() == scrollbar.maximum()
assert _mapped_rect(hero, page) == hero_before
assert [_mapped_rect(button, page) for button in actions] == actions_before
assert [_mapped_rect(card, page) for card in (summary, vitals, labs)] == fact_positions
assert page.insights_scroll.verticalScrollBar().value() == insight_scroll_value
for title in (page.ai_analysis_title, assistant_title):
page.insights_scroll.ensureWidgetVisible(title)
_settle(application)
assert insights_viewport.rect().contains(_mapped_rect(title, insights_viewport))
assert repository.calls == requests
def test_narrow_workspace_reuses_scrolls_and_preserves_drafts_tabs_and_patient(
application, shell_factory,
):
shell, page, repository = shell_factory()
clinical, insights = page.clinical_scroll, page.insights_scroll
page.detail_tabs.setCurrentIndex(4)
page.note_edit.setPlainText("未保存的本地备注")
page._pending_tongue_images = ["draft-tongue.png"]
page._pending_report_files = ["draft-report.pdf"]
requests = list(repository.calls)
for width in (1024, 1920, 1024, 1366):
shell.resize(width, 768)
_settle(application)
assert page.clinical_scroll is clinical
assert page.insights_scroll is insights
assert page.detail_tabs.currentIndex() == page.clinical_pages.currentIndex() == 4
assert page._selected_appointment_id == 51
assert page.note_edit.toPlainText() == "未保存的本地备注"
assert page._pending_tongue_images == ["draft-tongue.png"]
assert page._pending_report_files == ["draft-report.pdf"]
if width == 1024:
assert page.workbench.mode_tabs.isVisible()
for index, scroll in ((1, insights), (0, clinical)):
page.workbench.mode_tabs.setCurrentIndex(index)
_settle(application)
assert scroll.isVisibleTo(page)
assert page.workbench._narrow_stack.currentWidget() is scroll
else:
assert not page.workbench.mode_tabs.isVisible()
assert clinical.isVisibleTo(page) and insights.isVisibleTo(page)
assert repository.calls == requests
def test_missing_labs_expand_and_collapse_without_losing_recorded_values(
application, shell_factory,
):
_shell, page, _repository = shell_factory()
before = {key: label.text() for key, label in page.lab_labels.items()}
assert before["hba1c"] == "7.2 %"
assert not page.lab_cells["hba1c"].isHidden()
assert all(cell.isHidden() for key, cell in page.lab_cells.items() if key != "hba1c")
assert page.lab_missing_button.text() == "显示 7 项未记录"
page.insights_scroll.ensureWidgetVisible(page.lab_missing_button)
_settle(application)
QTest.mouseClick(page.lab_missing_button, Qt.MouseButton.LeftButton)
_settle(application)
assert all(not cell.isHidden() for cell in page.lab_cells.values())
assert page.lab_missing_button.text() == "收起未记录项"
page.lab_missing_button.click()
_settle(application)
assert {key: label.text() for key, label in page.lab_labels.items()} == before
assert all(cell.isHidden() for key, cell in page.lab_cells.items() if key != "hba1c")
def test_free_text_glucose_keeps_source_without_invented_units_or_status(
application, shell_factory,
):
_shell, page, repository = shell_factory()
description = "近期空腹7至9之间,餐后约12,尚未携带原始记录"
diagnosis = {**repository.detail["diagnosis"], "fasting_blood_sugar": description}
page._render_case(repository.detail["appointment"], repository.detail["patient"], diagnosis)
_settle(application)
assert page.lab_labels["fasting"].text() == description
assert page.lab_labels["fasting"].textFormat() == Qt.TextFormat.PlainText
assert page.lab_cells["fasting"].property("description") is True
assert not page.lab_cells["fasting"].isHidden()
assert page.lab_state_labels["fasting"].isHidden()
assert page.case_metric_labels["fasting_glucose"].text() == description
assert f"空腹血糖:{description}\n" in page.diagnosis_text.text()
assert f"{description} mmol/L" not in page.health_summary_label.text()
row = QueueRow({**repository.detail["appointment"], "diagnosis": diagnosis})
try:
metric = row.findChild(QLabel, "ReceptionQueueMetric")
assert metric.text() == "血糖有描述"
assert metric.toolTip() == description
assert metric.property("tone") == "description"
assert row.glucose_drop.isHidden()
finally:
row.deleteLater()
def test_compact_ai_prompts_keep_full_questions_and_callbacks(shell_factory, monkeypatch):
_shell, page, _repository = shell_factory()
sent = []
monkeypatch.setattr(page, "_open_ai_report_for_prompt", sent.append)
questions = [
"基于当前病史,下一步检查建议?", "该患者的用药调整建议?",
"糖尿病教育要点有哪些?", "并发症筛查建议?",
]
labels = ["检查建议", "用药核对", "健康教育", "并发症筛查"]
assert len(page.ai_prompt_buttons) == len(questions)
for button, label, question in zip(page.ai_prompt_buttons, labels, questions, strict=True):
assert button.text() == label
assert button.toolTip() == button.accessibleName() == question
assert button.isEnabled()
button.click()
assert sent == questions
def test_patient_facts_stay_first_while_ai_is_loading_or_unavailable(application, shell_factory):
_shell, page, repository = shell_factory()
before = {key: label.text() for key, label in page.patient_summary_labels.items()}
requests = list(repository.calls)
for state in ("loading", "error", "permission"):
page._set_ai_analysis_state(state)
_settle(application)
assert {key: label.text() for key, label in page.patient_summary_labels.items()} == before
assert page.patient_summary_card.mapTo(page.insights_scroll.widget(), QPoint()).y() == 0
assert repository.calls == requests
def test_patient_change_returns_to_facts_and_clears_previous_summary(application, shell_factory, monkeypatch):
_shell, page, _repository = shell_factory()
page.insights_scroll.verticalScrollBar().setValue(page.insights_scroll.verticalScrollBar().maximum())
monkeypatch.setattr(page, "_load_detail", lambda record, **_kwargs: page._reset_detail_content(record))
page._select_record({"id": 52, "patient_name": "另一位患者"})
_settle(application)
assert page.insights_scroll.verticalScrollBar().value() == 0
assert all(label.text() == "正在加载…" for label in page.patient_summary_labels.values())
page._render_detail_load_failure("详情暂不可用")
assert all(label.text() == "未记录" for label in page.patient_summary_labels.values())
assert all(label.property("missing") is True for label in page.patient_summary_labels.values())
+85 -4
View File
@@ -2,10 +2,12 @@ from __future__ import annotations
import os
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import QApplication, QDialog, QMainWindow
from PySide6.QtCore import QPoint, QRect, Qt, QTimer
from PySide6.QtWidgets import QApplication, QDialog, QMainWindow, QWidget
from doctor_workstation.core import PermissionSet
from doctor_workstation.services import DemoDoctorRepository
@@ -92,7 +94,7 @@ def test_modal_exec_uses_main_window_geometry() -> None:
main.close()
def test_owner_synchronized_business_drawers_use_main_window_85_percent() -> None:
def test_business_windows_and_standalone_readonly_keep_main_window_85_percent() -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)
main = QMainWindow()
@@ -104,7 +106,6 @@ def test_owner_synchronized_business_drawers_use_main_window_85_percent() -> Non
dialogs = [
AppointmentDrawer({"id": 501, "diagnosis_id": 501}, repository, main, autoload=False),
DiagnosisDialog(repository, main),
OrderDetailDrawer(main),
PrescriptionEditorDialog(repository, parent=main),
]
try:
@@ -121,6 +122,86 @@ def test_owner_synchronized_business_drawers_use_main_window_85_percent() -> Non
main.close()
def _client_geometry(widget):
return QRect(widget.mapToGlobal(QPoint(0, 0)), widget.size())
def _settle(app):
for _ in range(4):
app.processEvents()
@pytest.mark.parametrize("view_only", [False, True])
def test_diagnosis_drawer_scrim_covers_the_entire_workstation_client_area(view_only) -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)
main = QMainWindow()
main.setProperty("doctorMainWindow", True)
main.setGeometry(30, 50, 1400, 900)
page = QWidget(main)
main.setCentralWidget(page)
main.show()
_settle(app)
dialog = DiagnosisDialog(object(), page, permissions=PermissionSet(["tcm.diagnosis/edit"]))
try:
dialog.open_for(501, editable=not view_only, view_only=view_only,
authoritative_detail={"diagnosis": {"id": 501, "patient_id": 1501}})
_settle(app)
def assert_full_coverage():
assert _client_geometry(dialog) == _client_geometry(main)
assert dialog.drawer_overlay.rect() == dialog.rect()
assert dialog.drawer_panel.width() == round(main.width() * 0.60)
assert dialog.drawer_panel.mapTo(dialog, QPoint(0, 0)).x() + dialog.drawer_panel.width() == dialog.width()
assert dialog.drawer_panel.height() == dialog.height()
image = dialog.grab().toImage()
shade = image.pixelColor(2, 2)
assert shade.alpha() > 0
assert image.pixelColor(2, image.height() - 3) == shade
assert_full_coverage()
main.setGeometry(70, 80, 1200, 780)
_settle(app)
assert_full_coverage()
main.showMaximized()
_settle(app)
assert_full_coverage()
main.showNormal()
_settle(app)
assert_full_coverage()
finally:
dialog.close()
main.close()
@pytest.mark.parametrize("standalone_readonly", [False, True])
def test_order_scrim_covers_its_diagnosis_owner_while_main_window_is_visible(standalone_readonly) -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)
main = QMainWindow()
main.setProperty("doctorMainWindow", True)
main.setGeometry(30, 50, 1400, 900)
main.show()
_settle(app)
owner = DiagnosisDialog(object(), main, permissions=PermissionSet(["tcm.diagnosis/edit"]))
owner.open_for(501, editable=not standalone_readonly,
authoritative_detail={"diagnosis": {"id": 501, "patient_id": 1501}})
drawer = OrderDetailDrawer(owner)
try:
drawer.show()
_settle(app)
assert _client_geometry(drawer) == _client_geometry(owner)
assert drawer.drawer_panel.width() == round(owner.width() * 0.8)
assert drawer.scrim.height() == owner.height()
main.setGeometry(70, 80, 1280, 820)
_settle(app)
assert _client_geometry(drawer) == _client_geometry(owner)
finally:
drawer.close()
owner.close()
main.close()
def test_maximized_workstation_opens_patient_picker_at_85_percent() -> None:
app = QApplication.instance() or QApplication([])
_install_business_dialog_styling(app)