330 lines
19 KiB
PHP
330 lines
19 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
namespace app\service\shared;
|
|
|
|
use app\exception\ApiError;
|
|
use app\service\Input;
|
|
use app\service\group\GroupService;
|
|
|
|
/** Maps the small administration surface without changing original persistence semantics. */
|
|
final class SharedRecordsService
|
|
{
|
|
private array $readCache = [];
|
|
private const ADMIN_PRESERVE = ['avatar', 'multipoint_login', 'jobs_id', 'gender', 'age', 'phone', 'title',
|
|
'department', 'specialty', 'education', 'experience', 'honors', 'license_no', 'qualification_images',
|
|
'enable_image_consult', 'enable_video_consult', 'enable_charge'];
|
|
|
|
public function __construct(private readonly SourceApiClient $source, private readonly string $token, private readonly array $actor,
|
|
private readonly ?GroupService $group = null)
|
|
{
|
|
}
|
|
|
|
public function dispatch(string $operation, array $data = [], array $query = []): array
|
|
{
|
|
if ($operation === 'options') { return $this->options(); }
|
|
if (!preg_match('/^(admin|role|menu|dept)\.(lists|add|edit|delete)$/D', $operation, $match)) {
|
|
throw new ApiError(404, '接口不存在');
|
|
}
|
|
[$all, $kind, $action] = $match;
|
|
$permission = ($kind === 'dept' ? 'dept.dept' : 'auth.' . $kind) . '/' . $action;
|
|
if (!$this->can($permission)) { throw new ApiError(403, '权限不足'); }
|
|
if ($action === 'lists') {
|
|
if ($kind === 'admin' || $kind === 'role') { return $this->paged($kind, $query); }
|
|
Input::only($query, []);
|
|
$tree = $kind === 'menu' ? $this->read('auth.menu/lists')['lists'] ?? null : $this->read('dept.dept/lists');
|
|
if (!is_array($tree)) { throw new ApiError(502, '共享数据源响应异常'); }
|
|
return SourceMapper::tree($tree, $kind === 'menu' ? SourceMapper::menu(...) : SourceMapper::dept(...));
|
|
}
|
|
if ($action === 'delete') { return $this->delete($kind, $data); }
|
|
return match ($kind) {
|
|
'admin' => $this->saveAdmin($action, $data),
|
|
'role' => $this->saveRole($action, $data),
|
|
default => $this->saveTree($kind, $action, $data),
|
|
};
|
|
}
|
|
|
|
private function can(string $permission): bool
|
|
{
|
|
return SourceMapper::can($this->actor['source_permissions'] ?? $this->actor['permissions'], $permission);
|
|
}
|
|
|
|
private function any(array $permissions): bool
|
|
{
|
|
foreach ($permissions as $permission) { if ($this->can($permission)) { return true; } }
|
|
return false;
|
|
}
|
|
|
|
private function read(string $path, array $query = []): array
|
|
{
|
|
$key = $path . '?' . http_build_query($query);
|
|
return $this->readCache[$key] ??= $this->source->request('GET', $path, $query, $this->token);
|
|
}
|
|
|
|
private function write(string $path, array $data): array
|
|
{
|
|
$this->source->request('POST', $path, $data, $this->token);
|
|
// 普通写入无需后读;成功后的详情读取失败不能掩盖已完成的修改。
|
|
return [];
|
|
}
|
|
|
|
private function options(): array
|
|
{
|
|
$admin = $this->any(['auth.admin/add', 'auth.admin/edit']);
|
|
$roles = $admin ? $this->mapRoles($this->read('auth.role/all')) : [];
|
|
$depts = $admin || $this->any(['dept.dept/lists', 'dept.dept/add', 'dept.dept/edit'])
|
|
? SourceMapper::tree($this->read('dept.dept/all'), SourceMapper::dept(...)) : [];
|
|
$roleMenus = $this->any(['auth.role/lists', 'auth.role/add', 'auth.role/edit']);
|
|
$menus = $roleMenus || $this->any(['auth.menu/lists', 'auth.menu/add', 'auth.menu/edit'])
|
|
? SourceMapper::tree($this->grantMenuTree(), SourceMapper::menu(...)) : [];
|
|
foreach ($menus as &$menu) { $menu += ['company_id' => 1, 'company_name' => '互联网医院', 'native' => false]; }
|
|
unset($menu);
|
|
if ($roleMenus && $this->group) { $menus = array_merge($menus, $this->group->roleMenuTree($this->actor)); }
|
|
return ['roles' => $roles, 'depts' => $depts, 'menus' => $menus];
|
|
}
|
|
|
|
private function grantMenuTree(): array
|
|
{
|
|
$tree = $this->can('auth.menu/lists') ? $this->read('auth.menu/lists')['lists'] ?? null : $this->read('auth.menu/all');
|
|
if (!is_array($tree)) { throw new ApiError(502, '共享数据源响应异常'); }
|
|
SourceMapper::sourceMenuIds(array_column(SourceMapper::flatten($tree), 'id'));
|
|
return $tree;
|
|
}
|
|
|
|
private function mapRoles(array $rows): array
|
|
{
|
|
$roles = array_map(SourceMapper::role(...), $rows);
|
|
if (!$this->group || $roles === []) { return $roles; }
|
|
$grants = $this->group->roleNativeMenuIdsForRoles($this->actor, array_column($roles, 'id'));
|
|
foreach ($roles as &$role) {
|
|
$role['menu_id'] = array_values(array_unique(array_merge($role['menu_id'], $grants[$role['id']] ?? [])));
|
|
}
|
|
unset($role);
|
|
return $roles;
|
|
}
|
|
|
|
private function paged(string $kind, array $query): array
|
|
{
|
|
[$page, $size, $keyword, $disable] = Input::page($query);
|
|
$rows = $this->allPages('auth.' . $kind . '/lists');
|
|
$rows = $kind === 'admin' ? array_map(SourceMapper::user(...), $rows) : $this->mapRoles($rows);
|
|
$needle = mb_strtolower($keyword);
|
|
$rows = array_values(array_filter($rows, static function (array $row) use ($kind, $needle, $disable): bool {
|
|
if ($disable !== null && $row['disable'] !== $disable) { return false; }
|
|
return $needle === '' || str_contains(mb_strtolower($row['name']), $needle)
|
|
|| ($kind === 'admin' && str_contains(mb_strtolower($row['account']), $needle));
|
|
}));
|
|
return ['lists' => array_slice($rows, ($page - 1) * $size, $size), 'count' => count($rows),
|
|
'page_no' => $page, 'page_size' => $size];
|
|
}
|
|
|
|
private function allPages(string $path): array
|
|
{
|
|
$result = [];
|
|
$seen = [];
|
|
for ($page = 1; $page <= 100; $page++) {
|
|
$data = $this->read($path, ['page_no' => $page, 'page_size' => 100]);
|
|
$rows = $data['lists'] ?? null;
|
|
$count = $data['count'] ?? null;
|
|
if (!is_array($rows) || !array_is_list($rows) || (!is_int($count) && !(is_string($count) && ctype_digit($count)))
|
|
|| (int) $count < 0 || (int) $count > 10000 || count($rows) > 100) {
|
|
throw new ApiError(502, '共享数据源分页响应异常');
|
|
}
|
|
foreach ($rows as $row) {
|
|
$id = is_array($row) ? (int) ($row['id'] ?? 0) : 0;
|
|
if ($id < 1 || isset($seen[$id])) { throw new ApiError(502, '共享数据源分页已变化,请重试'); }
|
|
$seen[$id] = true;
|
|
$result[] = $row;
|
|
}
|
|
if (count($result) >= (int) $count) { return $result; }
|
|
if ($rows === []) { throw new ApiError(502, '共享数据源分页响应异常'); }
|
|
}
|
|
throw new ApiError(502, '共享数据数量超出单次读取范围');
|
|
}
|
|
|
|
private function detail(string $kind, int $id): array
|
|
{
|
|
$path = ($kind === 'dept' ? 'dept.dept' : 'auth.' . $kind) . '/detail';
|
|
$row = $this->read($path, ['id' => $id]);
|
|
if ((int) ($row['id'] ?? 0) !== $id) { throw new ApiError(404, '记录不存在'); }
|
|
return $row;
|
|
}
|
|
|
|
private function saveAdmin(string $action, array $data): array
|
|
{
|
|
Input::only($data, $action === 'edit' ? ['id', 'account', 'name', 'password', 'disable', 'role_id', 'dept_id']
|
|
: ['account', 'name', 'password', 'disable', 'role_id', 'dept_id']);
|
|
$id = $action === 'edit' ? Input::integer($data['id'] ?? null) : 0;
|
|
$old = $id ? $this->detail('admin', $id) : [];
|
|
if ((int) ($old['root'] ?? 0) === 1 && (int) $this->actor['is_root'] !== 1) {
|
|
throw new ApiError(403, '只有根管理员可以编辑根账号');
|
|
}
|
|
$source = array_replace($old, $data);
|
|
$payload = ['account' => Input::text($source['account'] ?? null, '账号', 1, 32),
|
|
'name' => Input::text($source['name'] ?? null, '名称', 1, 16),
|
|
'disable' => Input::integer($source['disable'] ?? 0, '状态', 0, 1)];
|
|
if ($payload['disable'] === 1 && ((int) ($old['root'] ?? 0) === 1 || $id === $this->actor['id'])) {
|
|
throw new ApiError(409, '不能停用自己或根账号');
|
|
}
|
|
$roles = Input::ids($source['role_id'] ?? [], '角色');
|
|
$depts = Input::ids($source['dept_id'] ?? [], '部门');
|
|
if ($roles === [] && (int) ($old['root'] ?? 0) !== 1) { throw new ApiError(422, '请选择角色'); }
|
|
$this->references($roles, $this->read('auth.role/all'), SourceMapper::ids($old['role_id'] ?? []), '角色');
|
|
$this->references($depts, SourceMapper::flatten($this->read('dept.dept/all')), SourceMapper::ids($old['dept_id'] ?? []), '部门');
|
|
$payload += ['role_id' => $roles, 'dept_id' => $depts, 'multipoint_login' => 1, 'jobs_id' => []];
|
|
foreach (self::ADMIN_PRESERVE as $key) { if (array_key_exists($key, $old)) { $payload[$key] = $old[$key]; } }
|
|
if (!$id || (array_key_exists('password', $data) && $data['password'] !== '')) {
|
|
$payload['password'] = SharedIdentityService::password($data['password'] ?? null);
|
|
$payload['password_confirm'] = $payload['password'];
|
|
}
|
|
if ($id) { $payload['id'] = $id; }
|
|
return $this->write('auth.admin/' . $action, $payload);
|
|
}
|
|
|
|
private function saveRole(string $action, array $data): array
|
|
{
|
|
Input::only($data, $action === 'edit' ? ['id', 'name', 'desc', 'sort', 'disable', 'menu_id', 'data_scope']
|
|
: ['name', 'desc', 'sort', 'disable', 'menu_id', 'data_scope']);
|
|
if (array_key_exists('disable', $data) && Input::integer($data['disable'], '状态', 0, 1) !== 0) {
|
|
throw new ApiError(422, '原系统不支持停用角色');
|
|
}
|
|
$id = $action === 'edit' ? Input::integer($data['id'] ?? null) : 0;
|
|
$old = $id ? $this->detail('role', $id) : [];
|
|
$values = array_replace($old, $data);
|
|
$payload = ['name' => Input::text($values['name'] ?? null, '角色名称', 1, 64),
|
|
'desc' => Input::text($values['desc'] ?? '', '角色说明', 0, 500),
|
|
'sort' => Input::integer($values['sort'] ?? 0, '排序', 0, 1000000),
|
|
'data_scope' => Input::integer($values['data_scope'] ?? 1, '数据范围', 1, 4)];
|
|
$oldMenus = SourceMapper::sourceMenuIds($old['menu_id'] ?? []);
|
|
$syncNative = array_key_exists('menu_id', $data);
|
|
$nativeMenus = [];
|
|
if (array_key_exists('menu_id', $data)) {
|
|
$requested = Input::ids($data['menu_id'], '菜单');
|
|
$menus = array_values(array_filter($requested, static fn (int $id): bool => $id < SourceMapper::NATIVE_MENU_ID_BASE));
|
|
$nativeMenus = array_values(array_filter($requested, static fn (int $id): bool => $id >= SourceMapper::NATIVE_MENU_ID_BASE));
|
|
if ($nativeMenus !== [] && !$this->group) { throw new ApiError(422, '集团菜单授权尚未启用'); }
|
|
// 必须在撤回旧授权或写医院前验证所有目标,保留高段与医院编号的隔离。
|
|
$this->group?->validateRoleNativeMenuIds($this->actor, $nativeMenus, $id ?: null);
|
|
$visible = array_map('intval', array_column(SourceMapper::flatten($this->grantMenuTree()), 'id'));
|
|
if (array_diff($menus, $visible, $oldMenus) !== []) { throw new ApiError(422, '菜单不存在或不可分配'); }
|
|
// menu/all omits disabled nodes. An editor cannot revoke grants it was unable to see.
|
|
$menus = array_values(array_unique(array_merge($menus, array_diff($oldMenus, $visible))));
|
|
} else { $menus = $oldMenus; }
|
|
$payload['menu_id'] = $menus;
|
|
if ($id) { $payload['id'] = $id; }
|
|
if (!$this->group || !$syncNative) { return $this->write('auth.role/' . $action, $payload); }
|
|
|
|
// 两套存储没有共同事务:先收回本地旧授权,避免源保存失败后保留新增权限。
|
|
if ($id) { $this->group->clearRoleNativeMenus($this->actor, $id); }
|
|
try {
|
|
$result = $this->source->request('POST', 'auth.role/' . $action, $payload, $this->token);
|
|
} catch (ApiError $error) {
|
|
throw new ApiError($error->status, $error->getMessage() . ($id ? ';集团菜单授权已撤回,请检查角色后重新保存' : ''));
|
|
} catch (\Throwable $error) {
|
|
throw new ApiError(502, '医院角色保存失败' . ($id ? ',集团菜单授权已撤回,请检查后重试' : ',请稍后重试'));
|
|
}
|
|
if ($nativeMenus === []) { return []; }
|
|
if (!$id) {
|
|
// 只接受本次源写入返回的主键;名称或列表差集不能证明并发创建的归属。
|
|
$created = $result['id'] ?? null;
|
|
if ((!is_int($created) && !(is_string($created) && ctype_digit($created)))
|
|
|| filter_var($created, FILTER_VALIDATE_INT) === false || (int) $created < 1) {
|
|
throw new ApiError(502, '医院角色已创建,但原系统未返回角色编号,集团菜单未保存;请刷新角色列表后编辑授权');
|
|
}
|
|
$id = (int) $created;
|
|
}
|
|
try {
|
|
$this->group->replaceRoleNativeMenus($this->actor, $id, $nativeMenus);
|
|
} catch (\Throwable $error) {
|
|
try { $this->group->clearRoleNativeMenus($this->actor, $id); }
|
|
catch (\Throwable $cleanupError) { throw new ApiError(502, '医院角色已保存,集团菜单授权保存及回收失败,请立即检查角色授权'); }
|
|
throw new ApiError(502, '医院角色已保存,集团菜单授权未保存且已撤回,请检查后重新保存');
|
|
}
|
|
return [];
|
|
}
|
|
|
|
private function saveTree(string $kind, string $action, array $data): array
|
|
{
|
|
$allowed = ['pid', 'name', 'sort', 'disable'];
|
|
if ($kind === 'menu') { $allowed = [...$allowed, 'type', 'paths', 'component', 'perms', 'icon', 'is_show', 'is_cache', 'selected', 'params']; }
|
|
Input::only($data, $action === 'edit' ? [...$allowed, 'id'] : $allowed);
|
|
$id = $action === 'edit' ? Input::integer($data['id'] ?? null, 'id', 1,
|
|
$kind === 'menu' ? SourceMapper::NATIVE_MENU_ID_BASE - 1 : PHP_INT_MAX) : 0;
|
|
$old = $id ? $this->detail($kind, $id) : [];
|
|
$values = array_replace($old, $data);
|
|
$pid = Input::integer($values['pid'] ?? 0, '上级编号', 0,
|
|
$kind === 'menu' ? SourceMapper::NATIVE_MENU_ID_BASE - 1 : PHP_INT_MAX);
|
|
if ($kind === 'dept' && $id && (int) $old['pid'] === 0) { $pid = 0; }
|
|
if ($kind === 'dept' && !$id && $pid === 0) { throw new ApiError(422, '请在现有部门下新增,原系统不支持新增顶级部门'); }
|
|
$this->validateParent($kind, $id, $pid);
|
|
$payload = ['pid' => $pid, 'name' => Input::text($values['name'] ?? null, '名称', 1, 30),
|
|
'sort' => Input::integer($values['sort'] ?? 0, '排序', 0, 1000000)];
|
|
$disable = Input::integer($data['disable'] ?? ($kind === 'menu' ? $old['is_disable'] ?? 0 : 1 - (int) ($old['status'] ?? 1)), '状态', 0, 1);
|
|
if ($kind === 'menu') {
|
|
$type = Input::text($values['type'] ?? null, '菜单类型', 1, 1);
|
|
if (!in_array($type, ['M', 'C', 'A'], true)) { throw new ApiError(422, '菜单类型必须为M/C/A'); }
|
|
if ($type === 'A' && $pid === 0) { throw new ApiError(422, '按钮必须归属目录或页面'); }
|
|
$payload += ['type' => $type, 'is_disable' => $disable,
|
|
'is_show' => Input::integer($values['is_show'] ?? 1, '显示状态', 0, 1),
|
|
'is_cache' => Input::integer($values['is_cache'] ?? 0, '缓存状态', 0, 1)];
|
|
foreach (['icon' => 100, 'perms' => 100, 'paths' => 200, 'component' => 200, 'selected' => 200, 'params' => 200] as $key => $max) {
|
|
$payload[$key] = Input::text($values[$key] ?? '', $key, 0, $max);
|
|
}
|
|
if ($id && $type === 'A') {
|
|
$children = SourceMapper::flatten($this->can('auth.menu/lists') ? $this->read('auth.menu/lists')['lists'] ?? [] : $this->read('auth.menu/all'));
|
|
foreach ($children as $child) { if ((int) ($child['pid'] ?? 0) === $id) { throw new ApiError(409, '有子菜单的节点不能改为按钮'); } }
|
|
}
|
|
} else {
|
|
$payload += ['status' => 1 - $disable, 'leader' => (string) ($old['leader'] ?? ''), 'mobile' => (string) ($old['mobile'] ?? '')];
|
|
}
|
|
if ($id) { $payload['id'] = $id; }
|
|
return $this->write(($kind === 'dept' ? 'dept.dept' : 'auth.menu') . '/' . $action, $payload);
|
|
}
|
|
|
|
private function validateParent(string $kind, int $id, int $pid): void
|
|
{
|
|
$seen = [];
|
|
while ($pid > 0) {
|
|
if ($pid === $id || isset($seen[$pid]) || count($seen) >= 64) { throw new ApiError(422, '上级节点不能是自己或后代,且层级不能超过64层'); }
|
|
$seen[$pid] = true;
|
|
$parent = $this->detail($kind, $pid);
|
|
if ($kind === 'menu' && ($parent['type'] ?? '') === 'A') { throw new ApiError(422, '按钮不能作为上级菜单'); }
|
|
$pid = (int) ($parent['pid'] ?? 0);
|
|
}
|
|
}
|
|
|
|
private function references(array $ids, array $rows, array $existing, string $label): void
|
|
{
|
|
$byId = [];
|
|
foreach ($rows as $row) { if (is_array($row)) { $byId[(int) ($row['id'] ?? 0)] = $row; } }
|
|
foreach ($ids as $id) {
|
|
if (!isset($byId[$id])) { throw new ApiError(422, $label . '不存在'); }
|
|
if (isset($byId[$id]['status']) && (int) $byId[$id]['status'] !== 1 && !in_array($id, $existing, true)) {
|
|
throw new ApiError(422, '不能新增关联停用部门');
|
|
}
|
|
}
|
|
}
|
|
|
|
private function delete(string $kind, array $data): array
|
|
{
|
|
Input::only($data, ['id']);
|
|
$id = Input::integer($data['id'] ?? null, 'id', 1,
|
|
$kind === 'menu' ? SourceMapper::NATIVE_MENU_ID_BASE - 1 : PHP_INT_MAX);
|
|
if ($kind === 'admin') {
|
|
if ($id === $this->actor['id']) { throw new ApiError(409, '不能删除自己'); }
|
|
$row = $this->detail('admin', $id);
|
|
if ((int) ($row['root'] ?? 0) === 1) { throw new ApiError(409, '不能删除根账号'); }
|
|
}
|
|
if ($kind === 'dept') {
|
|
$row = $this->detail('dept', $id);
|
|
if ((int) ($row['pid'] ?? 0) === 0) { throw new ApiError(409, '不能删除顶级部门'); }
|
|
}
|
|
if ($kind === 'role') { $this->detail('role', $id); }
|
|
$result = $this->write(($kind === 'dept' ? 'dept.dept' : 'auth.' . $kind) . '/delete', ['id' => $id]);
|
|
if ($kind === 'role' && $this->group) {
|
|
try { $this->group->clearRoleNativeMenus($this->actor, $id); }
|
|
catch (\Throwable $error) { throw new ApiError(502, '医院角色已删除,集团菜单授权清理失败,请检查后重试'); }
|
|
}
|
|
return $result;
|
|
}
|
|
}
|