Files
zyt/app/src/doctor_workstation/ui/chat_notifications.py
T
2026-10-29 16:14:55 +08:00

435 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""登录后常驻的聊天通知:患者打开会话、离开会话、面诊结束。
与后台 ``admin/src/components/chat-notify-toast`` 同一套合同:轮询
``chat/notifications``(服务端取一次即消费),把结果堆成右上角卡片,点击卡片进入
对应工作面,关闭按钮单独移除。桌面端额外做了一件网页做不到的事——新通知到达时让
任务栏闪一下,医生切到别的窗口也能看见。
"""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime
from typing import Any
from PySide6.QtCore import QEvent, QObject, Qt, QTimer, Signal
from PySide6.QtWidgets import (
QApplication,
QFrame,
QHBoxLayout,
QLabel,
QPushButton,
QVBoxLayout,
QWidget,
)
from .design_system import clinical_stylesheet
from .widgets import display_text, first_value, run_async
# 后台 ChatNotifyLogic 写入的三种 type。
PATIENT_OPENED_CHAT = "patient_opened_chat"
PATIENT_LEFT_CHAT = "patient_left_chat"
CONSULTATION_COMPLETE = "consultation_complete"
_TITLES: dict[str, str] = {
PATIENT_OPENED_CHAT: "患者打开会话",
PATIENT_LEFT_CHAT: "患者离开会话",
CONSULTATION_COMPLETE: "面诊结束",
}
_MAX_CARDS = 5
_POLL_INTERVAL_MS = 5_000
CHAT_NOTIFICATION_QSS = """
QFrame#ChatNotifyCard {
background-color: #FFFFFF;
border: 1px solid #BBF0CE;
border-radius: 12px;
}
QFrame#ChatNotifyCard[kind="left"] { border-color: #E4E4E5; }
QFrame#ChatNotifyCard[kind="complete"] { border-color: #8B9AD9; }
QLabel#ChatNotifyBadge {
min-width: 34px;
max-width: 34px;
min-height: 34px;
max-height: 34px;
color: #FFFFFF;
background-color: #287B65;
border-radius: 9px;
font-size: 15px;
font-weight: 700;
}
QLabel#ChatNotifyBadge[kind="left"] { background-color: #6A6B6D; }
QLabel#ChatNotifyBadge[kind="complete"] { background-color: #4F63D9; }
QLabel#ChatNotifyTitle { color: #1A1C1F; font-size: 13px; font-weight: 700; }
QLabel#ChatNotifyDesc { color: #1A1C1F; font-size: 12px; }
QLabel#ChatNotifyTime { color: #6A6B6D; font-size: 11px; }
QPushButton#ChatNotifyOpen {
min-height: 26px;
padding: 0 10px;
color: #4F63D9;
background-color: #EEF1FA;
border: 1px solid #EDEDEE;
border-radius: 7px;
font-size: 12px;
font-weight: 600;
}
QPushButton#ChatNotifyOpen:hover {
color: #4156C4;
background-color: #EEF1FA;
border-color: #8B9AD9;
}
QPushButton#ChatNotifyClose {
min-width: 22px;
max-width: 22px;
min-height: 22px;
max-height: 22px;
color: #6A6B6D;
background-color: transparent;
border: 0;
border-radius: 6px;
font-size: 14px;
}
QPushButton#ChatNotifyClose:hover { color: #1A1C1F; background-color: #F7F7F7; }
"""
@dataclass(frozen=True)
class ChatNotification:
"""One queued notification, normalised from the admin payload."""
id: str
kind: str
patient_name: str
patient_id: str
doctor_name: str
diagnosis_id: int
created_at: int
@property
def title(self) -> str:
return _TITLES.get(self.kind, "系统通知")
@property
def description(self) -> str:
patient = self.patient_name or "患者"
if self.kind == CONSULTATION_COMPLETE:
doctor = self.doctor_name or "医生"
return f"{patient} 的面诊已由 {doctor} 完成,请及时跟进"
if self.kind == PATIENT_LEFT_CHAT:
return f"{patient} 已离开问诊会话页面"
return f"{patient} 已打开与您的会话,请及时查看"
@property
def action_text(self) -> str:
if self.kind == CONSULTATION_COMPLETE:
return "查看诊单"
if self.kind == PATIENT_OPENED_CHAT:
return "去接诊台"
return ""
def parse_notification(row: Any) -> ChatNotification | None:
"""Normalise one server row; unknown or id-less rows are dropped."""
if not isinstance(row, Mapping):
return None
identifier = str(first_value(row, "id", default="") or "").strip()
kind = str(first_value(row, "type", default=PATIENT_OPENED_CHAT) or "").strip()
if not identifier or kind not in _TITLES:
return None
try:
diagnosis_id = int(first_value(row, "diagnosis_id", default=0) or 0)
except (TypeError, ValueError):
diagnosis_id = 0
try:
created_at = int(first_value(row, "created_at", default=0) or 0)
except (TypeError, ValueError):
created_at = 0
return ChatNotification(
id=identifier,
kind=kind,
patient_name=display_text(first_value(row, "patient_name"), ""),
patient_id=str(first_value(row, "patient_id", default="") or "").strip(),
doctor_name=display_text(first_value(row, "doctor_name"), ""),
diagnosis_id=diagnosis_id,
created_at=created_at,
)
def relative_time(created_at: int, *, now: float | None = None) -> str:
"""Match the admin card's 刚刚 / N 分钟前 wording."""
if not created_at:
return ""
current = datetime.now().timestamp() if now is None else now
delta = max(0, int(current - created_at))
if delta < 60:
return "刚刚"
if delta < 3600:
return f"{delta // 60} 分钟前"
if delta < 86400:
return f"{delta // 3600} 小时前"
return datetime.fromtimestamp(created_at).strftime("%m-%d %H:%M")
class _NotificationCard(QFrame):
"""One dismissible card; the whole surface is a click target."""
opened = Signal(str)
dismissed = Signal(str)
def __init__(self, notification: ChatNotification, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.notification = notification
self.setObjectName("ChatNotifyCard")
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
self.setCursor(Qt.CursorShape.PointingHandCursor)
kind = (
"complete"
if notification.kind == CONSULTATION_COMPLETE
else "left"
if notification.kind == PATIENT_LEFT_CHAT
else "opened"
)
self.setProperty("kind", kind)
root = QHBoxLayout(self)
root.setContentsMargins(13, 11, 10, 12)
root.setSpacing(11)
badge = QLabel("✓" if kind == "complete" else "→" if kind == "left" else "话")
badge.setObjectName("ChatNotifyBadge")
badge.setProperty("kind", kind)
badge.setAlignment(Qt.AlignmentFlag.AlignCenter)
root.addWidget(badge, 0, Qt.AlignmentFlag.AlignTop)
body = QVBoxLayout()
body.setContentsMargins(0, 0, 0, 0)
body.setSpacing(3)
title = QLabel(notification.title)
title.setObjectName("ChatNotifyTitle")
body.addWidget(title)
description = QLabel(notification.description)
description.setObjectName("ChatNotifyDesc")
description.setWordWrap(True)
body.addWidget(description)
self.time_label = QLabel(relative_time(notification.created_at))
self.time_label.setObjectName("ChatNotifyTime")
body.addWidget(self.time_label)
if notification.action_text:
actions = QHBoxLayout()
actions.setContentsMargins(0, 4, 0, 0)
actions.setSpacing(8)
self.open_button = QPushButton(notification.action_text)
self.open_button.setObjectName("ChatNotifyOpen")
self.open_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.open_button.clicked.connect(lambda: self.opened.emit(self.notification.id))
actions.addWidget(self.open_button)
actions.addStretch(1)
body.addLayout(actions)
root.addLayout(body, 1)
self.close_button = QPushButton("×")
self.close_button.setObjectName("ChatNotifyClose")
self.close_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.close_button.setToolTip("忽略这条通知")
self.close_button.clicked.connect(lambda: self.dismissed.emit(self.notification.id))
root.addWidget(self.close_button, 0, Qt.AlignmentFlag.AlignTop)
def refresh_time(self) -> None:
self.time_label.setText(relative_time(self.notification.created_at))
def mouseReleaseEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
if event.button() == Qt.MouseButton.LeftButton:
self.opened.emit(self.notification.id)
super().mouseReleaseEvent(event)
class ChatNotificationCenter(QWidget):
"""Polls the server queue and stacks cards over the shell's top-right corner."""
notification_activated = Signal(object)
def __init__(
self,
repository: Any,
host: QWidget,
*,
interval_ms: int = _POLL_INTERVAL_MS,
) -> None:
super().__init__(host)
self.repository = repository
self.setObjectName("ChatNotifyLayer")
self.setStyleSheet(clinical_stylesheet(CHAT_NOTIFICATION_QSS))
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, False)
self._cards: dict[str, _NotificationCard] = {}
self._pending: list[ChatNotification] = []
self._loading = False
self._generation = 0
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(10)
self._layout = layout
self.hide()
self._timer = QTimer(self)
self._timer.setInterval(max(1_000, int(interval_ms)))
self._timer.timeout.connect(self.poll)
self._clock = QTimer(self)
self._clock.setInterval(30_000)
self._clock.timeout.connect(self._refresh_times)
host.installEventFilter(self)
# ----- polling ------------------------------------------------------
def start(self) -> None:
if not self._timer.isActive():
self._timer.start()
self._clock.start()
self.poll()
def stop(self) -> None:
self._generation += 1
self._timer.stop()
self._clock.stop()
def poll(self) -> None:
"""Ask for queued notifications; overlapping polls are skipped.
服务端取一次即消费,重叠请求会让通知丢在被丢弃的那次响应里。
"""
if self._loading:
return
fetch = getattr(self.repository, "list_chat_notifications", None)
if not callable(fetch):
return
self._loading = True
generation = self._generation
run_async(
fetch,
on_success=lambda rows: self._loaded(generation, rows),
on_error=lambda _error: None, # 静默失败,避免打断问诊
on_finished=self._finished,
)
def _finished(self) -> None:
self._loading = False
def _loaded(self, generation: int, rows: Any) -> None:
if generation != self._generation:
return
self.add_notifications(rows)
# ----- cards --------------------------------------------------------
@property
def pending(self) -> list[ChatNotification]:
return list(self._pending)
def add_notifications(self, rows: Any) -> int:
"""Show new cards; returns how many were actually added."""
if isinstance(rows, Mapping) or not isinstance(rows, Sequence):
candidates: Sequence[Any] = [rows]
else:
candidates = rows
added = 0
for row in candidates:
notification = parse_notification(row)
if notification is None or notification.id in self._cards:
continue
self._add_card(notification)
added += 1
if added:
self._trim()
self._relayout()
self._alert_taskbar()
return added
def _add_card(self, notification: ChatNotification) -> None:
card = _NotificationCard(notification, self)
card.opened.connect(self._activate)
card.dismissed.connect(self.dismiss)
self._cards[notification.id] = card
self._pending.insert(0, notification)
self._layout.insertWidget(0, card)
def _trim(self) -> None:
while len(self._pending) > _MAX_CARDS:
self.dismiss(self._pending[-1].id, relayout=False)
def dismiss(self, notification_id: str, *, relayout: bool = True) -> None:
card = self._cards.pop(str(notification_id), None)
self._pending = [item for item in self._pending if item.id != str(notification_id)]
if card is not None:
self._layout.removeWidget(card)
card.hide()
card.deleteLater()
if relayout:
self._relayout()
def clear(self) -> None:
for notification_id in list(self._cards):
self.dismiss(notification_id, relayout=False)
self._relayout()
def _activate(self, notification_id: str) -> None:
card = self._cards.get(str(notification_id))
if card is None:
return
notification = card.notification
self.dismiss(notification_id)
self.notification_activated.emit(notification)
def _refresh_times(self) -> None:
for card in self._cards.values():
card.refresh_time()
def _alert_taskbar(self) -> None:
"""Flash the taskbar entry when the doctor is working in another window."""
application = QApplication.instance()
window = self.window()
if application is None or window is None or window.isActiveWindow():
return
application.alert(window, 3_000)
# ----- placement ----------------------------------------------------
def _relayout(self) -> None:
if not self._cards:
self.hide()
return
host = self.parentWidget()
if host is None:
return
width = min(360, max(260, host.width() - 48))
self.setFixedWidth(width)
self.adjustSize()
self.move(max(12, host.width() - width - 24), 74)
self.show()
self.raise_()
def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt virtual
if watched is self.parentWidget() and event.type() in {
QEvent.Type.Resize,
QEvent.Type.Show,
}:
self._relayout()
return False
__all__ = [
"CHAT_NOTIFICATION_QSS",
"CONSULTATION_COMPLETE",
"PATIENT_LEFT_CHAT",
"PATIENT_OPENED_CHAT",
"ChatNotification",
"ChatNotificationCenter",
"parse_notification",
"relative_time",
]