更新::

This commit is contained in:
Your Name
2026-11-06 13:35:33 +08:00
parent b46fb901ca
commit 0c43d54c08
8 changed files with 633 additions and 69 deletions
@@ -0,0 +1,109 @@
"""Global patient search must not inherit a narrow queue or stale pagination."""
from __future__ import annotations
import os
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QDate, Signal
from PySide6.QtWidgets import QApplication, QWidget
from doctor_workstation.services.repository import RemoteDoctorRepository
from doctor_workstation.ui.pages import consultations as module
class Client:
def __init__(self) -> None:
self.calls = []
def get(self, endpoint: str, params: Any = None) -> Any:
params = dict(params or {})
self.calls.append((endpoint, params))
page = params.get("page_no", 1)
return {"lists": [{"id": page, "patient_name": "测试患者"}], "count": 2}
class DetailStub(QWidget):
saved = Signal()
def __init__(self, _repository: Any, parent: QWidget | None = None) -> None:
super().__init__(parent)
@pytest.fixture(scope="module")
def application() -> QApplication:
return QApplication.instance() or QApplication([])
@pytest.fixture
def page(application: QApplication, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(module, "DiagnosisDialog", DetailStub)
def immediate(function: Any, **callbacks: Any) -> None:
callbacks["on_success"](function())
if callbacks.get("on_finished"):
callbacks["on_finished"]()
monkeypatch.setattr(module, "run_async", immediate)
client = Client()
view = module.ConsultationsPage(RemoteDoctorRepository(client))
monkeypatch.setattr(view, "_refresh_counts", lambda: None)
yield view, client
view.poll_timer.stop()
view.pager.invalidate()
view.close()
view.deleteLater()
application.processEvents()
@pytest.mark.parametrize("query", [" 林患者 ", "13800138000", "138", "", " "])
def test_global_search_submits_only_new_keyword_and_normal_scoped_list(page, query):
view, client = page
view.patient_name_edit.setText("旧患者")
view.doctor_edit.setText("旧医生")
view.keyword_edit.setText("旧手机号")
view.pending_assign_keyword.setText("旧待分配关键词")
view._pending_assign = "1"
view._pending_booking = "1"
view._completed_appointment = "1"
for combo in (view.department_combo, view.assistant_combo, view.channel_combo):
combo.addItem("旧筛选", 123)
combo.setCurrentIndex(combo.count() - 1)
view.latest_appointment_start_date.setDate(QDate(2026, 1, 3))
view.latest_appointment_end_date.setDate(QDate(2026, 1, 1))
view.latest_assign_start_date.setDate(QDate(2026, 1, 3))
view.latest_assign_end_date.setDate(QDate(2026, 1, 1))
view.unserved_sort_combo.setCurrentIndex(1)
client.calls.clear()
view.search_patient(query)
assert len(client.calls) == 1
endpoint, params = client.calls[0]
assert endpoint == "tcm.diagnosis/lists"
assert params.get("keyword", "") == query.strip()
assert params["page_no"] == 1
assert all(not value for key, value in params.items() if key not in {
"keyword", "page_no", "page_size",
})
assert view.keyword_edit.text() == query.strip()
assert view.patient_name_edit.text() == view.pending_assign_keyword.text() == ""
assert view._appointment_date == view._appointment_status_filter == ""
assert view._pending_assign == ""
assert view.table_host.model._sort_direction == ""
assert view.table_host.model.rowCount() == 1
def test_repeating_global_search_starts_at_first_page(page):
view, client = page
view.search_patient("林患者")
view.pager.load_more()
assert view.pager.page == 2
client.calls.clear()
view.search_patient("林患者")
assert [params["page_no"] for _, params in client.calls] == [1]
assert view.pager.page == 1
assert view.table_host.model.rowCount() == 1
@@ -0,0 +1,172 @@
"""Global patient searches enter the patient list with one scoped request."""
from __future__ import annotations
import os
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.pages import patients as patients_module
from doctor_workstation.ui.pages.patients import PatientsPage
class Repository:
def __init__(self) -> None:
self.calls: list[tuple[str, dict[str, Any]]] = []
def _result(self, kind: str, query: dict[str, Any]) -> dict[str, Any]:
self.calls.append((kind, dict(query)))
start = (query["page_no"] - 1) * query["page_size"]
return {
"lists": [
{
"id": index + 100,
"diagnosis_id": index + 100,
"patient_name": f"患者 {index}",
"appointment_status": 1,
"queue_status": "waiting",
}
for index in range(start, min(start + query["page_size"], 37))
],
"count": 37,
"extend": {"scope": {"label": "本人患者"}, "summary": {}},
}
def list_patients(self, **query: Any) -> dict[str, Any]:
return self._result("patients", query)
def patient_orders(self, **query: Any) -> dict[str, Any]:
return self._result("orders", query)
def patient_progress(self, **query: Any) -> dict[str, Any]:
return self._result("progress", query)
@pytest.fixture(scope="module")
def application() -> QApplication:
return QApplication.instance() or QApplication([])
@pytest.fixture
def page(application: QApplication, monkeypatch: pytest.MonkeyPatch):
def immediate(function: Any, **callbacks: Any) -> object:
result = function()
callbacks["on_success"](result)
if callbacks.get("on_finished"):
callbacks["on_finished"]()
return object()
monkeypatch.setattr(patients_module, "run_async", immediate)
repository = Repository()
widget = PatientsPage(repository, PermissionSet(["firstvisit.myPatient/lists"]))
widget.resize(1280, 900)
widget.show()
application.processEvents()
yield widget, repository
for timer in widget.findChildren(QTimer):
timer.stop()
widget.close()
widget.deleteLater()
application.processEvents()
def assert_patient_query(repository: Repository, keyword: str) -> None:
assert repository.calls == [
(
"patients",
{
"page_no": 1,
"page_size": 15,
"keyword": keyword,
"status": "",
"start_date": "",
"end_date": "",
},
)
]
@pytest.mark.parametrize("tab_index", [0, 1, 2], ids=["patients", "orders", "progress"])
@pytest.mark.parametrize("expanded", [False, True], ids=["collapsed", "expanded"])
def test_search_enters_patient_list_and_clears_old_filters(
page, monkeypatch: pytest.MonkeyPatch, tab_index: int, expanded: bool
) -> None:
widget, repository = page
workspace = widget.patient_workspace
workspace.keyword_edit.setText("旧患者")
workspace.status_combo.setCurrentIndex(2)
workspace.set_date_mode("today", refresh=False)
widget.filter_disclosures[0].set_expanded(expanded)
widget.order_workspace.keyword_edit.setText("旧订单")
widget.tabs.setCurrentIndex(tab_index)
repository.calls.clear()
refreshes: list[bool] = []
original_refresh = widget.refresh
def refresh() -> None:
refreshes.append(True)
original_refresh()
monkeypatch.setattr(widget, "refresh", refresh)
widget.search_patient(" 13800138000 ")
assert widget.tabs.currentWidget() is workspace
assert_patient_query(repository, "13800138000")
assert refreshes == [True]
assert workspace.keyword_edit.text() == "13800138000"
assert workspace._date_mode == "all"
assert workspace.status_buttons[""].isChecked()
assert workspace._page == workspace.pager.page == 1
assert widget.filter_disclosures[0].expanded is expanded
assert widget.order_workspace.keyword_edit.text() == "旧订单"
assert not widget.progress_workspace.timer.isActive()
@pytest.mark.parametrize("query", ["", " "], ids=["empty", "whitespace"])
def test_empty_search_clears_keyword_even_when_patient_page_is_hidden(page, query: str) -> None:
widget, repository = page
widget.patient_workspace.keyword_edit.setText("旧患者")
widget.patient_workspace.status_combo.setCurrentIndex(3)
widget.tabs.setCurrentIndex(1)
widget.hide()
repository.calls.clear()
widget.search_patient(query)
assert widget.tabs.currentIndex() == 0
assert widget.patient_workspace.keyword_edit.text() == ""
assert_patient_query(repository, "")
def test_repeated_search_discards_previously_loaded_pages(page) -> None:
widget, repository = page
widget.search_patient("患者")
workspace = widget.patient_workspace
workspace.pager.load_more()
assert workspace._page == workspace.pager.page == 2
repository.calls.clear()
widget.search_patient("患者")
assert_patient_query(repository, "患者")
assert workspace._page == workspace.pager.page == 1
assert workspace.table.rowCount() == 15
def test_reset_button_still_accepts_qt_clicked_signal(page) -> None:
widget, repository = page
workspace = widget.patient_workspace
workspace.keyword_edit.setText("旧患者")
workspace.status_combo.setCurrentIndex(2)
repository.calls.clear()
workspace.reset_button.click()
assert workspace.keyword_edit.text() == ""
assert_patient_query(repository, "")
+176
View File
@@ -0,0 +1,176 @@
"""Historical reception queries retain their day and include finished appointments."""
from __future__ import annotations
import os
from datetime import date
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QDate, QTimer
from PySide6.QtWidgets import QApplication
from doctor_workstation.core import PermissionSet
from doctor_workstation.services.repository import RemoteDoctorRepository
from doctor_workstation.ui.pages import reception as module
from doctor_workstation.ui.widgets import StatusBadge
class Today(date):
@classmethod
def today(cls):
return cls(2026, 11, 6)
class Client:
def __init__(self):
self.calls = []
def get(self, endpoint: str, params: Any = None):
params = dict(params or {})
self.calls.append((endpoint, params))
assert endpoint == "doctor.appointment/lists"
day = params["start_date"]
statuses = [2, 3, 4] if day == "2026-10-17" else []
rows = [
{"id": status, "patient_name": "测试患者", "status": status,
"status_desc": module.STATUS_TEXT[status], "appointment_date": day}
for status in statuses
if params.get("status") in (None, "", status)
]
offset = (params["page_no"] - 1) * params["page_size"]
return {
"lists": rows[offset:offset + params["page_size"]], "count": len(rows),
"extend": {"status_count": {str(status): statuses.count(status) for status in range(1, 5)}},
}
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def page(application, monkeypatch):
def immediate(function, **callbacks):
callbacks["on_success"](function())
callbacks["on_finished"]()
monkeypatch.setattr(module, "date", Today)
monkeypatch.setattr(module, "run_async", immediate)
client = Client()
widget = module.ReceptionPage(RemoteDoctorRepository(client), PermissionSet([]))
# Keep this test on the list boundary, without loading patient clinical details.
monkeypatch.setattr(widget, "_select_record", lambda *_args, **_kwargs: None)
monkeypatch.setattr(widget, "_maybe_load_more_queue", lambda: None)
yield widget, client
for timer in widget.findChildren(QTimer):
timer.stop()
widget.close()
widget.deleteLater()
application.processEvents()
def test_historical_day_opens_all_statuses_and_labels_cancelled_correctly(page):
widget, client = page
widget.queue_date_button._pick_date(QDate(2026, 10, 17))
assert widget.queue_title.text() == "历史接诊"
assert widget._queue_filter_status is None
assert widget._queue_filter_buttons[None].isChecked()
assert [record.status for record in widget._queue_records] == [2, 3, 4]
assert widget._queue_filter_buttons[None].text() == "全部 3"
assert widget._queue_filter_buttons[2].text() == "已取消 1"
row = widget.queue_list.itemWidget(widget.queue_list.item(0))
assert any(badge.text() == "已取消" and not badge.isHidden() for badge in row.findChildren(StatusBadge))
assert client.calls[-1][1]["start_date"] == client.calls[-1][1]["end_date"] == "2026-10-17"
assert not client.calls[-1][1].get("status")
assert "progress_board" not in client.calls[-1][1]
assert "diag_scope_relax" not in client.calls[-1][1]
@pytest.mark.parametrize("status", [None, 1, 2, 3, 4])
def test_history_status_refresh_and_poll_keep_exact_date(page, status):
widget, client = page
widget.queue_date_button._pick_date(QDate(2026, 10, 17))
widget._set_queue_filter(status)
widget.refresh(workspace_refresh=True)
widget._poll_queue()
assert all(params["start_date"] == params["end_date"] == "2026-10-17" for _, params in client.calls)
assert client.calls[-1][1].get("status") == status
assert widget._queue_filter_buttons[None].text() == "全部 3"
if status == 2:
assert "已取消" in widget.queue_filter_summary.text()
def test_history_pagination_keeps_date_and_status(page):
widget, client = page
widget._queue_page_size = 2
widget.queue_date_button._pick_date(QDate(2026, 10, 17))
widget._load_more()
assert [params["page_no"] for _, params in client.calls] == [1, 2]
assert len(widget._queue_records) == 3
assert client.calls[-1][1]["start_date"] == "2026-10-17"
assert not client.calls[-1][1].get("status")
def test_empty_day_explains_selected_date_and_explicit_today_selection_shows_all(page):
widget, _client = page
assert widget._queue_filter_status == 1
widget.queue_date_button._pick_date(QDate(2026, 10, 16))
assert widget.queue_stack.currentWidget() is widget.queue_empty
assert "2026-10-16" in widget.queue_empty_description.text()
assert "当前账号" in widget.queue_empty_description.text()
assert "挂号记录" in widget.queue_empty_description.text()
widget.queue_date_button._pick_date(QDate(2026, 11, 6))
assert widget.queue_title.text() == "今日接诊"
assert widget._queue_filter_status is None
widget.queue_date_button._pick_date(QDate(2026, 11, 7))
assert widget.queue_title.text() == "预约接诊"
@pytest.mark.parametrize("selected_date", ["2026-10-17", "2026-11-06", "2026-11-07"])
def test_selecting_any_day_clears_old_name_and_status_with_one_request(page, application, selected_date):
widget, client = page
widget.show()
application.processEvents()
widget.search_edit.setText("之前查过的患者")
widget._set_queue_filter(3)
client.calls.clear()
widget.queue_date_button._pick_date(QDate.fromString(selected_date, "yyyy-MM-dd"))
assert len(client.calls) == 1
endpoint, params = client.calls[0]
assert endpoint == "doctor.appointment/lists"
assert params["start_date"] == params["end_date"] == selected_date
assert params["page_no"] == 1
assert not params.get("patient_name")
assert not params.get("status")
assert widget.search_edit.text() == ""
assert widget._queue_filter_buttons[None].isChecked()
assert not any(key in params for key in ("progress_board", "diag_scope_relax", "assistant_id"))
def test_calendar_reselects_same_day_and_deduplicates_click_activation(page, application):
widget, client = page
widget.show()
application.processEvents()
widget._set_queue_filter(3)
widget.search_edit.setText("旧姓名")
client.calls.clear()
button = widget.queue_date_button
calendar = button.calendarWidget()
selected = QDate(2026, 11, 6)
button.click()
assert calendar.isVisible()
calendar.clicked.emit(selected)
calendar.activated.emit(selected)
assert len(client.calls) == 1
assert not calendar.isVisible()
assert widget.search_edit.text() == ""
assert widget._queue_filter_status is None
button.click()
calendar.activated.emit(selected)
assert len(client.calls) == 2
+70 -2
View File
@@ -7,7 +7,8 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QSize, Qt
from PySide6.QtWidgets import QApplication, QDialog, QFrame, QToolButton, QWidget
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QDialog, QFrame, QLineEdit, QToolButton, QWidget
from doctor_workstation.ui import shell as shell_module
from doctor_workstation.ui.shell import NavigationItem, ShellWindow
@@ -35,10 +36,15 @@ class _ShellPageDouble(QWidget):
self.show_count = 0
self.ai_context_available = False
self.ai_open_count = 0
self.search_queries: list[str] = []
def refresh(self) -> None:
self.refresh_count += 1
def search_patient(self, query: str) -> None:
self.search_queries.append(query)
self.refresh()
def open_selected_ai_consult(self) -> bool:
self.ai_open_count += 1
return self.ai_context_available
@@ -243,13 +249,75 @@ def test_registered_pages_are_not_top_level_windows(shell_window: ShellWindow) -
assert not page.isWindow()
@pytest.mark.parametrize("origin,trigger,target", [
("consultations", "enter", "consultations"),
("appointments", "button", "consultations"),
("prescriptions", "enter", "consultations"),
("prescription_library", "button", "consultations"),
("patients", "enter", "patients"),
("legacy_reference", "action", "consultations"),
])
def test_topbar_search_routes_to_patient_page_once(
shell_window: ShellWindow, application: QApplication, origin: str, trigger: str, target: str,
) -> None:
assert shell_window.navigate(origin)
application.processEvents()
unrelated = QLineEdit(shell_window.pages[origin])
unrelated.setPlaceholderText("患者姓名")
unrelated.setText("原页面条件")
page = shell_window.pages[target]
before = page.refresh_count
shell_window.global_search.setText(" 13800138000 ")
if trigger == "enter":
QTest.keyClick(shell_window.global_search, Qt.Key.Key_Return)
elif trigger == "button":
QTest.mouseClick(shell_window.search_mark, Qt.MouseButton.LeftButton)
else:
shell_window._global_search_icon_action.trigger()
application.processEvents()
assert shell_window.stack.currentWidget() is page
assert page.search_queries == ["13800138000"]
assert page.refresh_count == before + 1
assert unrelated.text() == "原页面条件"
def test_topbar_search_uses_available_patient_page_and_empty_query_clears(
shell_window: ShellWindow, application: QApplication,
) -> None:
shell_window.pages.pop("consultations")
shell_window.global_search.setText("林患者")
QTest.keyClick(shell_window.global_search, Qt.Key.Key_Return)
application.processEvents()
patient_page = shell_window.pages["patients"]
assert shell_window.stack.currentWidget() is patient_page
shell_window.global_search.clear()
QTest.keyClick(shell_window.global_search, Qt.Key.Key_Return)
assert patient_page.search_queries == ["林患者", ""]
def test_topbar_search_without_patient_page_does_not_query_unrelated_pages(
shell_window: ShellWindow, monkeypatch: pytest.MonkeyPatch,
) -> None:
shell_window.pages.pop("consultations")
shell_window.pages.pop("patients")
current = shell_window.stack.currentWidget()
before = current.refresh_count
messages = []
monkeypatch.setattr(shell_module, "show_toast", lambda *args: messages.append(args))
shell_window.global_search.setText("林患者")
QTest.keyClick(shell_window.global_search, Qt.Key.Key_Return)
assert current.refresh_count == before
assert shell_window.stack.currentWidget() is current
assert "没有可用的患者搜索页面" in messages[0][1]
def test_reference_shell_has_integrated_search_ai_card_and_window_controls(
shell_window: ShellWindow,
) -> None:
assert shell_window.navigate("legacy_reference")
assert shell_window.windowFlags() & Qt.WindowType.FramelessWindowHint
assert (
shell_window.global_search.placeholderText() == "搜索患者姓名、手机号、病历号"
shell_window.global_search.placeholderText() == "搜索患者姓名、手机号..."
)
assert shell_window.assistant_card.isVisible()
assert shell_window.assistant_button.text() == "开始对话"