Files
YwxAppThink/app/backend/controller/Group.php
T

313 lines
9.8 KiB
PHP

<?php
/*
* @Author: YwxApp <ywx@ywxapp.cn>
* @Date: 2026-04-29 02:32:33
* @LastEditors: YwxApp <ywx@ywxapp.cn>
* @LastEditTime: 2026-07-21 22:31:51
* @Description:
* @FilePath: \ywxapp_dev\app\backend\controller\Group.php
* @CustomString: Copyright (c) 2026 YwxApp
*/
namespace app\backend\controller;
use think\facade\Db;
use think\facade\View;
use think\Request;
use ywxapp\model\MemberGroup as GroupModel;
use ywxapp\model\MemberGroupRule as GroupRuleModel;
use ywxapp\model\MemberRule as RuleModel;
use ywxapp\controller\BackendBase;
/**
* Group 类
*
* @author ywxapp <admin@ywxapp.cn>
*/
class Group extends BackendBase
{
/**
* Summary of needLogin
* @var array
*/
protected $noNeedLogin = [];
/**
* Summary of needRight
* @var array
*/
protected $noNeedVerify = [];
/**
* 控制器初始化 initialize
* @return void
*/
protected function initialize()
{}
/**
* 显示资源列表
*
* @param \think\Request $request
* @return \think\Response
*/
public function index()
{
$page = $this->request->param('page', 1);
$size = $this->request->param('size', 15);
if ($this->request->isAjax()) {
$data = GroupModel::paginate([
'page' => $page,
'list_rows' => $size,
]);
$this->result->success($data->items());
}
View::assign('title', '登录');
return View::fetch();
}
/**
* 数据创建
*
* @param Request $request
* @return \think\Response
*/
public function create()
{
if ($this->request->isAjax()) {
$roles = GroupModel::where('status', 1)->select();
$this->result->success(['roles' => $roles]);
}
View::assign('title', '登录');
return View::fetch('group/index');
}
/**
* 数据保存
*
* @param Request $request
* @return \think\Response
*/
public function save()
{
$params = $this->request->only(['title', 'name', 'status', 'description'], 'post');
try {
validate(RoleValidate::class)->check($params);
Db::transaction(function () use ($params) {
$data = GroupModel::create($params);
});
$this->result->success();
} catch (ValidateException $e) {
$this->result->error($e->getMessage());
} catch (DbException $e) {
$this->result->error($e->getMessage(), 2);
}
}
/**
* 数据编辑
*
* @param Request $request
* @param int|null $ids
* @return \think\Response
*/
public function edit($id = null)
{
if ($this->request->isAjax()) {
$data = GroupModel::where('id', $id)->find();
$this->result->success(['info' => $data]);
}
View::assign('title', '登录');
return View::fetch('group/index');
}
/**
* 数据更新
*
* @param Request $request
* @param int|null $ids
* @return \think\Response
*/
public function update()
{
$params = $this->request->only(['id', 'title', 'name', 'status', 'description'], 'put');
$info = GroupModel::find($params['id']);
if (! $info) {
$this->result->error('角色不存在', 404);
}
// 禁止编辑超级管理员组
if ($params['id'] == config('ywxapp.superAdmin', 1) && $info->name === 'superadmin') {
$this->result->error('超级管理员组不可编辑', 403);
}
$info->save($params);
$this->result->success($info, "角色更新成功");
}
/**
* 获取详情
*/
public function read()
{
$info = RoleModel::with(['roles', 'permissions'])
->find($id);
if (! $info) {
$this->result->error('角色不存在', 404);
}
$this->result->success($info, "角色更新成功");
}
/**
* 数据回收站
*
* @param Request $request
* @return \think\Response
*/
public function recyclebin()
{
$page = $this->request->param('page', 1);
$size = $this->request->param('size', 15);
if ($this->request->isAjax()) {
$roles = GroupModel::onlyTrashed()->with(['permissions'])
->paginate([
'page' => $page,
'list_rows' => $size,
]);
$this->result->success($roles->items());
}
View::assign('title', '回收站');
return View::fetch('group/index');
}
/**
* 数据删除
*/
public function delete()
{
if ($this->request->isAjax() && $this->request->isDelete()) {
$ids = $this->request->param('ids', '');
$force = $this->request->param('force', false);
if (empty($ids)) {
$this->result->error('请选择要删除的数据');
}
$idsArray = explode(',', $ids);
// 禁止删除超级管理员组
if (in_array((int)config('ywxapp.superAdmin', 1), array_map('intval', $idsArray), true)) {
$this->result->error('超级管理员组不可删除', 403);
}
try {
Db::transaction(function () use ($idsArray, $force) {
if ($force) {
GroupModel::onlyTrashed()->whereIn('id', $idsArray)->select()->each(function ($item) {
$item->permissions()->detach();
$item->force()->delete();
});
} else {
GroupModel::destroy($idsArray);
}
});
$this->result->success();
} catch (\think\exception\HttpResponseException $e) {
throw $e; // 不要 return,不要吞掉!
} catch (\Exception $e) {
\think\facade\Log::error('批量删除管理员失败', [
'exception' => $e->__toString(),
'admin_ids' => $idsArray,
]);
$this->result->error('删除失败: ' . ($e->getMessage() ?: $e->__toString()), 500);
}
}
}
/**
* 数据恢复
*/
public function restore($ids = '')
{
if ($this->request->isAjax() && $this->request->isPost()) {
$ids = $this->request->param('ids', '');
if (empty($ids)) {
$this->result->error('请选择要恢复的数据');
}
$idsArray = explode(',', $ids);
Db::startTrans();
try {
GroupModel::withTrashed()
->where('id', 'in', $idsArray)
->select()
->each(function ($item) {
$item->restore();
});
Db::commit();
$this->result->success('恢复成功');
} catch (DbException $e) {
Db::rollback();
$this->result->error('恢复失败: ' . $e->getMessage());
}
}
}
/**
* 权限分配
*/
public function permission()
{
$id = $this->request->param('id', 0);
if ($this->request->isGet()) {
// 1. 获取所有权限
$permissions = RuleModel::where('status', 1)->order('sort', 'asc')->select()->toArray();
// 2. 获取角色已拥有的权限ID
$ownedPermissions = GroupRuleModel::where('gid', $id)->column('rid');
// 超级管理员组:权限恒为 *(全部),前端展示为全部勾选且不可编辑
$group = GroupModel::find($id);
$isSuper = $group && ($group->name === 'superadmin' || $id == config('ywxapp.superAdmin', 1));
if ($isSuper) {
$ownedPermissions = array_column($permissions, 'id');
}
// 3. 构建带选中状态的树
$treeData = $this->buildTreeWithChecked($permissions, $ownedPermissions);
$this->result->success($treeData, $isSuper ? '超级管理员组拥有全部权限(*)' : '获取成功');
}
if ($this->request->isAjax() && $this->request->isPut()) {
// 禁止修改超级管理员组权限
$group = GroupModel::find($id);
if ($group && ($group->name === 'superadmin' || $id == config('ywxapp.superAdmin', 1))) {
$this->result->error('超级管理员组权限不可修改', 403);
}
$permissionIds = $this->request->param('permissions/a', []);
try {
Db::startTrans();
GroupRuleModel::where('gid', $id)->delete();
foreach ($permissionIds as $permissionId) {
GroupRuleModel::create([
'gid' => $id,
'rid' => $permissionId,
]);
}
Db::commit();
$this->result->success([], '权限分配成功');
} catch (\Exception $e) {
Db::rollback();
$this->result->error('保存失败:' . $e->getMessage());
}
}
}
/**
* 构建树选择项
*/
private function buildTreeWithChecked($items, $checkedIds, $parentId = 0)
{
$tree = [];
foreach ($items as $item) {
if ($item['pid'] == $parentId) {
$isChecked = in_array($item['id'], $checkedIds);
$children = $this->buildTreeWithChecked($items, $checkedIds, $item['id']);
$item['spread'] = true;
$item['checked'] = $isChecked;
$item['children'] = $children;
$tree[] = $item;
}
}
return $tree;
}
}