This commit is contained in:
Your Name
2026-11-06 12:01:31 +08:00
parent 5926083221
commit b46fb901ca
9 changed files with 1433 additions and 11 deletions
@@ -184,6 +184,21 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
->limit($this->limitOffset, $this->limitLength)
->select()
->toArray();
// 仅补充已通过权限过滤且落在本页的医助姓名,不依赖调用者拥有后台人员列表权限。
$assistantIds = array_values(array_unique(array_filter(array_map(
'intval',
array_column($lists, 'assistant_id')
), static function (int $id): bool {
return $id > 0;
})));
$assistantNames = $assistantIds === []
? []
: Admin::whereIn('id', $assistantIds)->whereNull('delete_time')->column('name', 'id');
foreach ($lists as &$item) {
$item['assistant_name'] = trim((string) ($assistantNames[(int) ($item['assistant_id'] ?? 0)] ?? ''));
}
unset($item);
// 关联挂号:doctor_appointment.patient_id 存诊单主键 id(与 Appointment 列表 join 一致)
$diagnosisIds = array_filter(array_unique(array_column($lists, 'id')));
+261
View File
@@ -0,0 +1,261 @@
<?php
declare(strict_types=1);
// Exercise the real lists/count methods with synthetic in-memory rows only.
require dirname(__DIR__) . '/vendor/autoload.php';
final class AssistantNameQuery
{
public static array $tables = [];
public static array $adminReads = [];
private array $conditions = [];
private ?array $fields = null;
private int $offset = 0;
private ?int $length = null;
public function __construct(private string $table) {}
public function where($field, $operator = null, $value = null): self
{
if (is_array($field)) {
foreach ($field as $condition) {
$this->where(...$condition);
}
return $this;
}
if (func_num_args() === 2) {
$value = $operator;
$operator = '=';
}
if ($operator === 'in') {
return $this->whereIn($field, $value);
}
if ($operator !== '=') {
throw new RuntimeException('Unexpected fixture operator: ' . $operator);
}
$this->conditions[] = [$field, '=', $value];
return $this;
}
public function whereIn(string $field, array $values): self
{
$this->conditions[] = [$field, 'in', $values];
return $this;
}
public function whereNull(string $field): self
{
$this->conditions[] = [$field, 'null', null];
return $this;
}
public function whereRaw(string $sql): self
{
if (!in_array($sql, ['0 = 1', '(assistant_id IS NULL OR assistant_id = 0)'], true)) {
throw new RuntimeException('Unexpected fixture SQL: ' . $sql);
}
$this->conditions[] = ['', 'raw', $sql];
return $this;
}
public function with(array $relations): self { return $this; }
public function append(array $fields): self { return $this; }
public function orderRaw(string $order): self { return $this; }
public function order(string $field, string $direction): self { return $this; }
public function group(string $field): self { return $this; }
public function getTableFields(): array { return []; }
public function field($fields): self
{
$this->fields = is_array($fields) ? $fields : array_map('trim', explode(',', $fields));
return $this;
}
public function limit(int $offset, int $length): self
{
$this->offset = $offset;
$this->length = $length;
return $this;
}
private function rows(): array
{
$rows = array_values(array_filter(self::$tables[$this->table] ?? [], function (array $row): bool {
foreach ($this->conditions as [$field, $operator, $value]) {
$actual = $row[$field] ?? null;
if (($operator === '=' && $actual != $value)
|| ($operator === 'in' && !in_array($actual, $value))
|| ($operator === 'null' && $actual !== null)
|| ($operator === 'raw' && ($value === '0 = 1' || ($row['assistant_id'] ?? 0) != 0))) {
return false;
}
}
return true;
}));
return array_slice($rows, $this->offset, $this->length);
}
public function select(): think\Collection
{
if ($this->table === 'admin') {
throw new RuntimeException('Assistant enrichment must not read full admin records');
}
$rows = $this->rows();
if ($this->fields !== null) {
$rows = array_map(fn (array $row): array => array_intersect_key($row, array_flip($this->fields)), $rows);
}
return new think\Collection($rows);
}
public function column(string $field, string $key = ''): array
{
if ($this->table === 'admin') {
self::$adminReads[] = ['conditions' => $this->conditions, 'field' => $field, 'key' => $key];
}
return array_column($this->rows(), $field, $key !== '' ? $key : null);
}
public function count(): int { return count($this->rows()); }
}
class AssistantNameModel
{
protected const TABLE = 'empty';
public function getTable(): string { return static::TABLE; }
public static function where(...$args): AssistantNameQuery
{
return (new AssistantNameQuery(static::TABLE))->where(...$args);
}
public static function whereIn(...$args): AssistantNameQuery
{
return (new AssistantNameQuery(static::TABLE))->whereIn(...$args);
}
}
final class AssistantNameDiagnosis extends AssistantNameModel { protected const TABLE = 'tcm_diagnosis'; }
final class AssistantNameAdmin extends AssistantNameModel { protected const TABLE = 'admin'; }
final class AssistantNameRoles extends AssistantNameModel { protected const TABLE = 'admin_role'; }
final class AssistantNameAppointment extends AssistantNameModel { protected const TABLE = 'doctor_appointment'; }
final class AssistantNameDb
{
public static function name(string $table): AssistantNameQuery { return new AssistantNameQuery($table); }
}
final class AssistantNameRevisitDue
{
public static function buildListPayload(...$args): array { return []; }
public static function emptyPayload(): array { return []; }
}
class_alias(AssistantNameDiagnosis::class, 'app\\common\\model\\tcm\\Diagnosis');
class_alias(AssistantNameAdmin::class, 'app\\common\\model\\auth\\Admin');
class_alias(AssistantNameRoles::class, 'app\\common\\model\\auth\\AdminRole');
class_alias(AssistantNameAppointment::class, 'app\\common\\model\\doctor\\Appointment');
foreach (['tcm\\Prescription', 'tcm\\CallRecord', 'tcm\\BloodRecord', 'tcm\\DietRecord',
'tcm\\ExerciseRecord', 'dict\\DictData'] as $model) {
class_alias(AssistantNameModel::class, 'app\\common\\model\\' . $model);
}
class_alias(AssistantNameDb::class, 'think\\facade\\Db');
class_alias(AssistantNameRevisitDue::class, 'app\\common\\service\\tcm\\RevisitDueService');
final class AssistantNameLists extends app\adminapi\lists\tcm\DiagnosisLists
{
public function __construct(private ?array $visibleIds = null, array $params = [], int $offset = 0,
int $length = 100, int $actor = 91)
{
$this->params = $params;
$this->adminId = $actor;
$this->adminInfo = ['admin_id' => $actor];
$this->searchWhere = [];
$this->limitOffset = $offset;
$this->limitLength = $length;
}
protected function dataScopeShouldApply(): bool { return true; }
protected function getDataScopeVisibleAdminIds(): ?array { return $this->visibleIds; }
}
$assertions = 0;
function assistantNameExpect(bool $ok, string $message): void
{
global $assertions;
if (!$ok) {
throw new RuntimeException('FAIL: ' . $message);
}
$assertions++;
}
// Input order is already the normal no-appointment descending-id order.
AssistantNameQuery::$tables = [
'tcm_diagnosis' => [
['id' => 109, 'assistant_id' => 41],
['id' => 108, 'assistant_id' => '42'],
['id' => 107, 'assistant_id' => 41],
['id' => 106, 'assistant_id' => null],
['id' => 105, 'assistant_id' => 0],
['id' => 104, 'assistant_id' => 404],
['id' => 103, 'assistant_id' => 43],
['id' => 102, 'assistant_id' => 44],
['id' => 101, 'assistant_id' => -1],
],
'admin' => [
['id' => 41, 'name' => ' 林医助 ', 'delete_time' => null, 'disable' => 0, 'account' => 'private-41'],
['id' => 42, 'name' => '王医助', 'delete_time' => null, 'disable' => 1, 'account' => 'private-42'],
['id' => 43, 'name' => '已删除医助', 'delete_time' => 123, 'disable' => 0],
['id' => 44, 'name' => ' ', 'delete_time' => null, 'disable' => 0],
['id' => 45, 'name' => '未关联人员', 'delete_time' => null, 'disable' => 0],
],
];
$lists = new AssistantNameLists();
$rows = $lists->lists();
assistantNameExpect(array_column($rows, 'assistant_name', 'id') === [
109 => '林医助', 108 => '王医助', 107 => '林医助', 106 => '', 105 => '',
104 => '', 103 => '', 102 => '', 101 => '',
], 'each row gets the assigned name; unassigned, missing, deleted, blank and invalid assignments remain empty');
assistantNameExpect(AssistantNameQuery::$adminReads === [[
'conditions' => [['id', 'in', [41, 42, 404, 43, 44]], ['delete_time', 'null', null]],
'field' => 'name', 'key' => 'id',
]], 'one batch reads only positive unique assigned ids and the name/id projection');
assistantNameExpect($rows[1]['assistant_id'] === '42' && $rows[1]['assistant_name'] === '王医助',
'disabled but still assigned staff retain their name without changing the original id');
assistantNameExpect(!str_contains(json_encode($rows, JSON_UNESCAPED_UNICODE), 'private-')
&& !str_contains(json_encode($rows, JSON_UNESCAPED_UNICODE), '未关联人员'),
'enrichment exposes neither admin account fields nor unrelated names');
assistantNameExpect($lists->count() === count($rows), 'enrichment does not change total count');
AssistantNameQuery::$adminReads = [];
$scoped = new AssistantNameLists([41]);
$rows = $scoped->lists();
assistantNameExpect(array_column($rows, 'id') === [109, 107] && $scoped->count() === 2,
'real data-scope filtering remains active for lists and count');
assistantNameExpect(AssistantNameQuery::$adminReads[0]['conditions'][0] === ['id', 'in', [41]],
'names outside the authorized rows are never queried');
AssistantNameQuery::$adminReads = [];
$page = new AssistantNameLists(null, [], 1, 1);
$rows = $page->lists();
assistantNameExpect(array_column($rows, 'id') === [108] && $rows[0]['assistant_name'] === '王医助'
&& $page->count() === 9, 'pagination and count are preserved');
assistantNameExpect(AssistantNameQuery::$adminReads[0]['conditions'][0] === ['id', 'in', [42]],
'only names on the requested page are queried');
AssistantNameQuery::$tables['admin_role'] = [['admin_id' => 41, 'role_id' => 2]];
AssistantNameQuery::$adminReads = [];
$self = new AssistantNameLists(null, [], 0, 100, 41);
assistantNameExpect(array_column($self->lists(), 'id') === [109, 107] && $self->count() === 2,
'assistant-role self filtering is unchanged');
assistantNameExpect(AssistantNameQuery::$adminReads[0]['conditions'][0] === ['id', 'in', [41]],
'assistant-role name hydration uses the self-filtered result only');
AssistantNameQuery::$tables['admin_role'] = [];
foreach ([new AssistantNameLists([]), new AssistantNameLists(null, [], 50, 10)] as $empty) {
AssistantNameQuery::$adminReads = [];
assistantNameExpect($empty->lists() === [] && AssistantNameQuery::$adminReads === [],
'empty authorization scope or an empty page does not query admin data');
}
AssistantNameQuery::$adminReads = [];
$pending = new AssistantNameLists(null, ['pending_assign' => 1]);
$rows = $pending->lists();
assistantNameExpect(array_column($rows, 'id') === [106, 105] && $pending->count() === 2
&& array_column($rows, 'assistant_name') === ['', ''] && AssistantNameQuery::$adminReads === [],
'unassigned-only lists have an explicit empty name and need no admin query');
echo "Diagnosis assistant names: {$assertions} assertions passed (no DB or network)\n";
@@ -0,0 +1,252 @@
<?php
declare(strict_types=1);
// Execute the real middleware, department controller and tree filtering logic.
// Only authentication storage, department rows and scope lookup are in memory.
namespace app\adminapi\logic {
final class LoginLogic
{
public static function adminMustBindWorkWechat(array $adminInfo): bool { return false; }
}
}
namespace app\common\cache {
final class AdminAuthCache
{
public static array $permissions = [];
public static array $allUris = [];
public static array $actors = [];
public static int $allUriReads = 0;
public function __construct(int $adminId) { self::$actors[] = $adminId; }
public function getAdminUri(): array { return self::$permissions; }
public function getAllUri(): array { self::$allUriReads++; return self::$allUris; }
}
}
namespace app\common\service {
final class JsonService
{
public static function fail(string $msg = 'fail', array $data = [], int $code = 0, int $show = 1): array
{
return compact('code', 'show', 'msg', 'data');
}
public static function data(array $data): array
{
return ['code' => 1, 'show' => 0, 'msg' => '', 'data' => $data];
}
}
}
namespace app\common\model\dept {
final class Dept
{
public static array $rows = [];
public static int $reads = 0;
public static function order(array $order): self { self::$reads++; return new self(); }
public function select(): self { return $this; }
public function toArray(): array { return self::$rows; }
}
}
namespace app\common\service\DataScope {
final class DataScopeService
{
public static ?array $allowed = [12 => true];
public static array $actors = [];
public static function isEnabled(): bool { return true; }
public static function getAllowedDeptIdSet(int $adminId, array $adminInfo): ?array
{
self::$actors[] = [$adminId, $adminInfo];
return self::$allowed;
}
}
}
namespace app\adminapi\http\middleware {
function request(): object { return $GLOBALS['diagnosis_department_request']; }
function env(...$arguments): never { throw new \RuntimeException('This test must not read environment configuration'); }
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use app\adminapi\controller\dept\DeptController;
use app\adminapi\http\middleware\AuthMiddleware;
use app\common\cache\AdminAuthCache;
use app\common\model\dept\Dept;
use app\common\service\DataScope\DataScopeService;
use app\common\service\JsonService;
final class DiagnosisDepartmentRequest
{
public array $adminInfo;
public object $controllerObject;
public string $controllerName = 'dept.Dept';
public string $actionName = 'all';
public function __construct(public array $query = [], public string $method = 'GET',
public array $body = [], bool $root = false)
{
$this->adminInfo = ['admin_id' => 91, 'root' => $root ? 1 : 0, 'role_id' => [7],
'login_ip' => '192.0.2.91', 'work_wechat_userid' => 'synthetic-doctor-91'];
}
public function get(?string $name = null, $default = null)
{
return $name === null ? $this->query : ($this->query[$name] ?? $default);
}
public function param(string $name, $default = null)
{
return $this->body[$name] ?? $this->query[$name] ?? $default;
}
public function isGet(): bool { return $this->method === 'GET'; }
public function controller(): string { return $this->controllerName; }
public function action(): string { return $this->actionName; }
public function ip(): string { return '192.0.2.91'; }
}
final class DiagnosisDepartmentController extends DeptController
{
public function __construct(DiagnosisDepartmentRequest $request)
{
$this->request = $request;
$this->adminId = $request->adminInfo['admin_id'];
$this->adminInfo = $request->adminInfo;
}
protected function data($data) { return JsonService::data($data); }
}
$assertions = 0;
function departmentPermissionExpect(bool $ok, string $label): void
{
global $assertions;
if (!$ok) { throw new RuntimeException('FAIL: ' . $label); }
$assertions++;
}
function departmentPermissionInvoke(DiagnosisDepartmentRequest $request, array $permissions,
?array $registered = null): array
{
AdminAuthCache::$permissions = $permissions;
AdminAuthCache::$allUris = $registered ?? [
'dept.dept/all', 'dept.dept/lists', 'dept.dept/leaderDept', 'dept.dept/detail',
'dept.dept/add', 'dept.dept/edit', 'dept.dept/delete', 'dept.jobs/all',
];
AdminAuthCache::$actors = [];
AdminAuthCache::$allUriReads = 0;
DataScopeService::$actors = [];
Dept::$reads = 0;
$GLOBALS['diagnosis_department_request'] = $request;
$controller = new DiagnosisDepartmentController($request);
$request->controllerObject = $controller;
return (new AuthMiddleware())->handle($request, static function () use ($request, $controller): array {
if (strtolower($request->controller() . '/' . $request->action()) === 'dept.dept/all') {
return $controller->all();
}
// A sentinel verifies function-level grants without performing CRUD writes.
return ['code' => 1, 'continued' => true];
});
}
Dept::$rows = [
['id' => 10, 'pid' => 0, 'name' => '共享祖先'],
['id' => 11, 'pid' => 10, 'name' => '未授权同级'],
['id' => 12, 'pid' => 10, 'name' => '授权部门'],
['id' => 20, 'pid' => 0, 'name' => '其他部门'],
];
$scopedTree = [[
'id' => 10, 'pid' => 0, 'name' => '共享祖先', 'level' => 0,
'children' => [['id' => 12, 'pid' => 10, 'name' => '授权部门', 'level' => 1, 'children' => []]],
]];
foreach ([1, '1'] as $scope) {
foreach (['tcm.diagnosis/lists', 'TCM.DIAGNOSIS/LISTS'] as $permission) {
$request = new DiagnosisDepartmentRequest(['apply_data_scope' => $scope]);
$request->controllerName = 'DePt.DePt';
$request->actionName = 'AlL';
$result = departmentPermissionInvoke($request, [$permission]);
departmentPermissionExpect($result === ['code' => 1, 'show' => 0, 'msg' => '', 'data' => $scopedTree],
'exact patient-list grant returns the real scoped tree and original envelope');
departmentPermissionExpect(DataScopeService::$actors === [[91, $request->adminInfo]],
'controller passes the authenticated identity to data scope');
departmentPermissionExpect(Dept::$reads === 1 && AdminAuthCache::$allUriReads === 0,
'read-only alias does not need a department management grant');
}
}
$invalidQueries = [[], ['apply_data_scope' => null]];
foreach ([0, '0', '', '01', '1x', '1.0', ' 1', '1 ', true, false, 1.0, 2, -1,
[], ['1'], new stdClass()] as $invalid) {
$invalidQueries[] = ['apply_data_scope' => $invalid];
}
foreach ($invalidQueries as $query) {
$result = departmentPermissionInvoke(new DiagnosisDepartmentRequest($query), ['tcm.diagnosis/lists']);
departmentPermissionExpect($result['code'] === 0, 'missing or malformed scope cannot acquire the alias ' . json_encode($query));
departmentPermissionExpect(Dept::$reads === 0 && DataScopeService::$actors === [],
'invalid scope is rejected before any department read');
}
foreach ([[], ['tcm.diagnosis/detail'], ['tcm.diagnosis/edit'], ['tcm.diagnosis/listsOther'],
['dept.dept/lists']] as $permissions) {
$result = departmentPermissionInvoke(new DiagnosisDepartmentRequest(['apply_data_scope' => '1']), $permissions);
departmentPermissionExpect($result['code'] === 0 && Dept::$reads === 0,
'unrelated permissions do not acquire the patient-list alias ' . json_encode($permissions));
}
foreach (['POST', 'PUT', 'DELETE', 'HEAD'] as $method) {
$result = departmentPermissionInvoke(new DiagnosisDepartmentRequest(['apply_data_scope' => '1'], $method),
['tcm.diagnosis/lists']);
departmentPermissionExpect($result['code'] === 0 && Dept::$reads === 0, 'alias denies HTTP method ' . $method);
}
foreach (['GET', 'POST'] as $method) {
$result = departmentPermissionInvoke(new DiagnosisDepartmentRequest([], $method, ['apply_data_scope' => '1']),
['tcm.diagnosis/lists']);
departmentPermissionExpect($result['code'] === 0 && Dept::$reads === 0,
'request body cannot enable GET-only scope on ' . $method);
}
foreach (['lists', 'leaderDept', 'detail', 'add', 'edit', 'delete'] as $action) {
foreach (['GET', 'POST'] as $method) {
$request = new DiagnosisDepartmentRequest(['apply_data_scope' => '1'], $method);
$request->actionName = $action;
$result = departmentPermissionInvoke($request, ['tcm.diagnosis/lists']);
departmentPermissionExpect($result['code'] === 0 && Dept::$reads === 0,
'patient-list grant never authorizes department action ' . $method . ' ' . $action);
}
$request = new DiagnosisDepartmentRequest([], 'POST');
$request->actionName = $action;
$result = departmentPermissionInvoke($request, ['dept.dept/' . $action]);
departmentPermissionExpect(($result['continued'] ?? false) === true,
'original exact department permission still authorizes ' . $action);
}
$otherController = new DiagnosisDepartmentRequest(['apply_data_scope' => '1']);
$otherController->controllerName = 'dept.Jobs';
$result = departmentPermissionInvoke($otherController, ['tcm.diagnosis/lists']);
departmentPermissionExpect($result['code'] === 0, 'alias is limited to the exact department controller');
$originalGrant = departmentPermissionInvoke(new DiagnosisDepartmentRequest(), ['dept.dept/all']);
departmentPermissionExpect($originalGrant['code'] === 1 && count($originalGrant['data']) === 2
&& count($originalGrant['data'][0]['children']) === 2 && DataScopeService::$actors === [],
'original all-departments permission retains its unscoped response');
$originalScoped = departmentPermissionInvoke(new DiagnosisDepartmentRequest(['apply_data_scope' => 1]), ['dept.dept/all']);
departmentPermissionExpect($originalScoped['data'] === $scopedTree && count(DataScopeService::$actors) === 1,
'original department grant can still request a scoped tree');
$root = departmentPermissionInvoke(new DiagnosisDepartmentRequest([], 'GET', [], true), []);
departmentPermissionExpect($root['code'] === 1 && count($root['data']) === 2 && AdminAuthCache::$actors === [],
'root retains the existing middleware bypass and full tree');
DataScopeService::$allowed = null;
$rootScoped = departmentPermissionInvoke(new DiagnosisDepartmentRequest(['apply_data_scope' => 1], 'GET', [], true), []);
departmentPermissionExpect($rootScoped['data'] === $root['data'] && count(DataScopeService::$actors) === 1,
'root scoped requests still execute the controller data-scope contract');
DataScopeService::$allowed = [];
$empty = departmentPermissionInvoke(new DiagnosisDepartmentRequest(['apply_data_scope' => '1']), ['tcm.diagnosis/lists']);
departmentPermissionExpect($empty === ['code' => 1, 'show' => 0, 'msg' => '', 'data' => []],
'authorized empty scope remains a successful empty tree, never a full-data fallback');
$legacy = departmentPermissionInvoke(new DiagnosisDepartmentRequest(), [], []);
departmentPermissionExpect($legacy['code'] === 1 && count($legacy['data']) === 2 && AdminAuthCache::$allUriReads === 1,
'unmatched requests continue through the existing unregistered-route policy unchanged');
echo "Diagnosis department filter permission: {$assertions} assertions passed (no DB or network)\n";
}