This commit is contained in:
gr
2026-11-05 17:28:39 +08:00
9 changed files with 894 additions and 18 deletions
@@ -98,6 +98,7 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
// 关键字:待分配 Tab 用多字段宽搜;其它 Tab 仍为姓名/手机。
$this->applyDiagnosisListKeywordFilter($query, $pendingAssign);
$this->applyDoctorNameFilter($query, $pendingWideSearch);
// 待分配医助列表:assistant_id 为 NULL 或 0(宽搜不加此条件)
if ($narrowPendingAssignPool) {
@@ -191,7 +192,11 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
$appointmentMap = [];
$subQuery = Appointment::where('patient_id', 'in', $diagnosisIds)
->where('status', 'in', [1, 3, 4]); // 1=已预约 3=已完成 4=已过号
if (!empty($this->params['appointment_date'])) {
$doctorConditions = $this->doctorAppointmentConditions($pendingWideSearch, (new Appointment())->getTable());
if ($doctorConditions !== null) {
// 根级操作挂号与嵌套预约必须使用筛选命中的挂号,不能取该患者其他医生的第一条预约。
$subQuery->whereRaw($doctorConditions[0], $doctorConditions[1]);
} elseif (!$pendingWideSearch && !empty($this->params['appointment_date'])) {
$subQuery->where('appointment_date', (string) $this->params['appointment_date']);
}
@@ -568,6 +573,7 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
}
$this->applyDiagnosisListKeywordFilter($query, $pendingAssign);
$this->applyDoctorNameFilter($query, $pendingWideSearch);
if ($narrowPendingAssignPool) {
$query->whereRaw('(assistant_id IS NULL OR assistant_id = 0)');
@@ -643,6 +649,60 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
$this->applyPendingAssignBusinessOrderMonthFilter($query);
return $query->count();
}
/**
* 医生姓名按有效挂号关联;日期、状态必须命中同一条挂号,避免历史医生串入当前队列。
* EXISTS 在分页前执行且与 count 共用,不会因同医生的多次挂号重复计数。
*/
private function applyDoctorNameFilter($query, bool $pendingWideSearch): void
{
$doctorConditions = $this->doctorAppointmentConditions($pendingWideSearch, 'doctor_apt');
if ($doctorConditions === null) {
return;
}
$aptTbl = (new Appointment())->getTable();
$diagTbl = (new Diagnosis())->getTable();
$query->whereExists(new \think\db\Raw(
"SELECT 1 FROM {$aptTbl} doctor_apt WHERE doctor_apt.patient_id = {$diagTbl}.id AND " . $doctorConditions[0],
$doctorConditions[1]
));
}
/**
* 列表/count 的诊单筛选与列表预约组装共用条件,保证医生、日期、状态来自同一挂号。
* @return array{0:string,1:array}|null
*/
private function doctorAppointmentConditions(bool $pendingWideSearch, string $appointmentAlias): ?array
{
$doctorName = trim((string) ($this->params['doctor_name'] ?? ''));
if ($doctorName === '') {
return null;
}
$adminTbl = (new Admin())->getTable();
$conditions = [
"{$appointmentAlias}.status IN (" . implode(',', self::EFFECTIVE_APPOINTMENT_STATUSES) . ')',
"EXISTS (SELECT 1 FROM {$adminTbl} filter_doctor WHERE filter_doctor.id = {$appointmentAlias}.doctor_id"
. ' AND filter_doctor.delete_time IS NULL AND filter_doctor.name LIKE :diagnosis_doctor_name)',
];
$bindings = ['diagnosis_doctor_name' => '%' . $doctorName . '%'];
// 待分配关键词宽搜保持原有日期/状态豁免,但仍尊重明确输入的医生姓名。
if (!$pendingWideSearch) {
if (!empty($this->params['appointment_date'])) {
$conditions[] = "{$appointmentAlias}.appointment_date = :diagnosis_doctor_date";
$bindings['diagnosis_doctor_date'] = (string) $this->params['appointment_date'];
}
if (isset($this->params['appointment_status']) && $this->params['appointment_status'] !== '') {
$conditions[] = "{$appointmentAlias}.status = :diagnosis_doctor_status";
$bindings['diagnosis_doctor_status'] = (int) $this->params['appointment_status'];
}
if (isset($this->params['completed_appointment']) && (string) $this->params['completed_appointment'] === '1') {
$conditions[] = "{$appointmentAlias}.status = 3";
}
}
return [implode(' AND ', $conditions), $bindings];
}
/**
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
// Execute real list/count SQL and hydration against Python's synthetic SQLite database.
// JSON lines on stdout/stdin transport SQL/results; no application database is connected.
require dirname(__DIR__) . '/vendor/autoload.php';
final class DiagnosisDoctorNoConnection extends think\db\connector\Mysql
{
public function connect(array $config = [], $linkNum = 0, $autoConnection = false): PDO
{
throw new RuntimeException('Doctor filter tests must never open a database connection');
}
public function getFields(string $tableName): array { return []; }
}
final class DiagnosisDoctorQuery extends think\db\Query
{
public static array $captured = [];
public function with($with) { return $this; }
public function append(array $append = []) { return $this; }
private function executeFixture(): array
{
$this->parseOptions();
$query = [
'sql' => $this->getConnection()->getBuilder()->select($this),
'bindings' => array_map(static fn ($binding) => $binding[0], $this->getBind()),
];
self::$captured[] = $query;
echo json_encode(['query' => $query], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . PHP_EOL;
$response = json_decode((string) fgets(STDIN), true, 512, JSON_THROW_ON_ERROR);
if (isset($response['error'])) {
throw new RuntimeException($response['error']);
}
return $response['rows'];
}
public function select(array $data = []): think\Collection
{
return new think\Collection($this->executeFixture());
}
public function count(string $field = '*'): int
{
$this->field('COUNT(*) AS think_count');
return (int) $this->executeFixture()[0]['think_count'];
}
public function column(string|array $field, string $key = ''): array
{
$this->field($key !== '' ? [$key, $field] : $field);
return array_column($this->executeFixture(), $field, $key !== '' ? $key : null);
}
public function getTableFields(string $tableName = ''): array
{
return [];
}
}
class DiagnosisDoctorModel
{
protected const TABLE = 'tcm_diagnosis';
public function getTable(): string { return static::TABLE; }
private static function query(): DiagnosisDoctorQuery
{
$query = (new DiagnosisDoctorQuery(new DiagnosisDoctorNoConnection(['type' => 'mysql'])))
->table(static::TABLE);
return static::TABLE === 'tcm_diagnosis' ? $query->whereNull('delete_time') : $query;
}
public static function where(...$args): DiagnosisDoctorQuery { return static::query()->where(...$args); }
public static function whereIn(...$args): DiagnosisDoctorQuery { return static::query()->whereIn(...$args); }
}
final class DiagnosisDoctorAppointment extends DiagnosisDoctorModel
{
protected const TABLE = 'doctor_appointment';
}
final class DiagnosisDoctorAdmin extends DiagnosisDoctorModel { protected const TABLE = 'admin'; }
final class DiagnosisDoctorPrescription extends DiagnosisDoctorModel { protected const TABLE = 'tcm_prescription'; }
// Unrelated list enrichment is empty in this fixture; current appointment prescriptions run real SQL.
final class DiagnosisDoctorEmptyModel
{
public static function where(...$args): self { return new self(); }
public static function whereIn(...$args): self { return new self(); }
public function __call($name, $args) { return $this; }
public function column(...$args): array { return []; }
public function select(): think\Collection { return new think\Collection([]); }
}
final class DiagnosisDoctorRevisitDue
{
public static function buildListPayload(...$args): array { return []; }
public static function emptyPayload(): array { return []; }
}
final class DiagnosisDoctorDb
{
public static function name(string $name): DiagnosisDoctorQuery
{
return (new DiagnosisDoctorQuery(new DiagnosisDoctorNoConnection(['type' => 'mysql'])))->table($name);
}
}
final class DiagnosisDoctorRoles
{
public static array $roles = [];
public static function where(...$args): self { return new self(); }
public function column(...$args): array { return self::$roles; }
}
class_alias(DiagnosisDoctorModel::class, 'app\\common\\model\\tcm\\Diagnosis');
class_alias(DiagnosisDoctorAppointment::class, 'app\\common\\model\\doctor\\Appointment');
class_alias(DiagnosisDoctorAdmin::class, 'app\\common\\model\\auth\\Admin');
class_alias(DiagnosisDoctorRoles::class, 'app\\common\\model\\auth\\AdminRole');
class_alias(DiagnosisDoctorPrescription::class, 'app\\common\\model\\tcm\\Prescription');
foreach (['tcm\\CallRecord', 'tcm\\BloodRecord', 'tcm\\DietRecord', 'tcm\\ExerciseRecord', 'dict\\DictData'] as $model) {
class_alias(DiagnosisDoctorEmptyModel::class, 'app\\common\\model\\' . $model);
}
class_alias(DiagnosisDoctorRevisitDue::class, 'app\\common\\service\\tcm\\RevisitDueService');
class_alias(DiagnosisDoctorDb::class, 'think\\facade\\Db');
class DiagnosisDoctorLists extends app\adminapi\lists\tcm\DiagnosisLists
{
public array $visibleIds = [301];
protected function dataScopeShouldApply(): bool { return true; }
protected function getDataScopeVisibleAdminIds(): ?array { return $this->visibleIds; }
}
$cases = [
'all' => [],
'blank' => ['doctor_name' => ' '],
'doctor' => ['doctor_name' => ' 陈医生 '],
'partial' => ['doctor_name' => '陈'],
'unknown' => ['doctor_name' => '不存在'],
'other' => ['doctor_name' => '李医生'],
'today' => ['doctor_name' => '陈医生', 'appointment_date' => '2026-11-05'],
'today_pending' => ['doctor_name' => '陈医生', 'appointment_date' => '2026-11-05', 'appointment_status' => 1],
'today_completed' => ['doctor_name' => '陈医生', 'appointment_date' => '2026-11-05', 'completed_appointment' => 1],
'latest_range' => ['doctor_name' => '陈医生', 'latest_appointment_start_date' => '2026-11-05', 'latest_appointment_end_date' => '2026-11-05'],
'page' => ['doctor_name' => '陈医生', 'fixture_offset' => 1, 'fixture_length' => 2],
'keyword' => ['doctor_name' => '陈医生', 'keyword' => '目标'],
'assistant' => ['doctor_name' => '陈医生', 'fixture_role' => 2],
'no_scope' => ['doctor_name' => '陈医生', 'fixture_scope' => []],
'injection' => ['doctor_name' => "陈医生' OR 1=1 --"],
'pending_wide' => [
'doctor_name' => '陈医生', 'pending_assign' => 1, 'pending_assign_keyword' => '目标',
'appointment_date' => '1900-01-01', 'appointment_status' => 2,
],
];
$reflection = new ReflectionClass(DiagnosisDoctorLists::class);
$result = [];
foreach ($cases as $name => $params) {
$lists = $reflection->newInstanceWithoutConstructor();
$reflection->getProperty('params')->setValue($lists, $params);
$reflection->getProperty('adminId')->setValue($lists, 301);
$reflection->getProperty('searchWhere')->setValue($lists, []);
$lists->visibleIds = $params['fixture_scope'] ?? [301];
$lists->limitOffset = $params['fixture_offset'] ?? 0;
$lists->limitLength = $params['fixture_length'] ?? 100;
DiagnosisDoctorRoles::$roles = isset($params['fixture_role']) ? [$params['fixture_role']] : [];
DiagnosisDoctorQuery::$captured = [];
$result[$name] = [
'count' => $lists->count(),
'lists' => $lists->lists(),
'queries' => DiagnosisDoctorQuery::$captured,
];
}
echo json_encode(['result' => $result], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . PHP_EOL;
+167
View File
@@ -0,0 +1,167 @@
"""Execute real ThinkPHP list/count SQL and nonempty list hydration against synthetic SQLite rows.
Run: python server/tests/DiagnosisDoctorFilterTest.py
Requires PHP plus the existing server/vendor dependencies, never production data.
"""
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import unittest
class DiagnosisDoctorFilterTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.db = sqlite3.connect(":memory:")
cls.db.row_factory = sqlite3.Row
cls.db.create_function("CONCAT", -1, lambda *values: "".join(map(str, values)))
cls.db.executescript("""
CREATE TABLE tcm_diagnosis (
id INTEGER, patient_id INTEGER, patient_name TEXT, id_card TEXT, phone TEXT,
gender INTEGER, age INTEGER, diagnosis_date TEXT, diagnosis_type TEXT,
syndrome_type TEXT, assistant_id INTEGER, assign_read_at INTEGER, status INTEGER,
create_time INTEGER, update_time INTEGER, delete_time INTEGER, remark TEXT,
symptoms TEXT, current_medications TEXT
);
CREATE TABLE doctor_appointment (
id INTEGER, patient_id INTEGER, doctor_id INTEGER, appointment_date TEXT,
appointment_time TEXT, status INTEGER, appointment_type TEXT, create_time INTEGER
);
CREATE TABLE admin (id INTEGER, name TEXT, delete_time INTEGER);
CREATE TABLE tcm_prescription (
id INTEGER, diagnosis_id INTEGER, appointment_id INTEGER, doctor_name TEXT,
creator_id INTEGER, prescription_date TEXT, create_time INTEGER,
void_status INTEGER, audit_status INTEGER, delete_time INTEGER
);
INSERT INTO admin VALUES (201, '陈医生', NULL), (202, '李医生', NULL), (203, '陈医生已删除', 1);
INSERT INTO tcm_prescription VALUES
(101, 1, 1, '陈医生', 201, '2026-11-05', 1, 0, 1, NULL),
(102, 1, 13, '李医生', 202, '2026-11-03', 1, 0, 0, NULL);
""")
for diagnosis_id in range(1, 10):
cls.db.execute(
"INSERT INTO tcm_diagnosis (id, patient_id, patient_name, assistant_id, delete_time) VALUES (?, ?, ?, ?, ?)",
(diagnosis_id, diagnosis_id + 100, f"目标患者{diagnosis_id}", 302 if diagnosis_id == 7 else 301,
1 if diagnosis_id == 8 else None),
)
appointments = [
# Two same-doctor appointments must still yield one diagnosis/count.
(1, 1, 201, "2026-11-05", 1), (2, 1, 201, "2026-11-05", 1),
# Historical doctor A must not appear in doctor A's today queue.
(3, 2, 201, "2026-11-04", 3), (4, 2, 202, "2026-11-05", 1),
# Doctor A completed while doctor B is pending on the same day.
(5, 3, 201, "2026-11-05", 3), (6, 3, 202, "2026-11-05", 1),
(7, 4, 201, "2026-11-05", 2), # Cancelled does not establish ownership.
(8, 5, 202, "2026-11-05", 1),
(9, 6, 201, "2026-11-06", 4),
(10, 7, 201, "2026-11-05", 1), # Outside assistant data scope.
(11, 8, 201, "2026-11-05", 1), # Deleted diagnosis.
(12, 9, 203, "2026-11-05", 1), # Deleted doctor.
(13, 1, 202, "2026-11-03", 1), # Earlier other-doctor row must never drive actions.
(14, 1, 201, "2026-11-05", 4), # Same doctor/day, wrong status for pending queue.
]
cls.db.executemany(
"INSERT INTO doctor_appointment VALUES (?, ?, ?, ?, '09:00:00', ?, 'video', 1)", appointments
)
fixture = Path(__file__).with_name("DiagnosisDoctorFilterSqlFixture.php")
with subprocess.Popen(
[os.environ.get("PHP_BINARY", "php"), str(fixture)], encoding="utf-8",
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
) as process:
for line in process.stdout:
message = json.loads(line)
if "result" in message:
cls.results = message["result"]
break
query = message["query"]
try:
rows = cls.db.execute(query["sql"], query["bindings"]).fetchall()
response = {"rows": [dict(row) for row in rows]}
except sqlite3.Error as error:
response = {"error": f"{error}: {query['sql']}"}
process.stdin.write(json.dumps(response, ensure_ascii=False) + "\n")
process.stdin.flush()
_, errors = process.communicate(timeout=20)
if process.returncode:
raise AssertionError(errors)
@classmethod
def tearDownClass(cls):
cls.db.close()
def result(self, case):
result = self.results[case]
return [row["id"] for row in result["lists"]], result["count"]
def assert_case(self, case, expected):
ids, count = self.result(case)
self.assertCountEqual(ids, expected, case)
self.assertEqual(count, len(expected), case)
def test_name_filter_effective_appointments_and_data_scope(self):
for case in ("doctor", "partial", "keyword", "assistant"):
self.assert_case(case, [1, 2, 3, 6])
self.assert_case("other", [1, 2, 3, 5])
self.assert_case("unknown", [])
self.assert_case("no_scope", [])
def test_blank_filter_keeps_existing_list(self):
self.assertEqual(self.result("blank"), self.result("all"))
self.assert_case("all", [1, 2, 3, 4, 5, 6, 9])
def test_date_and_status_must_match_the_same_doctors_appointment(self):
self.assert_case("today", [1, 3])
self.assert_case("today_pending", [1])
self.assert_case("today_completed", [3])
def test_latest_date_range_retains_its_existing_latest_appointment_meaning(self):
self.assert_case("latest_range", [1, 2, 3])
def test_pagination_does_not_change_filtered_count(self):
all_ids, count = self.result("doctor")
self.assertEqual(self.result("page"), (all_ids[1:3], count))
def test_pending_keyword_wide_search_keeps_explicit_doctor(self):
self.assert_case("pending_wide", [1, 2, 3, 6, 7])
def test_hydrated_appointments_root_and_prescription_use_matching_appointment(self):
for case in ("doctor", "today", "today_pending", "today_completed", "pending_wide"):
for row in self.results[case]["lists"]:
with self.subTest(case=case, diagnosis=row["id"]):
self.assertTrue(row["appointments"])
for appointment in row["appointments"]:
self.assertEqual(appointment["doctor_name"], "陈医生")
self.assertEqual(appointment["doctor_id"], 201)
if case.startswith("today"):
self.assertTrue(appointment["time_text"].startswith("2026-11-05"))
if case in ("today_pending", "today_completed"):
self.assertEqual(appointment["status"], 1 if case == "today_pending" else 3)
primary = row["appointments"][0]
for root, nested in (
("appointment_id", "id"), ("appointment_status", "status"),
("appointment_doctor_id", "doctor_id"), ("appointment_doctor_name", "doctor_name"),
("appointment_time_text", "time_text"), ("appointment_type", "appointment_type"),
):
self.assertEqual(row[root], primary[nested])
row = next(row for row in self.results["today_pending"]["lists"] if row["id"] == 1)
self.assertEqual([appointment["id"] for appointment in row["appointments"]], [1, 2])
self.assertEqual(row["current_prescription_id"], 101)
self.assertEqual(row["prescription_audit_status"], 1)
def test_doctor_filter_does_not_change_latest_appointment_summary(self):
row = next(row for row in self.results["doctor"]["lists"] if row["id"] == 2)
self.assertEqual(row["appointment_id"], 3)
self.assertEqual(row["latest_appointment_id"], 4)
def test_doctor_name_is_bound_data(self):
self.assert_case("injection", [])
for query in self.results["injection"]["queries"]:
self.assertNotIn("陈医生' OR 1=1 --", query["sql"])
self.assertIn("%陈医生' OR 1=1 --%", query["bindings"].values())
if __name__ == "__main__":
unittest.main()