Merge branch 'develop' of https://gitee.com/Tyssen/yi-shi into develop
This commit is contained in:
@@ -1,5 +1,35 @@
|
||||
<?php
|
||||
use think\facade\Route;
|
||||
|
||||
// 超级管理员认证相关路由
|
||||
Route::post('auth/login', 'app\\superadmin\\controller\\Auth@login');
|
||||
// 超级管理员认证相关路由(不需要鉴权)
|
||||
Route::post('auth/login', 'app\\superadmin\\controller\\Auth@login');
|
||||
|
||||
// 需要登录认证的路由组
|
||||
Route::group('', function () {
|
||||
// 菜单管理相关路由
|
||||
Route::group('menu', function () {
|
||||
Route::get('tree', 'app\\superadmin\\controller\\Menu@getMenuTree');
|
||||
Route::get('list', 'app\\superadmin\\controller\\Menu@getMenuList');
|
||||
Route::post('save', 'app\\superadmin\\controller\\Menu@saveMenu');
|
||||
Route::delete('delete/:id', 'app\\superadmin\\controller\\Menu@deleteMenu');
|
||||
Route::post('status', 'app\\superadmin\\controller\\Menu@updateStatus');
|
||||
Route::get('toplevel', 'app\\superadmin\\controller\\Menu@getTopLevelMenus');
|
||||
});
|
||||
|
||||
// 管理员相关路由
|
||||
Route::group('administrator', function () {
|
||||
// 获取管理员列表
|
||||
Route::get('list', 'app\\superadmin\\controller\\Administrator@getList');
|
||||
// 获取管理员详情
|
||||
Route::get('detail/:id', 'app\\superadmin\\controller\\Administrator@getDetail');
|
||||
// 更新管理员信息
|
||||
Route::post('update', 'app\\superadmin\\controller\\Administrator@updateAdmin');
|
||||
// 添加管理员
|
||||
Route::post('add', 'app\\superadmin\\controller\\Administrator@addAdmin');
|
||||
// 删除管理员
|
||||
Route::post('delete', 'app\\superadmin\\controller\\Administrator@deleteAdmin');
|
||||
});
|
||||
|
||||
// 系统信息相关路由
|
||||
Route::get('system/info', 'app\\superadmin\\controller\\System@getInfo');
|
||||
})->middleware(['app\\superadmin\\middleware\\AdminAuth']);
|
||||
328
Server/application/superadmin/controller/Administrator.php
Normal file
328
Server/application/superadmin/controller/Administrator.php
Normal file
@@ -0,0 +1,328 @@
|
||||
<?php
|
||||
namespace app\superadmin\controller;
|
||||
|
||||
use app\superadmin\model\AdministratorPermissions;
|
||||
use think\Controller;
|
||||
use app\superadmin\model\Administrator as AdminModel;
|
||||
|
||||
/**
|
||||
* 管理员控制器
|
||||
*/
|
||||
class Administrator extends Controller
|
||||
{
|
||||
/**
|
||||
* 获取管理员列表
|
||||
* @return \think\response\Json
|
||||
*/
|
||||
public function getList()
|
||||
{
|
||||
// 获取分页参数
|
||||
$page = $this->request->param('page/d', 1);
|
||||
$limit = $this->request->param('limit/d', 10);
|
||||
$keyword = $this->request->param('keyword/s', '');
|
||||
|
||||
// 构建查询条件
|
||||
$where = [
|
||||
['deleteTime', '=', 0]
|
||||
];
|
||||
|
||||
// 如果有搜索关键词
|
||||
if (!empty($keyword)) {
|
||||
$where[] = ['account|name', 'like', "%{$keyword}%"];
|
||||
}
|
||||
|
||||
// 查询管理员数据
|
||||
$total = AdminModel::where($where)->count();
|
||||
$list = AdminModel::where($where)
|
||||
->field('id, account, name, status, authId, createTime, lastLoginTime, lastLoginIp')
|
||||
->order('id', 'desc')
|
||||
->page($page, $limit)
|
||||
->select();
|
||||
|
||||
// 格式化数据
|
||||
$data = [];
|
||||
foreach ($list as $item) {
|
||||
$data[] = [
|
||||
'id' => $item->id,
|
||||
'username' => $item->account,
|
||||
'name' => $item->name,
|
||||
'role' => $this->getRoleName($item->authId),
|
||||
'status' => $item->status,
|
||||
'createdAt' => date('Y-m-d H:i:s', $item->createTime),
|
||||
'lastLogin' => !empty($item->lastLoginTime) ? date('Y-m-d H:i:s', $item->lastLoginTime) : '从未登录',
|
||||
'permissions' => $this->getPermissions($item->id)
|
||||
];
|
||||
}
|
||||
|
||||
return json([
|
||||
'code' => 200,
|
||||
'msg' => '获取成功',
|
||||
'data' => [
|
||||
'list' => $data,
|
||||
'total' => $total,
|
||||
'page' => $page,
|
||||
'limit' => $limit
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取详细信息
|
||||
* @param int $id 管理员ID
|
||||
* @return \think\response\Json
|
||||
*/
|
||||
public function getDetail($id)
|
||||
{
|
||||
// 查询管理员信息
|
||||
$admin = AdminModel::where('id', $id)
|
||||
->where('deleteTime', 0)
|
||||
->field('id, account, name, status, authId, createTime, lastLoginTime')
|
||||
->find();
|
||||
|
||||
// 如果查不到记录
|
||||
if (!$admin) {
|
||||
return json([
|
||||
'code' => 404,
|
||||
'msg' => '管理员不存在',
|
||||
'data' => null
|
||||
]);
|
||||
}
|
||||
|
||||
// 格式化数据
|
||||
$data = [
|
||||
'id' => $admin->id,
|
||||
'username' => $admin->account,
|
||||
'name' => $admin->name,
|
||||
'status' => $admin->status,
|
||||
'authId' => $admin->authId,
|
||||
'roleName' => $this->getRoleName($admin->authId),
|
||||
'createdAt' => $admin->createTime,
|
||||
'lastLogin' => !empty($admin->lastLoginTime) ? date('Y-m-d H:i', $admin->lastLoginTime) : '从未登录',
|
||||
'permissions' => $this->getPermissions($admin->authId)
|
||||
];
|
||||
|
||||
return json([
|
||||
'code' => 200,
|
||||
'msg' => '获取成功',
|
||||
'data' => $data
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据权限ID获取角色名称
|
||||
* @param int $authId 权限ID
|
||||
* @return string
|
||||
*/
|
||||
private function getRoleName($authId)
|
||||
{
|
||||
// 可以从权限表中查询,这里为演示简化处理
|
||||
switch($authId) {
|
||||
case 1:
|
||||
return '超级管理员';
|
||||
case 2:
|
||||
return '项目管理员';
|
||||
case 3:
|
||||
return '客户管理员';
|
||||
default:
|
||||
return '普通管理员';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据权限ID获取权限列表
|
||||
* @param int $authId 权限ID
|
||||
* @return array
|
||||
*/
|
||||
private function getPermissions($authId)
|
||||
{
|
||||
$ids = AdministratorPermissions::getPermissions($authId);
|
||||
|
||||
if ($ids) {
|
||||
return \app\superadmin\model\Menu::getMenusNameByIds($ids);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新管理员信息
|
||||
* @return \think\response\Json
|
||||
*/
|
||||
public function updateAdmin()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return json(['code' => 405, 'msg' => '请求方法不允许']);
|
||||
}
|
||||
|
||||
// 获取当前登录的管理员信息
|
||||
$currentAdmin = $this->request->adminInfo;
|
||||
|
||||
// 获取请求参数
|
||||
$id = $this->request->post('id/d');
|
||||
$username = $this->request->post('username/s');
|
||||
$name = $this->request->post('name/s');
|
||||
$password = $this->request->post('password/s');
|
||||
$permissionIds = $this->request->post('permissionIds/a');
|
||||
|
||||
// 参数验证
|
||||
if (empty($id) || empty($username) || empty($name)) {
|
||||
return json(['code' => 400, 'msg' => '参数不完整']);
|
||||
}
|
||||
|
||||
// 判断是否有权限修改
|
||||
if ($currentAdmin->id != 1 && $currentAdmin->id != $id) {
|
||||
return json(['code' => 403, 'msg' => '您没有权限修改其他管理员']);
|
||||
}
|
||||
|
||||
// 查询管理员
|
||||
$admin = AdminModel::where('id', $id)->where('deleteTime', 0)->find();
|
||||
if (!$admin) {
|
||||
return json(['code' => 404, 'msg' => '管理员不存在']);
|
||||
}
|
||||
|
||||
// 准备更新数据
|
||||
$data = [
|
||||
'account' => $username,
|
||||
'name' => $name,
|
||||
'updateTime' => time()
|
||||
];
|
||||
|
||||
// 如果提供了密码,则更新密码
|
||||
if (!empty($password)) {
|
||||
$data['password'] = md5($password);
|
||||
}
|
||||
|
||||
// 更新管理员信息
|
||||
$result = $admin->save($data);
|
||||
|
||||
// 如果当前是超级管理员(ID为1),并且修改的不是自己,则更新权限
|
||||
if ($currentAdmin->id == 1 && $currentAdmin->id != $id && !empty($permissionIds)) {
|
||||
\app\superadmin\model\AdministratorPermissions::savePermissions($id, $permissionIds);
|
||||
}
|
||||
|
||||
return json([
|
||||
'code' => 200,
|
||||
'msg' => '更新成功',
|
||||
'data' => null
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加管理员
|
||||
* @return \think\response\Json
|
||||
*/
|
||||
public function addAdmin()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return json(['code' => 405, 'msg' => '请求方法不允许']);
|
||||
}
|
||||
|
||||
// 获取当前登录的管理员信息
|
||||
$currentAdmin = $this->request->adminInfo;
|
||||
|
||||
// 只有超级管理员(ID为1)可以添加管理员
|
||||
if ($currentAdmin->id != 1) {
|
||||
return json(['code' => 403, 'msg' => '您没有权限添加管理员']);
|
||||
}
|
||||
|
||||
// 获取请求参数
|
||||
$username = $this->request->post('username/s');
|
||||
$name = $this->request->post('name/s');
|
||||
$password = $this->request->post('password/s');
|
||||
$permissionIds = $this->request->post('permissionIds/a');
|
||||
|
||||
// 参数验证
|
||||
if (empty($username) || empty($name) || empty($password)) {
|
||||
return json(['code' => 400, 'msg' => '参数不完整']);
|
||||
}
|
||||
|
||||
// 检查账号是否已存在
|
||||
$exists = AdminModel::where('account', $username)->where('deleteTime', 0)->find();
|
||||
if ($exists) {
|
||||
return json(['code' => 400, 'msg' => '账号已存在']);
|
||||
}
|
||||
|
||||
// 创建管理员
|
||||
$admin = new AdminModel();
|
||||
$admin->account = $username;
|
||||
$admin->name = $name;
|
||||
$admin->password = md5($password);
|
||||
$admin->status = 1;
|
||||
$admin->createTime = time();
|
||||
$admin->updateTime = time();
|
||||
$admin->deleteTime = 0;
|
||||
$admin->save();
|
||||
|
||||
// 保存权限
|
||||
if (!empty($permissionIds)) {
|
||||
\app\superadmin\model\AdministratorPermissions::savePermissions($admin->id, $permissionIds);
|
||||
}
|
||||
|
||||
return json([
|
||||
'code' => 200,
|
||||
'msg' => '添加成功',
|
||||
'data' => null
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除管理员
|
||||
* @return \think\response\Json
|
||||
*/
|
||||
public function deleteAdmin()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return json(['code' => 405, 'msg' => '请求方法不允许']);
|
||||
}
|
||||
|
||||
// 获取当前登录的管理员信息
|
||||
$currentAdmin = $this->request->adminInfo;
|
||||
|
||||
// 获取请求参数
|
||||
$id = $this->request->post('id/d');
|
||||
|
||||
// 参数验证
|
||||
if (empty($id)) {
|
||||
return json(['code' => 400, 'msg' => '参数不完整']);
|
||||
}
|
||||
|
||||
// 不能删除自己的账号
|
||||
if ($currentAdmin->id == $id) {
|
||||
return json(['code' => 403, 'msg' => '不能删除自己的账号']);
|
||||
}
|
||||
|
||||
// 只有超级管理员(ID为1)可以删除管理员
|
||||
if ($currentAdmin->id != 1) {
|
||||
return json(['code' => 403, 'msg' => '您没有权限删除管理员']);
|
||||
}
|
||||
|
||||
// 不能删除超级管理员账号
|
||||
if ($id == 1) {
|
||||
return json(['code' => 403, 'msg' => '不能删除超级管理员账号']);
|
||||
}
|
||||
|
||||
// 查询管理员
|
||||
$admin = AdminModel::where('id', $id)->where('deleteTime', 0)->find();
|
||||
if (!$admin) {
|
||||
return json(['code' => 404, 'msg' => '管理员不存在']);
|
||||
}
|
||||
|
||||
// 执行软删除
|
||||
$admin->deleteTime = time();
|
||||
$result = $admin->save();
|
||||
|
||||
if ($result) {
|
||||
return json([
|
||||
'code' => 200,
|
||||
'msg' => '删除成功',
|
||||
'data' => null
|
||||
]);
|
||||
} else {
|
||||
return json([
|
||||
'code' => 500,
|
||||
'msg' => '删除失败',
|
||||
'data' => null
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ class Auth extends Controller
|
||||
*/
|
||||
private function createToken($admin)
|
||||
{
|
||||
$data = $admin->id . '|' . $admin->account . '|' . time();
|
||||
$data = $admin->id . '|' . $admin->account;
|
||||
return md5($data . 'cunkebao_admin_secret');
|
||||
}
|
||||
}
|
||||
183
Server/application/superadmin/controller/Menu.php
Normal file
183
Server/application/superadmin/controller/Menu.php
Normal file
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
namespace app\superadmin\controller;
|
||||
|
||||
use think\Controller;
|
||||
use app\superadmin\model\Menu as MenuModel;
|
||||
|
||||
/**
|
||||
* 菜单控制器
|
||||
*/
|
||||
class Menu extends Controller
|
||||
{
|
||||
/**
|
||||
* 获取菜单列表(树状结构)
|
||||
* @return \think\response\Json
|
||||
*/
|
||||
public function getMenuTree()
|
||||
{
|
||||
// 参数处理
|
||||
$onlyEnabled = $this->request->param('only_enabled', 1);
|
||||
$useCache = $this->request->param('use_cache', 0); // 由于要根据用户权限过滤,默认不使用缓存
|
||||
|
||||
// 获取当前登录的管理员信息
|
||||
$adminInfo = $this->request->adminInfo;
|
||||
|
||||
// 调用模型获取菜单树
|
||||
if ($adminInfo->id == 1) {
|
||||
// 超级管理员获取所有菜单
|
||||
$menuTree = MenuModel::getMenuTree($onlyEnabled, $useCache);
|
||||
} else {
|
||||
// 非超级管理员根据权限获取菜单
|
||||
$permissionIds = \app\superadmin\model\AdministratorPermissions::getPermissions($adminInfo->id);
|
||||
$menuTree = MenuModel::getMenuTreeByPermissions($permissionIds, $onlyEnabled);
|
||||
}
|
||||
|
||||
return json([
|
||||
'code' => 200,
|
||||
'msg' => '获取成功',
|
||||
'data' => $menuTree
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有菜单(平铺结构,便于后台管理)
|
||||
* @return \think\response\Json
|
||||
*/
|
||||
public function getMenuList()
|
||||
{
|
||||
// 查询条件
|
||||
$where = [];
|
||||
$status = $this->request->param('status');
|
||||
if ($status !== null && $status !== '') {
|
||||
$where[] = ['status', '=', intval($status)];
|
||||
}
|
||||
|
||||
// 获取所有菜单
|
||||
$menus = MenuModel::where($where)
|
||||
->order('sort', 'asc')
|
||||
->select();
|
||||
|
||||
return json([
|
||||
'code' => 200,
|
||||
'msg' => '获取成功',
|
||||
'data' => $menus
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加或更新菜单
|
||||
* @return \think\response\Json
|
||||
*/
|
||||
public function saveMenu()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return json(['code' => 405, 'msg' => '请求方法不允许']);
|
||||
}
|
||||
|
||||
// 获取参数
|
||||
$data = $this->request->post();
|
||||
|
||||
// 验证参数
|
||||
$validate = $this->validate($data, [
|
||||
'title|菜单名称' => 'require|max:50',
|
||||
'path|路由路径' => 'require|max:100',
|
||||
'parent_id|父菜单ID' => 'require|number',
|
||||
'status|状态' => 'require|in:0,1',
|
||||
'sort|排序' => 'require|number',
|
||||
]);
|
||||
|
||||
if ($validate !== true) {
|
||||
return json(['code' => 400, 'msg' => $validate]);
|
||||
}
|
||||
|
||||
// 保存菜单
|
||||
$result = MenuModel::saveMenu($data);
|
||||
|
||||
if ($result) {
|
||||
return json(['code' => 200, 'msg' => '保存成功']);
|
||||
} else {
|
||||
return json(['code' => 500, 'msg' => '保存失败']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除菜单
|
||||
* @param int $id 菜单ID
|
||||
* @return \think\response\Json
|
||||
*/
|
||||
public function deleteMenu($id)
|
||||
{
|
||||
if (!$this->request->isDelete()) {
|
||||
return json(['code' => 405, 'msg' => '请求方法不允许']);
|
||||
}
|
||||
|
||||
if (empty($id) || !is_numeric($id)) {
|
||||
return json(['code' => 400, 'msg' => '参数错误']);
|
||||
}
|
||||
|
||||
$result = MenuModel::deleteMenu($id);
|
||||
|
||||
if ($result) {
|
||||
return json(['code' => 200, 'msg' => '删除成功']);
|
||||
} else {
|
||||
return json(['code' => 500, 'msg' => '删除失败,可能存在子菜单']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新菜单状态
|
||||
* @return \think\response\Json
|
||||
*/
|
||||
public function updateStatus()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return json(['code' => 405, 'msg' => '请求方法不允许']);
|
||||
}
|
||||
|
||||
$id = $this->request->post('id');
|
||||
$status = $this->request->post('status');
|
||||
|
||||
if (empty($id) || !is_numeric($id) || !in_array($status, [0, 1])) {
|
||||
return json(['code' => 400, 'msg' => '参数错误']);
|
||||
}
|
||||
|
||||
$menu = MenuModel::find($id);
|
||||
if (!$menu) {
|
||||
return json(['code' => 404, 'msg' => '菜单不存在']);
|
||||
}
|
||||
|
||||
$menu->status = $status;
|
||||
$result = $menu->save();
|
||||
|
||||
// 清除缓存
|
||||
MenuModel::clearMenuCache();
|
||||
|
||||
if ($result) {
|
||||
return json(['code' => 200, 'msg' => '状态更新成功']);
|
||||
} else {
|
||||
return json(['code' => 500, 'msg' => '状态更新失败']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一级菜单(供权限设置使用)
|
||||
* @return \think\response\Json
|
||||
*/
|
||||
public function getTopLevelMenus()
|
||||
{
|
||||
// 获取所有启用的一级菜单
|
||||
$menus = \app\superadmin\model\Menu::where([
|
||||
['parent_id', '=', 0],
|
||||
['status', '=', 1]
|
||||
])
|
||||
->field('id, title')
|
||||
->order('sort', 'asc')
|
||||
->select();
|
||||
|
||||
return json([
|
||||
'code' => 200,
|
||||
'msg' => '获取成功',
|
||||
'data' => $menus
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
INSERT INTO `tk_administrators` (`name`, `account`, `password`, `status`, `createTime`, `updateTime`)
|
||||
VALUES ('超级管理员', 'admin', MD5('123456'), 1, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
|
||||
74
Server/application/superadmin/middleware/AdminAuth.php
Normal file
74
Server/application/superadmin/middleware/AdminAuth.php
Normal file
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
namespace app\superadmin\middleware;
|
||||
|
||||
/**
|
||||
* 超级管理员后台登录认证中间件
|
||||
*/
|
||||
class AdminAuth
|
||||
{
|
||||
/**
|
||||
* 处理请求
|
||||
* @param \think\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
// 获取Cookie中的管理员信息
|
||||
$adminId = cookie('admin_id');
|
||||
$adminToken = cookie('admin_token');
|
||||
|
||||
// 如果没有登录信息,返回401未授权
|
||||
if (empty($adminId) || empty($adminToken)) {
|
||||
return json([
|
||||
'code' => 401,
|
||||
'msg' => '请先登录',
|
||||
'data' => null
|
||||
]);
|
||||
}
|
||||
|
||||
// 获取管理员信息
|
||||
$admin = \app\superadmin\model\Administrator::where([
|
||||
['id', '=', $adminId],
|
||||
['status', '=', 1],
|
||||
['deleteTime', '=', 0]
|
||||
])->find();
|
||||
|
||||
// 如果管理员不存在,返回401未授权
|
||||
if (!$admin) {
|
||||
return json([
|
||||
'code' => 401,
|
||||
'msg' => '管理员账号不存在或已被禁用',
|
||||
'data' => null
|
||||
]);
|
||||
}
|
||||
|
||||
// 验证Token是否有效
|
||||
$expectedToken = $this->createToken($admin);
|
||||
|
||||
if ($adminToken !== $expectedToken) {
|
||||
return json([
|
||||
'code' => 401,
|
||||
'msg' => '登录已过期,请重新登录',
|
||||
'data' => null
|
||||
]);
|
||||
}
|
||||
|
||||
// 将管理员信息绑定到请求对象,方便后续控制器使用
|
||||
$request->adminInfo = $admin;
|
||||
|
||||
// 继续执行后续操作
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建登录令牌
|
||||
* @param \app\superadmin\model\Administrator $admin
|
||||
* @return string
|
||||
*/
|
||||
private function createToken($admin)
|
||||
{
|
||||
$data = $admin->id . '|' . $admin->account;
|
||||
return md5($data . 'cunkebao_admin_secret');
|
||||
}
|
||||
}
|
||||
@@ -11,20 +11,6 @@ class Administrator extends Model
|
||||
// 设置数据表名
|
||||
protected $name = 'administrators';
|
||||
|
||||
// 设置数据表前缀
|
||||
protected $prefix = 'tk_';
|
||||
|
||||
// 设置主键
|
||||
protected $pk = 'id';
|
||||
|
||||
// 自动写入时间戳
|
||||
protected $autoWriteTimestamp = true;
|
||||
|
||||
// 定义时间戳字段名
|
||||
protected $createTime = 'createTime';
|
||||
protected $updateTime = 'updateTime';
|
||||
protected $deleteTime = 'deleteTime';
|
||||
|
||||
// 隐藏字段
|
||||
protected $hidden = [
|
||||
'password'
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
namespace app\superadmin\model;
|
||||
|
||||
use think\Model;
|
||||
|
||||
/**
|
||||
* 超级管理员权限配置模型类
|
||||
*/
|
||||
class AdministratorPermissions extends Model
|
||||
{
|
||||
// 设置数据表名
|
||||
protected $name = 'administrator_permissions';
|
||||
|
||||
// 设置主键
|
||||
protected $pk = 'id';
|
||||
|
||||
// 自动写入时间戳
|
||||
protected $autoWriteTimestamp = true;
|
||||
|
||||
// 定义时间戳字段名
|
||||
protected $createTime = 'createTime';
|
||||
protected $updateTime = 'updateTime';
|
||||
protected $deleteTime = 'deleteTime';
|
||||
|
||||
// 定义字段类型
|
||||
protected $type = [
|
||||
'id' => 'integer',
|
||||
'adminId' => 'integer',
|
||||
'permissions' => 'json',
|
||||
'createTime' => 'integer',
|
||||
'updateTime' => 'integer',
|
||||
'deleteTime' => 'integer'
|
||||
];
|
||||
|
||||
/**
|
||||
* 保存管理员权限
|
||||
* @param int $adminId 管理员ID
|
||||
* @param array $permissionIds 权限ID数组
|
||||
* @return bool
|
||||
*/
|
||||
public static function savePermissions($adminId, $permissionIds)
|
||||
{
|
||||
// 检查是否已有记录
|
||||
$record = self::where('adminId', $adminId)->find();
|
||||
|
||||
// 准备权限数据
|
||||
$permissionData = [
|
||||
'ids' => is_array($permissionIds) ? implode(',', $permissionIds) : $permissionIds
|
||||
];
|
||||
|
||||
if ($record) {
|
||||
// 更新已有记录
|
||||
return $record->save([
|
||||
'permissions' => json_encode($permissionData),
|
||||
'updateTime' => time()
|
||||
]);
|
||||
} else {
|
||||
// 创建新记录
|
||||
return self::create([
|
||||
'adminId' => $adminId,
|
||||
'permissions' => json_encode($permissionData),
|
||||
'createTime' => time(),
|
||||
'updateTime' => time(),
|
||||
'deleteTime' => 0
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取管理员权限
|
||||
* @param int $adminId 管理员ID
|
||||
* @return array 权限ID数组
|
||||
*/
|
||||
public static function getPermissions($adminId)
|
||||
{
|
||||
$record = self::where('adminId', $adminId)->find();
|
||||
|
||||
if (!$record || empty($record->permissions)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$permissions = $record->permissions ? json_decode($record->permissions, true) : [];
|
||||
|
||||
if (isset($permissions['ids']) && !empty($permissions['ids'])) {
|
||||
return is_string($permissions['ids']) ? explode(',', $permissions['ids']) : $permissions['ids'];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
131
Server/application/superadmin/model/Menu.php
Normal file
131
Server/application/superadmin/model/Menu.php
Normal file
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
namespace app\superadmin\model;
|
||||
|
||||
use think\Model;
|
||||
use think\facade\Cache;
|
||||
|
||||
/**
|
||||
* 菜单模型类
|
||||
*/
|
||||
class Menu extends Model
|
||||
{
|
||||
// 设置数据表名
|
||||
protected $name = 'menus';
|
||||
|
||||
/**
|
||||
* 获取所有菜单,并组织成树状结构
|
||||
* @param bool $onlyEnabled 是否只获取启用的菜单
|
||||
* @param bool $useCache 是否使用缓存
|
||||
* @return array
|
||||
*/
|
||||
public static function getMenuTree($onlyEnabled = true, $useCache = true)
|
||||
{
|
||||
$cacheKey = 'superadmin_menu_tree' . ($onlyEnabled ? '_enabled' : '_all');
|
||||
|
||||
// 查询条件
|
||||
$where = [];
|
||||
if ($onlyEnabled) {
|
||||
$where[] = ['status', '=', 1];
|
||||
}
|
||||
|
||||
// 获取所有菜单
|
||||
$allMenus = self::where($where)
|
||||
->order('sort', 'asc')
|
||||
->select()
|
||||
->toArray();
|
||||
|
||||
// 组织成树状结构
|
||||
$menuTree = self::buildMenuTree($allMenus);
|
||||
|
||||
// 缓存结果
|
||||
if ($useCache) {
|
||||
Cache::set($cacheKey, $menuTree, 3600); // 缓存1小时
|
||||
}
|
||||
|
||||
return $menuTree;
|
||||
}
|
||||
|
||||
public static function getMenusNameByIds($ids)
|
||||
{
|
||||
return self::whereIn('id', $ids)->column('title');
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建菜单树
|
||||
* @param array $menus 所有菜单
|
||||
* @param int $parentId 父菜单ID
|
||||
* @return array
|
||||
*/
|
||||
private static function buildMenuTree($menus, $parentId = 0)
|
||||
{
|
||||
$tree = [];
|
||||
|
||||
foreach ($menus as $menu) {
|
||||
if ($menu['parent_id'] == $parentId) {
|
||||
$children = self::buildMenuTree($menus, $menu['id']);
|
||||
if (!empty($children)) {
|
||||
$menu['children'] = $children;
|
||||
}
|
||||
$tree[] = $menu;
|
||||
}
|
||||
}
|
||||
|
||||
return $tree;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据权限ID获取相应的菜单树
|
||||
* @param array $permissionIds 权限ID数组
|
||||
* @param bool $onlyEnabled 是否只获取启用的菜单
|
||||
* @return array
|
||||
*/
|
||||
public static function getMenuTreeByPermissions($permissionIds, $onlyEnabled = true)
|
||||
{
|
||||
// 如果没有权限,返回空数组
|
||||
if (empty($permissionIds)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// 查询条件
|
||||
$where = [];
|
||||
if ($onlyEnabled) {
|
||||
$where[] = ['status', '=', 1];
|
||||
}
|
||||
|
||||
// 获取所有一级菜单(用户拥有权限的)
|
||||
$topMenus = self::where($where)
|
||||
->where('parent_id', 0)
|
||||
->whereIn('id', $permissionIds)
|
||||
->order('sort', 'asc')
|
||||
->select()
|
||||
->toArray();
|
||||
|
||||
// 菜单ID集合,用于获取子菜单
|
||||
$menuIds = array_column($topMenus, 'id');
|
||||
|
||||
// 获取所有子菜单
|
||||
$childMenus = self::where($where)
|
||||
->where('parent_id', 'in', $menuIds)
|
||||
->order('sort', 'asc')
|
||||
->select()
|
||||
->toArray();
|
||||
|
||||
// 将子菜单按照父ID进行分组
|
||||
$childMenusGroup = [];
|
||||
foreach ($childMenus as $menu) {
|
||||
$childMenusGroup[$menu['parent_id']][] = $menu;
|
||||
}
|
||||
|
||||
// 构建菜单树
|
||||
$menuTree = [];
|
||||
foreach ($topMenus as $topMenu) {
|
||||
// 添加子菜单
|
||||
if (isset($childMenusGroup[$topMenu['id']])) {
|
||||
$topMenu['children'] = $childMenusGroup[$topMenu['id']];
|
||||
}
|
||||
$menuTree[] = $topMenu;
|
||||
}
|
||||
|
||||
return $menuTree;
|
||||
}
|
||||
}
|
||||
35
Server/database/create_menu_table.sql
Normal file
35
Server/database/create_menu_table.sql
Normal file
@@ -0,0 +1,35 @@
|
||||
-- 创建菜单表
|
||||
CREATE TABLE IF NOT EXISTS `tk_menus` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '菜单ID',
|
||||
`title` varchar(50) NOT NULL COMMENT '菜单名称',
|
||||
`path` varchar(100) NOT NULL COMMENT '路由路径',
|
||||
`icon` varchar(50) DEFAULT NULL COMMENT '图标名称',
|
||||
`parent_id` int(11) NOT NULL DEFAULT '0' COMMENT '父菜单ID,0表示顶级菜单',
|
||||
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态:1启用,0禁用',
|
||||
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序,数值越小越靠前',
|
||||
`create_time` int(11) DEFAULT NULL COMMENT '创建时间',
|
||||
`update_time` int(11) DEFAULT NULL COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_parent_id` (`parent_id`),
|
||||
KEY `idx_status` (`status`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统菜单表';
|
||||
|
||||
-- 插入超级管理员顶级菜单
|
||||
INSERT INTO `tk_menus` (`title`, `path`, `icon`, `parent_id`, `status`, `sort`, `create_time`, `update_time`) VALUES
|
||||
('仪表盘', '/dashboard', 'LayoutDashboard', 0, 1, 10, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('项目管理', '/dashboard/projects', 'FolderKanban', 0, 1, 20, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('客户池', '/dashboard/customers', 'Users', 0, 1, 30, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('管理员权限', '/dashboard/admins', 'Settings', 0, 1, 40, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('系统设置', '/settings', 'Cog', 0, 1, 50, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
|
||||
|
||||
-- 插入子菜单
|
||||
INSERT INTO `tk_menus` (`title`, `path`, `icon`, `parent_id`, `status`, `sort`, `create_time`, `update_time`) VALUES
|
||||
('项目列表', '/dashboard/projects', 'List', 2, 1, 21, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('新建项目', '/dashboard/projects/new', 'PlusCircle', 2, 1, 22, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('客户管理', '/dashboard/customers', 'Users', 3, 1, 31, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('客户分析', '/dashboard/customers/analytics', 'BarChart', 3, 1, 32, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('管理员列表', '/dashboard/admins', 'UserCog', 4, 1, 41, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('角色管理', '/dashboard/admins/roles', 'ShieldCheck', 4, 1, 42, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('权限设置', '/dashboard/admins/permissions', 'Lock', 4, 1, 43, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('基本设置', '/settings/general', 'Settings', 5, 1, 51, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
|
||||
('安全设置', '/settings/security', 'Shield', 5, 1, 52, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
|
||||
@@ -12,7 +12,7 @@
|
||||
// [ 应用入口文件 ]
|
||||
namespace think;
|
||||
|
||||
//处理跨域预检请求
|
||||
////处理跨域预检请求
|
||||
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
|
||||
//允许的源域名
|
||||
header("Access-Control-Allow-Origin: *");
|
||||
|
||||
173
Server/scripts/init-menu.php
Normal file
173
Server/scripts/init-menu.php
Normal file
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
/**
|
||||
* 菜单表初始化脚本
|
||||
* 执行该脚本,会创建菜单表并插入初始菜单数据
|
||||
* 执行方式: php init-menu.php
|
||||
*/
|
||||
|
||||
// 定义应用目录
|
||||
define('APP_PATH', __DIR__ . '/../application/');
|
||||
define('RUNTIME_PATH', __DIR__ . '/../runtime/');
|
||||
define('ROOT_PATH', __DIR__ . '/../');
|
||||
|
||||
// 加载框架引导文件
|
||||
require __DIR__ . '/../thinkphp/base.php';
|
||||
|
||||
// 加载环境变量
|
||||
use think\facade\Env;
|
||||
$rootPath = realpath(__DIR__ . '/../');
|
||||
Env::load($rootPath . '/.env');
|
||||
|
||||
// 读取数据库配置
|
||||
$dbConfig = [
|
||||
'type' => Env::get('database.type', 'mysql'),
|
||||
'hostname' => Env::get('database.hostname', '127.0.0.1'),
|
||||
'database' => Env::get('database.database', 'database'),
|
||||
'username' => Env::get('database.username', 'root'),
|
||||
'password' => Env::get('database.password', 'root'),
|
||||
'hostport' => Env::get('database.hostport', '3306'),
|
||||
'charset' => Env::get('database.charset', 'utf8mb4'),
|
||||
'prefix' => Env::get('database.prefix', 'tk_'),
|
||||
];
|
||||
|
||||
// 连接数据库
|
||||
try {
|
||||
$dsn = "{$dbConfig['type']}:host={$dbConfig['hostname']};port={$dbConfig['hostport']};dbname={$dbConfig['database']};charset={$dbConfig['charset']}";
|
||||
$pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
echo "数据库连接成功!\n";
|
||||
} catch (PDOException $e) {
|
||||
die("数据库连接失败: " . $e->getMessage() . "\n");
|
||||
}
|
||||
|
||||
// 创建菜单表SQL
|
||||
$createTableSql = "
|
||||
CREATE TABLE IF NOT EXISTS `{$dbConfig['prefix']}menus` (
|
||||
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '菜单ID',
|
||||
`title` varchar(50) NOT NULL COMMENT '菜单名称',
|
||||
`path` varchar(100) NOT NULL COMMENT '路由路径',
|
||||
`icon` varchar(50) DEFAULT NULL COMMENT '图标名称',
|
||||
`parent_id` int(11) NOT NULL DEFAULT '0' COMMENT '父菜单ID,0表示顶级菜单',
|
||||
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态:1启用,0禁用',
|
||||
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序,数值越小越靠前',
|
||||
`create_time` int(11) DEFAULT NULL COMMENT '创建时间',
|
||||
`update_time` int(11) DEFAULT NULL COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_parent_id` (`parent_id`),
|
||||
KEY `idx_status` (`status`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统菜单表';
|
||||
";
|
||||
|
||||
// 执行创建表SQL
|
||||
try {
|
||||
$pdo->exec($createTableSql);
|
||||
echo "菜单表创建成功!\n";
|
||||
} catch (PDOException $e) {
|
||||
echo "菜单表创建失败: " . $e->getMessage() . "\n";
|
||||
}
|
||||
|
||||
// 检查表中是否已有数据
|
||||
$checkSql = "SELECT COUNT(*) FROM `{$dbConfig['prefix']}menus`";
|
||||
try {
|
||||
$count = $pdo->query($checkSql)->fetchColumn();
|
||||
if ($count > 0) {
|
||||
echo "菜单表中已有 {$count} 条数据,跳过数据初始化\n";
|
||||
exit(0);
|
||||
}
|
||||
} catch (PDOException $e) {
|
||||
echo "检查数据失败: " . $e->getMessage() . "\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// 插入顶级菜单数据
|
||||
$topMenus = [
|
||||
['仪表盘', '/dashboard', 'LayoutDashboard', 0, 1, 10],
|
||||
['项目管理', '/dashboard/projects', 'FolderKanban', 0, 1, 20],
|
||||
['客户池', '/dashboard/customers', 'Users', 0, 1, 30],
|
||||
['管理员权限', '/dashboard/admins', 'Settings', 0, 1, 40],
|
||||
['系统设置', '/settings', 'Cog', 0, 1, 50],
|
||||
];
|
||||
|
||||
$insertTopMenuSql = "INSERT INTO `{$dbConfig['prefix']}menus`
|
||||
(`title`, `path`, `icon`, `parent_id`, `status`, `sort`, `create_time`, `update_time`)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
|
||||
$timestamp = time();
|
||||
$insertStmt = $pdo->prepare($insertTopMenuSql);
|
||||
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
foreach ($topMenus as $index => $menu) {
|
||||
$insertStmt->execute([
|
||||
$menu[0], // title
|
||||
$menu[1], // path
|
||||
$menu[2], // icon
|
||||
$menu[3], // parent_id
|
||||
$menu[4], // status
|
||||
$menu[5], // sort
|
||||
$timestamp,
|
||||
$timestamp
|
||||
]);
|
||||
}
|
||||
$pdo->commit();
|
||||
echo "顶级菜单数据插入成功!\n";
|
||||
} catch (PDOException $e) {
|
||||
$pdo->rollBack();
|
||||
echo "顶级菜单数据插入失败: " . $e->getMessage() . "\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// 查询刚插入的顶级菜单ID
|
||||
$menuIds = [];
|
||||
$queryTopMenuSql = "SELECT id, title FROM `{$dbConfig['prefix']}menus` WHERE parent_id = 0";
|
||||
try {
|
||||
$topMenusResult = $pdo->query($queryTopMenuSql)->fetchAll(PDO::FETCH_ASSOC);
|
||||
foreach ($topMenusResult as $menu) {
|
||||
$menuIds[$menu['title']] = $menu['id'];
|
||||
}
|
||||
} catch (PDOException $e) {
|
||||
echo "查询顶级菜单失败: " . $e->getMessage() . "\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// 插入子菜单数据
|
||||
$subMenus = [
|
||||
['项目列表', '/dashboard/projects', 'List', $menuIds['项目管理'], 1, 21],
|
||||
['新建项目', '/dashboard/projects/new', 'PlusCircle', $menuIds['项目管理'], 1, 22],
|
||||
['客户管理', '/dashboard/customers', 'Users', $menuIds['客户池'], 1, 31],
|
||||
['客户分析', '/dashboard/customers/analytics', 'BarChart', $menuIds['客户池'], 1, 32],
|
||||
['管理员列表', '/dashboard/admins', 'UserCog', $menuIds['管理员权限'], 1, 41],
|
||||
['角色管理', '/dashboard/admins/roles', 'ShieldCheck', $menuIds['管理员权限'], 1, 42],
|
||||
['权限设置', '/dashboard/admins/permissions', 'Lock', $menuIds['管理员权限'], 1, 43],
|
||||
['基本设置', '/settings/general', 'Settings', $menuIds['系统设置'], 1, 51],
|
||||
['安全设置', '/settings/security', 'Shield', $menuIds['系统设置'], 1, 52],
|
||||
];
|
||||
|
||||
$insertSubMenuSql = "INSERT INTO `{$dbConfig['prefix']}menus`
|
||||
(`title`, `path`, `icon`, `parent_id`, `status`, `sort`, `create_time`, `update_time`)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
$insertStmt = $pdo->prepare($insertSubMenuSql);
|
||||
foreach ($subMenus as $menu) {
|
||||
$insertStmt->execute([
|
||||
$menu[0], // title
|
||||
$menu[1], // path
|
||||
$menu[2], // icon
|
||||
$menu[3], // parent_id
|
||||
$menu[4], // status
|
||||
$menu[5], // sort
|
||||
$timestamp,
|
||||
$timestamp
|
||||
]);
|
||||
}
|
||||
$pdo->commit();
|
||||
echo "子菜单数据插入成功!\n";
|
||||
} catch (PDOException $e) {
|
||||
$pdo->rollBack();
|
||||
echo "子菜单数据插入失败: " . $e->getMessage() . "\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
echo "菜单初始化完成!\n";
|
||||
@@ -2,53 +2,184 @@
|
||||
|
||||
import type React from "react"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useState, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { ArrowLeft } from "lucide-react"
|
||||
import { ArrowLeft, Loader2 } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { getAdministratorDetail, updateAdministrator } from "@/lib/admin-api"
|
||||
import { useToast } from "@/components/ui/use-toast"
|
||||
import { getTopLevelMenus } from "@/lib/menu-api"
|
||||
import { getAdminInfo } from "@/lib/utils"
|
||||
|
||||
// Sample admin data for editing
|
||||
const adminData = {
|
||||
id: "2",
|
||||
username: "admin_li",
|
||||
name: "李管理",
|
||||
permissions: ["project_management", "customer_pool"],
|
||||
interface MenuPermission {
|
||||
id: number;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export default function EditAdminPage({ params }: { params: { id: string } }) {
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [username, setUsername] = useState(adminData.username)
|
||||
const [name, setName] = useState(adminData.name)
|
||||
const [adminInfo, setAdminInfo] = useState<any | null>(null)
|
||||
const [username, setUsername] = useState("")
|
||||
const [name, setName] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [confirmPassword, setConfirmPassword] = useState("")
|
||||
const [menuPermissions, setMenuPermissions] = useState<MenuPermission[]>([])
|
||||
const [selectedPermissions, setSelectedPermissions] = useState<number[]>([])
|
||||
const [currentAdmin, setCurrentAdmin] = useState<any | null>(null)
|
||||
const [canEditPermissions, setCanEditPermissions] = useState(false)
|
||||
|
||||
const permissions = [
|
||||
{ id: "project_management", label: "项目管理" },
|
||||
{ id: "customer_pool", label: "客户池" },
|
||||
{ id: "admin_management", label: "管理员权限" },
|
||||
]
|
||||
// 加载管理员详情和菜单权限
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
// 获取当前登录的管理员信息
|
||||
const currentAdminInfo = getAdminInfo()
|
||||
setCurrentAdmin(currentAdminInfo)
|
||||
|
||||
// 获取管理员详情
|
||||
const adminResponse = await getAdministratorDetail(params.id)
|
||||
|
||||
if (adminResponse.code === 200 && adminResponse.data) {
|
||||
setAdminInfo(adminResponse.data)
|
||||
setUsername(adminResponse.data.username)
|
||||
setName(adminResponse.data.name)
|
||||
|
||||
// 判断是否可以编辑权限
|
||||
// 只有超级管理员(ID为1)可以编辑其他人的权限
|
||||
// 编辑自己时不能修改权限
|
||||
const isEditingSelf = currentAdminInfo && parseInt(params.id) === currentAdminInfo.id
|
||||
const isSuperAdmin = currentAdminInfo && currentAdminInfo.id === 1
|
||||
|
||||
setCanEditPermissions(!!(isSuperAdmin && !isEditingSelf))
|
||||
|
||||
// 如果可以编辑权限,则获取菜单权限
|
||||
if (isSuperAdmin && !isEditingSelf) {
|
||||
const menuResponse = await getTopLevelMenus()
|
||||
if (menuResponse.code === 200 && menuResponse.data) {
|
||||
setMenuPermissions(menuResponse.data)
|
||||
|
||||
// 获取管理员已有的权限
|
||||
const permissionsResponse = await getAdministratorDetail(params.id)
|
||||
if (permissionsResponse.code === 200 && permissionsResponse.data) {
|
||||
// 如果有权限数据,则设置选中的权限
|
||||
if (permissionsResponse.data.permissions) {
|
||||
// 假设权限是存储为菜单ID的数组
|
||||
setSelectedPermissions(permissionsResponse.data.permissions.map((p: any) => p.id || p))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
toast({
|
||||
title: "获取管理员详情失败",
|
||||
description: adminResponse.msg || "请稍后重试",
|
||||
variant: "destructive",
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("获取数据出错:", error)
|
||||
toast({
|
||||
title: "获取数据失败",
|
||||
description: "请检查网络连接后重试",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const [selectedPermissions, setSelectedPermissions] = useState<string[]>(adminData.permissions)
|
||||
fetchData()
|
||||
}, [params.id])
|
||||
|
||||
const togglePermission = (permissionId: string) => {
|
||||
// 切换权限选择
|
||||
const togglePermission = (permissionId: number) => {
|
||||
setSelectedPermissions((prev) =>
|
||||
prev.includes(permissionId) ? prev.filter((id) => id !== permissionId) : [...prev, permissionId],
|
||||
)
|
||||
}
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
// 提交表单
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
// 验证密码
|
||||
if (password && password !== confirmPassword) {
|
||||
toast({
|
||||
title: "密码不匹配",
|
||||
description: "两次输入的密码不一致",
|
||||
variant: "destructive",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Simulate API call
|
||||
setTimeout(() => {
|
||||
|
||||
try {
|
||||
// 准备提交的数据
|
||||
const updateData: any = {
|
||||
username,
|
||||
name,
|
||||
}
|
||||
|
||||
// 如果有设置密码,则添加密码字段
|
||||
if (password) {
|
||||
updateData.password = password
|
||||
}
|
||||
|
||||
// 如果可以编辑权限,则添加权限字段
|
||||
if (canEditPermissions) {
|
||||
updateData.permissionIds = selectedPermissions
|
||||
}
|
||||
|
||||
// 调用更新API
|
||||
const response = await updateAdministrator(params.id, updateData)
|
||||
|
||||
if (response.code === 200) {
|
||||
toast({
|
||||
title: "更新成功",
|
||||
description: "管理员信息已更新",
|
||||
variant: "success",
|
||||
})
|
||||
|
||||
// 更新成功后返回列表页
|
||||
router.push("/dashboard/admins")
|
||||
} else {
|
||||
toast({
|
||||
title: "更新失败",
|
||||
description: response.msg || "请稍后重试",
|
||||
variant: "destructive",
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("更新管理员信息出错:", error)
|
||||
toast({
|
||||
title: "更新失败",
|
||||
description: "请检查网络连接后重试",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
router.push("/dashboard/admins")
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex h-[calc(100vh-200px)] items-center justify-center">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
<p className="text-sm text-muted-foreground">加载管理员详情中...</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -94,39 +225,60 @@ export default function EditAdminPage({ params }: { params: { id: string } }) {
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">重置密码</Label>
|
||||
<Input id="password" type="password" placeholder="留空则不修改密码" />
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="留空则不修改密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">确认密码</Label>
|
||||
<Input id="confirmPassword" type="password" placeholder="留空则不修改密码" />
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
placeholder="留空则不修改密码"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label>权限设置</Label>
|
||||
<div className="grid gap-2">
|
||||
{permissions.map((permission) => (
|
||||
<div key={permission.id} className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={permission.id}
|
||||
checked={selectedPermissions.includes(permission.id)}
|
||||
onCheckedChange={() => togglePermission(permission.id)}
|
||||
/>
|
||||
<Label htmlFor={permission.id} className="cursor-pointer">
|
||||
{permission.label}
|
||||
</Label>
|
||||
</div>
|
||||
))}
|
||||
{canEditPermissions && (
|
||||
<div className="space-y-3">
|
||||
<Label>权限设置</Label>
|
||||
<div className="grid gap-2">
|
||||
{menuPermissions.map((menu) => (
|
||||
<div key={menu.id} className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={`menu-${menu.id}`}
|
||||
checked={selectedPermissions.includes(menu.id)}
|
||||
onCheckedChange={() => togglePermission(menu.id)}
|
||||
/>
|
||||
<Label htmlFor={`menu-${menu.id}`} className="cursor-pointer">
|
||||
{menu.title}
|
||||
</Label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
<CardFooter className="flex justify-end gap-2">
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/dashboard/admins">取消</Link>
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? "保存中..." : "保存修改"}
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
保存中...
|
||||
</>
|
||||
) : (
|
||||
"保存修改"
|
||||
)}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
|
||||
@@ -2,43 +2,143 @@
|
||||
|
||||
import type React from "react"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useState, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { ArrowLeft } from "lucide-react"
|
||||
import { ArrowLeft, Loader2 } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { addAdministrator } from "@/lib/admin-api"
|
||||
import { useToast } from "@/components/ui/use-toast"
|
||||
import { getTopLevelMenus } from "@/lib/menu-api"
|
||||
import { getAdminInfo } from "@/lib/utils"
|
||||
|
||||
interface MenuPermission {
|
||||
id: number;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export default function NewAdminPage() {
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const [username, setUsername] = useState("")
|
||||
const [name, setName] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [confirmPassword, setConfirmPassword] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [menuPermissions, setMenuPermissions] = useState<MenuPermission[]>([])
|
||||
const [selectedPermissions, setSelectedPermissions] = useState<number[]>([])
|
||||
const [canManagePermissions, setCanManagePermissions] = useState(false)
|
||||
|
||||
const permissions = [
|
||||
{ id: "project_management", label: "项目管理" },
|
||||
{ id: "customer_pool", label: "客户池" },
|
||||
{ id: "admin_management", label: "管理员权限" },
|
||||
]
|
||||
// 加载权限数据
|
||||
useEffect(() => {
|
||||
const loadPermissions = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
// 获取当前登录的管理员
|
||||
const currentAdmin = getAdminInfo()
|
||||
|
||||
// 只有超级管理员(ID为1)可以管理权限
|
||||
if (currentAdmin && currentAdmin.id === 1) {
|
||||
setCanManagePermissions(true)
|
||||
|
||||
// 获取菜单权限
|
||||
const response = await getTopLevelMenus()
|
||||
if (response.code === 200 && response.data) {
|
||||
setMenuPermissions(response.data)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("获取权限数据失败:", error)
|
||||
toast({
|
||||
title: "获取权限数据失败",
|
||||
description: "请检查网络连接后重试",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
loadPermissions()
|
||||
}, [])
|
||||
|
||||
const [selectedPermissions, setSelectedPermissions] = useState<string[]>([])
|
||||
|
||||
const togglePermission = (permissionId: string) => {
|
||||
const togglePermission = (permissionId: number) => {
|
||||
setSelectedPermissions((prev) =>
|
||||
prev.includes(permissionId) ? prev.filter((id) => id !== permissionId) : [...prev, permissionId],
|
||||
)
|
||||
}
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
// 验证密码
|
||||
if (!password) {
|
||||
toast({
|
||||
title: "密码不能为空",
|
||||
description: "添加管理员时必须设置密码",
|
||||
variant: "destructive",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
toast({
|
||||
title: "密码不匹配",
|
||||
description: "两次输入的密码不一致",
|
||||
variant: "destructive",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Simulate API call
|
||||
setTimeout(() => {
|
||||
|
||||
try {
|
||||
// 准备提交数据
|
||||
const data: any = {
|
||||
username,
|
||||
name,
|
||||
password,
|
||||
}
|
||||
|
||||
// 如果可以管理权限,则添加权限设置
|
||||
if (canManagePermissions && selectedPermissions.length > 0) {
|
||||
data.permissionIds = selectedPermissions
|
||||
}
|
||||
|
||||
// 调用添加API
|
||||
const response = await addAdministrator(data)
|
||||
|
||||
if (response.code === 200) {
|
||||
toast({
|
||||
title: "添加成功",
|
||||
description: "管理员账号已成功添加",
|
||||
variant: "success",
|
||||
})
|
||||
|
||||
// 返回管理员列表页
|
||||
router.push("/dashboard/admins")
|
||||
} else {
|
||||
toast({
|
||||
title: "添加失败",
|
||||
description: response.msg || "请稍后重试",
|
||||
variant: "destructive",
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("添加管理员出错:", error)
|
||||
toast({
|
||||
title: "添加失败",
|
||||
description: "请检查网络连接后重试",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
router.push("/dashboard/admins")
|
||||
}, 1500)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -56,55 +156,97 @@ export default function NewAdminPage() {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>管理员信息</CardTitle>
|
||||
<CardDescription>创建新管理员账号并设置权限</CardDescription>
|
||||
<CardDescription>创建新的管理员账号</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">账号</Label>
|
||||
<Input id="username" placeholder="请输入账号" required />
|
||||
<Input
|
||||
id="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="请输入账号"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">姓名</Label>
|
||||
<Input id="name" placeholder="请输入姓名" required />
|
||||
<Input
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="请输入姓名"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">密码</Label>
|
||||
<Input id="password" type="password" placeholder="请设置密码" required />
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="请输入密码"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">确认密码</Label>
|
||||
<Input id="confirmPassword" type="password" placeholder="请再次输入密码" required />
|
||||
<Label htmlFor="confirm-password">确认密码</Label>
|
||||
<Input
|
||||
id="confirm-password"
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="请再次输入密码"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label>权限设置</Label>
|
||||
<div className="grid gap-2">
|
||||
{permissions.map((permission) => (
|
||||
<div key={permission.id} className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={permission.id}
|
||||
checked={selectedPermissions.includes(permission.id)}
|
||||
onCheckedChange={() => togglePermission(permission.id)}
|
||||
/>
|
||||
<Label htmlFor={permission.id} className="cursor-pointer">
|
||||
{permission.label}
|
||||
</Label>
|
||||
</div>
|
||||
))}
|
||||
{canManagePermissions && (
|
||||
<div className="space-y-3">
|
||||
<Label>权限设置</Label>
|
||||
<div className="grid gap-2">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-sm text-muted-foreground">加载权限数据中...</span>
|
||||
</div>
|
||||
) : (
|
||||
menuPermissions.map((menu) => (
|
||||
<div key={menu.id} className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={`menu-${menu.id}`}
|
||||
checked={selectedPermissions.includes(menu.id)}
|
||||
onCheckedChange={() => togglePermission(menu.id)}
|
||||
/>
|
||||
<Label htmlFor={`menu-${menu.id}`} className="cursor-pointer">
|
||||
{menu.title}
|
||||
</Label>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
<CardFooter className="flex justify-end gap-2">
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/dashboard/admins">取消</Link>
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? "创建中..." : "创建管理员"}
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
创建中...
|
||||
</>
|
||||
) : (
|
||||
"创建管理员"
|
||||
)}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
|
||||
@@ -1,15 +1,27 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useState, useEffect } from "react"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Search, MoreHorizontal, Edit, Trash, UserPlus } from "lucide-react"
|
||||
import { Search, MoreHorizontal, Edit, Trash, UserPlus, Loader2 } from "lucide-react"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { useToast } from "@/components/ui/use-toast"
|
||||
import { getAdministrators, deleteAdministrator, Administrator } from "@/lib/admin-api"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
|
||||
// Sample admin data
|
||||
// 保留原始示例数据,作为加载失败时的备用数据
|
||||
const adminsData = [
|
||||
{
|
||||
id: "1",
|
||||
@@ -51,13 +63,124 @@ const adminsData = [
|
||||
|
||||
export default function AdminsPage() {
|
||||
const [searchTerm, setSearchTerm] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
const [administrators, setAdministrators] = useState<Administrator[]>([])
|
||||
const [totalCount, setTotalCount] = useState(0)
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize] = useState(10)
|
||||
const { toast } = useToast()
|
||||
|
||||
// 删除对话框状态
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||
const [adminToDelete, setAdminToDelete] = useState<Administrator | null>(null)
|
||||
|
||||
const filteredAdmins = adminsData.filter(
|
||||
(admin) =>
|
||||
admin.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
admin.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
admin.role.toLowerCase().includes(searchTerm.toLowerCase()),
|
||||
)
|
||||
// 加载管理员列表
|
||||
useEffect(() => {
|
||||
fetchAdministrators()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [currentPage])
|
||||
|
||||
// 获取管理员列表
|
||||
const fetchAdministrators = async (keyword: string = searchTerm) => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const response = await getAdministrators(currentPage, pageSize, keyword)
|
||||
if (response.code === 200 && response.data) {
|
||||
setAdministrators(response.data.list)
|
||||
setTotalCount(response.data.total)
|
||||
} else {
|
||||
toast({
|
||||
title: "获取管理员列表失败",
|
||||
description: response.msg || "请稍后重试",
|
||||
variant: "destructive",
|
||||
})
|
||||
// 加载失败时显示示例数据
|
||||
setAdministrators(adminsData.map(admin => ({
|
||||
...admin,
|
||||
id: Number(admin.id)
|
||||
})) as Administrator[])
|
||||
setTotalCount(adminsData.length)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("获取管理员列表出错:", error)
|
||||
toast({
|
||||
title: "获取管理员列表失败",
|
||||
description: "请检查网络连接后重试",
|
||||
variant: "destructive",
|
||||
})
|
||||
// 加载失败时显示示例数据
|
||||
setAdministrators(adminsData.map(admin => ({
|
||||
...admin,
|
||||
id: Number(admin.id)
|
||||
})) as Administrator[])
|
||||
setTotalCount(adminsData.length)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理搜索
|
||||
const handleSearch = () => {
|
||||
setCurrentPage(1) // 重置为第一页
|
||||
fetchAdministrators()
|
||||
}
|
||||
|
||||
// Enter键搜索
|
||||
const handleSearchKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === "Enter") {
|
||||
handleSearch()
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否为超级管理员(id为1)
|
||||
const isSuperAdmin = (id: number) => {
|
||||
return id === 1
|
||||
}
|
||||
|
||||
// 打开删除确认对话框
|
||||
const openDeleteDialog = (admin: Administrator) => {
|
||||
setAdminToDelete(admin)
|
||||
setDeleteDialogOpen(true)
|
||||
}
|
||||
|
||||
// 确认删除管理员
|
||||
const confirmDelete = async () => {
|
||||
if (!adminToDelete) return
|
||||
|
||||
setIsDeleting(true)
|
||||
try {
|
||||
const response = await deleteAdministrator(adminToDelete.id)
|
||||
|
||||
if (response.code === 200) {
|
||||
toast({
|
||||
title: "删除成功",
|
||||
description: `管理员 ${adminToDelete.name} 已成功删除`,
|
||||
variant: "success",
|
||||
})
|
||||
|
||||
// 重新获取管理员列表
|
||||
fetchAdministrators()
|
||||
} else {
|
||||
toast({
|
||||
title: "删除失败",
|
||||
description: response.msg || "请稍后重试",
|
||||
variant: "destructive",
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("删除管理员出错:", error)
|
||||
toast({
|
||||
title: "删除失败",
|
||||
description: "请检查网络连接后重试",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setIsDeleting(false)
|
||||
setDeleteDialogOpen(false)
|
||||
setAdminToDelete(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -79,8 +202,10 @@ export default function AdminsPage() {
|
||||
className="pl-8"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
onKeyDown={handleSearchKeyDown}
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={handleSearch}>搜索</Button>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border">
|
||||
@@ -97,8 +222,16 @@ export default function AdminsPage() {
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{filteredAdmins.length > 0 ? (
|
||||
filteredAdmins.map((admin) => (
|
||||
{isLoading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} className="h-24 text-center">
|
||||
<div className="flex justify-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-primary" />
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : administrators.length > 0 ? (
|
||||
administrators.map((admin) => (
|
||||
<TableRow key={admin.id}>
|
||||
<TableCell className="font-medium">{admin.username}</TableCell>
|
||||
<TableCell>{admin.name}</TableCell>
|
||||
@@ -130,9 +263,14 @@ export default function AdminsPage() {
|
||||
<Edit className="mr-2 h-4 w-4" /> 编辑管理员
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive">
|
||||
<Trash className="mr-2 h-4 w-4" /> 删除管理员
|
||||
</DropdownMenuItem>
|
||||
{!isSuperAdmin(admin.id) && (
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={() => openDeleteDialog(admin)}
|
||||
>
|
||||
<Trash className="mr-2 h-4 w-4" /> 删除管理员
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
@@ -148,6 +286,59 @@ export default function AdminsPage() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{totalCount > pageSize && (
|
||||
<div className="flex justify-center gap-2 mt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
|
||||
disabled={currentPage === 1 || isLoading}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<span className="py-2 px-4 text-sm">
|
||||
第 {currentPage} 页 / 共 {Math.ceil(totalCount / pageSize)} 页
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage((prev) => prev + 1)}
|
||||
disabled={currentPage >= Math.ceil(totalCount / pageSize) || isLoading}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 删除确认对话框 */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确认删除管理员</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
您确定要删除管理员 "{adminToDelete?.name}" 吗?此操作无法撤销。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isDeleting}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmDelete}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
删除中...
|
||||
</>
|
||||
) : (
|
||||
"确认删除"
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"use client"
|
||||
|
||||
import type React from "react"
|
||||
|
||||
import { useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { usePathname } from "next/navigation"
|
||||
import { useState, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { LayoutDashboard, Users, Settings, LogOut, Menu, X } from "lucide-react"
|
||||
import { Menu, X } from "lucide-react"
|
||||
import { Sidebar } from "@/components/layout/sidebar"
|
||||
import { Header } from "@/components/layout/header"
|
||||
import { getAdminInfo } from "@/lib/utils"
|
||||
|
||||
export default function DashboardLayout({
|
||||
children,
|
||||
@@ -14,25 +15,20 @@ export default function DashboardLayout({
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const [sidebarOpen, setSidebarOpen] = useState(true)
|
||||
const pathname = usePathname()
|
||||
|
||||
const navItems = [
|
||||
{
|
||||
title: "项目管理",
|
||||
href: "/dashboard/projects",
|
||||
icon: <LayoutDashboard className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
title: "客户池",
|
||||
href: "/dashboard/customers",
|
||||
icon: <Users className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
title: "管理员权限",
|
||||
href: "/dashboard/admins",
|
||||
icon: <Settings className="h-5 w-5" />,
|
||||
},
|
||||
]
|
||||
const router = useRouter()
|
||||
|
||||
// 认证检查
|
||||
useEffect(() => {
|
||||
const checkAuth = () => {
|
||||
const adminInfo = getAdminInfo()
|
||||
if (!adminInfo) {
|
||||
// 未登录时跳转到登录页
|
||||
router.push('/login')
|
||||
}
|
||||
}
|
||||
|
||||
checkAuth()
|
||||
}, [router])
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden">
|
||||
@@ -45,55 +41,17 @@ export default function DashboardLayout({
|
||||
|
||||
{/* Sidebar */}
|
||||
<div
|
||||
className={`bg-primary text-primary-foreground w-64 flex-shrink-0 transition-all duration-300 ease-in-out ${
|
||||
className={`bg-background border-r w-64 flex-shrink-0 transition-all duration-300 ease-in-out ${
|
||||
sidebarOpen ? "translate-x-0" : "-translate-x-full"
|
||||
} md:translate-x-0 fixed md:relative z-40 h-full`}
|
||||
>
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex items-center justify-center h-16 border-b border-primary/10">
|
||||
<h1 className="text-xl font-bold">超级管理员后台</h1>
|
||||
</div>
|
||||
<nav className="flex-1 overflow-y-auto py-4">
|
||||
<ul className="space-y-1 px-2">
|
||||
{navItems.map((item) => (
|
||||
<li key={item.href}>
|
||||
<Link
|
||||
href={item.href}
|
||||
className={`flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors hover:bg-primary-foreground hover:text-primary ${
|
||||
pathname.startsWith(item.href) ? "bg-primary-foreground text-primary" : ""
|
||||
}`}
|
||||
>
|
||||
{item.icon}
|
||||
{item.title}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
<div className="border-t border-primary/10 p-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start gap-2 bg-transparent text-primary-foreground hover:bg-primary-foreground hover:text-primary"
|
||||
onClick={() => {
|
||||
// Handle logout
|
||||
window.location.href = "/login"
|
||||
}}
|
||||
>
|
||||
<LogOut className="h-5 w-5" />
|
||||
退出登录
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Sidebar />
|
||||
</div>
|
||||
|
||||
{/* Main content */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<header className="h-16 border-b flex items-center px-6 bg-background">
|
||||
<h2 className="text-lg font-medium">
|
||||
{navItems.find((item) => pathname.startsWith(item.href))?.title || "仪表盘"}
|
||||
</h2>
|
||||
</header>
|
||||
<main className="p-6">{children}</main>
|
||||
<div className="flex-1 flex flex-col overflow-hidden">
|
||||
<Header />
|
||||
<main className="flex-1 overflow-y-auto p-6">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -17,28 +17,26 @@ export default function DashboardPage() {
|
||||
const adminInfo = localStorage.getItem("admin_info")
|
||||
if (adminInfo) {
|
||||
try {
|
||||
const { name } = JSON.parse(adminInfo)
|
||||
setUserName(name || "管理员")
|
||||
const userData = JSON.parse(adminInfo)
|
||||
setUserName(userData.name || "管理员")
|
||||
} catch (err) {
|
||||
console.error("解析用户信息失败:", err)
|
||||
setUserName("管理员")
|
||||
}
|
||||
}
|
||||
|
||||
// 获取当前时间
|
||||
const hour = new Date().getHours()
|
||||
let timeGreeting = ""
|
||||
|
||||
if (hour >= 5 && hour < 12) {
|
||||
timeGreeting = "上午好"
|
||||
setGreeting("上午好")
|
||||
} else if (hour >= 12 && hour < 14) {
|
||||
timeGreeting = "中午好"
|
||||
setGreeting("中午好")
|
||||
} else if (hour >= 14 && hour < 18) {
|
||||
timeGreeting = "下午好"
|
||||
setGreeting("下午好")
|
||||
} else {
|
||||
timeGreeting = "晚上好"
|
||||
setGreeting("晚上好")
|
||||
}
|
||||
|
||||
setGreeting(timeGreeting)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Metadata } from "next"
|
||||
import { Inter } from "next/font/google"
|
||||
import "./globals.css"
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { ToastProvider } from "@/components/ui/use-toast"
|
||||
|
||||
const inter = Inter({ subsets: ["latin"] })
|
||||
|
||||
@@ -21,7 +22,9 @@ export default function RootLayout({
|
||||
<html lang="zh-CN" suppressHydrationWarning>
|
||||
<body className={inter.className}>
|
||||
<ThemeProvider attribute="class" defaultTheme="light" enableSystem disableTransitionOnChange>
|
||||
{children}
|
||||
<ToastProvider>
|
||||
{children}
|
||||
</ToastProvider>
|
||||
</ThemeProvider>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -8,52 +8,58 @@ import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { md5 } from "@/lib/utils"
|
||||
import { md5, saveAdminInfo } from "@/lib/utils"
|
||||
import { login } from "@/lib/admin-api"
|
||||
import { useToast } from "@/components/ui/use-toast"
|
||||
|
||||
export default function LoginPage() {
|
||||
const [username, setUsername] = useState("")
|
||||
const [account, setAccount] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [error, setError] = useState("")
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setIsLoading(true)
|
||||
setError("")
|
||||
|
||||
try {
|
||||
// 对密码进行MD5加密
|
||||
const encryptedPassword = md5(password)
|
||||
|
||||
// 调用登录接口
|
||||
const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/auth/login`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
account: username,
|
||||
password: encryptedPassword
|
||||
}),
|
||||
credentials: "include"
|
||||
})
|
||||
const result = await login(account, encryptedPassword)
|
||||
|
||||
const result = await response.json()
|
||||
|
||||
if (result.code === 200) {
|
||||
// 保存用户信息到本地存储
|
||||
localStorage.setItem("admin_info", JSON.stringify(result.data))
|
||||
localStorage.setItem("admin_token", result.data.token)
|
||||
if (result.code === 200 && result.data) {
|
||||
// 保存管理员信息
|
||||
saveAdminInfo(result.data)
|
||||
|
||||
// 显示成功提示
|
||||
toast({
|
||||
title: "登录成功",
|
||||
description: `欢迎回来,${result.data.name}`,
|
||||
variant: "success",
|
||||
})
|
||||
|
||||
// 跳转到仪表盘
|
||||
router.push("/dashboard")
|
||||
} else {
|
||||
setError(result.msg || "登录失败")
|
||||
// 显示错误提示
|
||||
toast({
|
||||
title: "登录失败",
|
||||
description: result.msg || "账号或密码错误",
|
||||
variant: "destructive",
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("登录失败:", err)
|
||||
setError("网络错误,请稍后再试")
|
||||
|
||||
// 显示错误提示
|
||||
toast({
|
||||
title: "登录失败",
|
||||
description: "网络错误,请稍后再试",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
@@ -65,17 +71,16 @@ export default function LoginPage() {
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl text-center">超级管理员后台</CardTitle>
|
||||
<CardDescription className="text-center">请输入您的账号和密码登录系统</CardDescription>
|
||||
{error && <p className="text-sm text-red-500 text-center">{error}</p>}
|
||||
</CardHeader>
|
||||
<form onSubmit={handleLogin}>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">账号</Label>
|
||||
<Label htmlFor="account">账号</Label>
|
||||
<Input
|
||||
id="username"
|
||||
id="account"
|
||||
placeholder="请输入账号"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
value={account}
|
||||
onChange={(e) => setAccount(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
77
SuperAdmin/components/layout/header.tsx
Normal file
77
SuperAdmin/components/layout/header.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { LogOut, Settings, User } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
|
||||
interface AdminInfo {
|
||||
id: number;
|
||||
name: string;
|
||||
account: string;
|
||||
}
|
||||
|
||||
export function Header() {
|
||||
const [adminInfo, setAdminInfo] = useState<AdminInfo | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// 从本地存储获取管理员信息
|
||||
const info = localStorage.getItem("admin_info")
|
||||
if (info) {
|
||||
try {
|
||||
setAdminInfo(JSON.parse(info))
|
||||
} catch (e) {
|
||||
console.error("解析管理员信息失败", e)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem("admin_token")
|
||||
localStorage.removeItem("admin_info")
|
||||
window.location.href = "/login"
|
||||
}
|
||||
|
||||
return (
|
||||
<header className="h-16 border-b px-6 flex items-center justify-between bg-background">
|
||||
<div className="flex-1"></div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-9 w-9 rounded-full p-0 relative">
|
||||
<span className="sr-only">用户菜单</span>
|
||||
<User className="h-5 w-5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<div className="px-2 py-1.5 text-sm font-medium">
|
||||
{adminInfo?.name || "管理员"}
|
||||
</div>
|
||||
<div className="px-2 py-1.5 text-xs text-muted-foreground">
|
||||
{adminInfo?.account || ""}
|
||||
</div>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="/settings" className="cursor-pointer flex items-center">
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
设置
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleLogout} className="cursor-pointer text-red-600">
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
退出登录
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
186
SuperAdmin/components/layout/sidebar.tsx
Normal file
186
SuperAdmin/components/layout/sidebar.tsx
Normal file
@@ -0,0 +1,186 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { usePathname } from "next/navigation"
|
||||
import { getMenus, type MenuItem } from "@/lib/menu-api"
|
||||
import * as LucideIcons from "lucide-react"
|
||||
import { ChevronDown, ChevronRight } from "lucide-react"
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname()
|
||||
const [menus, setMenus] = useState<MenuItem[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
// 使用Set来存储已展开的菜单ID
|
||||
const [expandedMenus, setExpandedMenus] = useState<Set<number>>(new Set())
|
||||
|
||||
useEffect(() => {
|
||||
const fetchMenus = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await getMenus()
|
||||
setMenus(data || [])
|
||||
|
||||
// 自动展开当前活动菜单的父菜单
|
||||
autoExpandActiveMenuParent(data || []);
|
||||
} catch (error) {
|
||||
console.error("获取菜单失败:", error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
fetchMenus()
|
||||
}, [])
|
||||
|
||||
// 自动展开当前活动菜单的父菜单
|
||||
const autoExpandActiveMenuParent = (menuItems: MenuItem[]) => {
|
||||
const newExpandedMenus = new Set<number>();
|
||||
|
||||
// 递归查找当前路径匹配的菜单项
|
||||
const findActiveMenu = (items: MenuItem[], parentIds: number[] = []) => {
|
||||
for (const item of items) {
|
||||
const currentPath = pathname === "/" ? "/dashboard" : pathname;
|
||||
const itemPath = item.path;
|
||||
|
||||
if (currentPath === itemPath || currentPath.startsWith(itemPath + "/")) {
|
||||
// 将所有父菜单ID添加到展开集合
|
||||
parentIds.forEach(id => newExpandedMenus.add(id));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (item.children && item.children.length > 0) {
|
||||
const found = findActiveMenu(item.children, [...parentIds, item.id]);
|
||||
if (found) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
findActiveMenu(menuItems);
|
||||
setExpandedMenus(newExpandedMenus);
|
||||
};
|
||||
|
||||
// 切换菜单展开状态
|
||||
const toggleMenu = (menuId: number) => {
|
||||
setExpandedMenus(prev => {
|
||||
const newExpanded = new Set(prev);
|
||||
if (newExpanded.has(menuId)) {
|
||||
newExpanded.delete(menuId);
|
||||
} else {
|
||||
newExpanded.add(menuId);
|
||||
}
|
||||
return newExpanded;
|
||||
});
|
||||
};
|
||||
|
||||
// 获取Lucide图标组件
|
||||
const getLucideIcon = (iconName: string) => {
|
||||
if (!iconName) return null;
|
||||
const Icon = (LucideIcons as any)[iconName];
|
||||
return Icon ? <Icon className="h-4 w-4 mr-2" /> : null;
|
||||
};
|
||||
|
||||
// 递归渲染菜单项
|
||||
const renderMenuItem = (item: MenuItem) => {
|
||||
const hasChildren = item.children && item.children.length > 0;
|
||||
const isExpanded = expandedMenus.has(item.id);
|
||||
const isActive = pathname === item.path;
|
||||
const isChildActive = hasChildren && item.children!.some(child =>
|
||||
pathname === child.path || pathname.startsWith(child.path + "/")
|
||||
);
|
||||
|
||||
return (
|
||||
<li key={item.id}>
|
||||
{hasChildren ? (
|
||||
<div className="flex flex-col">
|
||||
<button
|
||||
onClick={() => toggleMenu(item.id)}
|
||||
className={`flex items-center justify-between px-4 py-2 rounded-md text-sm w-full text-left ${
|
||||
isActive || isChildActive
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "hover:bg-accent hover:text-accent-foreground"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center">
|
||||
{item.icon && getLucideIcon(item.icon)}
|
||||
{item.title}
|
||||
</div>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{isExpanded && hasChildren && (
|
||||
<ul className="ml-4 mt-1 space-y-1">
|
||||
{item.children!.map(child => {
|
||||
const isChildItemActive = pathname === child.path;
|
||||
return (
|
||||
<li key={child.id}>
|
||||
<Link
|
||||
href={child.path}
|
||||
className={`flex items-center px-4 py-2 rounded-md text-sm ${
|
||||
isChildItemActive
|
||||
? "text-primary font-medium"
|
||||
: "hover:bg-accent hover:text-accent-foreground"
|
||||
}`}
|
||||
>
|
||||
{child.icon && getLucideIcon(child.icon)}
|
||||
{child.title}
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<Link
|
||||
href={item.path}
|
||||
className={`flex items-center px-4 py-2 rounded-md text-sm ${
|
||||
isActive
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "hover:bg-accent hover:text-accent-foreground"
|
||||
}`}
|
||||
>
|
||||
{item.icon && getLucideIcon(item.icon)}
|
||||
{item.title}
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-64 border-r bg-background h-full flex flex-col">
|
||||
<div className="p-4 border-b">
|
||||
<h2 className="text-lg font-bold">超级管理员</h2>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 overflow-auto p-2">
|
||||
{loading ? (
|
||||
// 加载状态
|
||||
<div className="space-y-2">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<div key={i} className="h-10 rounded animate-pulse bg-gray-200"></div>
|
||||
))}
|
||||
</div>
|
||||
) : menus.length > 0 ? (
|
||||
// 菜单项
|
||||
<ul className="space-y-1">
|
||||
{menus.map(renderMenuItem)}
|
||||
</ul>
|
||||
) : (
|
||||
// 无菜单数据
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
<p>暂无菜单数据</p>
|
||||
</div>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,12 @@ const AlertDialog = AlertDialogPrimitive.Root
|
||||
|
||||
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
|
||||
|
||||
const AlertDialogPortal = AlertDialogPrimitive.Portal
|
||||
const AlertDialogPortal = ({
|
||||
...props
|
||||
}: AlertDialogPrimitive.AlertDialogPortalProps) => (
|
||||
<AlertDialogPrimitive.Portal {...props} />
|
||||
)
|
||||
AlertDialogPortal.displayName = AlertDialogPrimitive.Portal.displayName
|
||||
|
||||
const AlertDialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
|
||||
@@ -18,7 +23,7 @@ const AlertDialogOverlay = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
@@ -36,7 +41,7 @@ const AlertDialogContent = React.forwardRef<
|
||||
<AlertDialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
@@ -128,8 +133,6 @@ AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
|
||||
@@ -35,7 +35,7 @@ const ScrollBar = React.forwardRef<
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent p-[1px]",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
|
||||
"h-2.5 border-t border-t-transparent p-[1px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -1,129 +1,61 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ToastPrimitives from "@radix-ui/react-toast"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { X } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const ToastProvider = ToastPrimitives.Provider
|
||||
|
||||
const ToastViewport = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Viewport>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Viewport
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
|
||||
|
||||
const toastVariants = cva(
|
||||
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border bg-background text-foreground",
|
||||
destructive:
|
||||
"destructive group border-destructive bg-destructive text-destructive-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
const Toast = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
|
||||
VariantProps<typeof toastVariants>
|
||||
>(({ className, variant, ...props }, ref) => {
|
||||
return (
|
||||
<ToastPrimitives.Root
|
||||
ref={ref}
|
||||
className={cn(toastVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
Toast.displayName = ToastPrimitives.Root.displayName
|
||||
|
||||
const ToastAction = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Action
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastAction.displayName = ToastPrimitives.Action.displayName
|
||||
|
||||
const ToastClose = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Close>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Close
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
|
||||
className
|
||||
)}
|
||||
toast-close=""
|
||||
{...props}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</ToastPrimitives.Close>
|
||||
))
|
||||
ToastClose.displayName = ToastPrimitives.Close.displayName
|
||||
|
||||
const ToastTitle = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Title
|
||||
ref={ref}
|
||||
className={cn("text-sm font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastTitle.displayName = ToastPrimitives.Title.displayName
|
||||
|
||||
const ToastDescription = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm opacity-90", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastDescription.displayName = ToastPrimitives.Description.displayName
|
||||
|
||||
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
|
||||
|
||||
type ToastActionElement = React.ReactElement<typeof ToastAction>
|
||||
|
||||
export {
|
||||
type ToastProps,
|
||||
type ToastActionElement,
|
||||
ToastProvider,
|
||||
ToastViewport,
|
||||
Toast,
|
||||
ToastTitle,
|
||||
ToastDescription,
|
||||
ToastClose,
|
||||
ToastAction,
|
||||
interface ToastProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
variant?: "default" | "destructive" | "success"
|
||||
onDismiss?: () => void
|
||||
title?: string
|
||||
description?: string
|
||||
action?: React.ReactNode
|
||||
}
|
||||
|
||||
export const ToastProvider = React.Fragment
|
||||
|
||||
export function Toast({
|
||||
className,
|
||||
variant = "default",
|
||||
onDismiss,
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
...props
|
||||
}: ToastProps) {
|
||||
const variantStyles = {
|
||||
default: "bg-background text-foreground",
|
||||
destructive: "bg-destructive text-destructive-foreground",
|
||||
success: "bg-green-500 text-white"
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-4 pr-8 shadow-lg transition-all",
|
||||
variantStyles[variant],
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex flex-col gap-1">
|
||||
{title && <p className="font-medium">{title}</p>}
|
||||
{description && <p className="text-sm opacity-90">{description}</p>}
|
||||
</div>
|
||||
{action}
|
||||
<button
|
||||
onClick={onDismiss}
|
||||
className="absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ToastViewport() {
|
||||
return (
|
||||
<div className="fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse gap-2 p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]"></div>
|
||||
)
|
||||
}
|
||||
|
||||
65
SuperAdmin/components/ui/use-toast.tsx
Normal file
65
SuperAdmin/components/ui/use-toast.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
"use client"
|
||||
|
||||
import { createContext, useContext, useState, useEffect, ReactNode } from "react"
|
||||
import { Toast, ToastProvider, ToastViewport } from "@/components/ui/toast"
|
||||
|
||||
type ToastProps = {
|
||||
id: string
|
||||
title?: string
|
||||
description?: string
|
||||
variant?: "default" | "destructive" | "success"
|
||||
action?: ReactNode
|
||||
}
|
||||
|
||||
interface ToastContextValue {
|
||||
toast: (props: Omit<ToastProps, "id">) => void
|
||||
dismiss: (id: string) => void
|
||||
toasts: ToastProps[]
|
||||
}
|
||||
|
||||
const ToastContext = createContext<ToastContextValue | null>(null)
|
||||
|
||||
export function useToast() {
|
||||
const context = useContext(ToastContext)
|
||||
if (context === null) {
|
||||
throw new Error("useToast must be used within a ToastProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
interface ToastProviderProps {
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export function ToastProvider({ children }: ToastProviderProps) {
|
||||
const [toasts, setToasts] = useState<ToastProps[]>([])
|
||||
|
||||
const toast = (props: Omit<ToastProps, "id">) => {
|
||||
const id = Math.random().toString(36).substring(2, 9)
|
||||
setToasts((prev) => [...prev, { id, ...props }])
|
||||
}
|
||||
|
||||
const dismiss = (id: string) => {
|
||||
setToasts((prev) => prev.filter((toast) => toast.id !== id))
|
||||
}
|
||||
|
||||
// 自动移除
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
if (toasts.length > 0) {
|
||||
setToasts((prev) => prev.slice(1))
|
||||
}
|
||||
}, 5000)
|
||||
return () => clearTimeout(timer)
|
||||
}, [toasts])
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={{ toast, dismiss, toasts }}>
|
||||
{children}
|
||||
<ToastViewport />
|
||||
{toasts.map((props) => (
|
||||
<Toast key={props.id} {...props} onDismiss={() => dismiss(props.id)} />
|
||||
))}
|
||||
</ToastContext.Provider>
|
||||
)
|
||||
}
|
||||
133
SuperAdmin/lib/admin-api.ts
Normal file
133
SuperAdmin/lib/admin-api.ts
Normal file
@@ -0,0 +1,133 @@
|
||||
import { apiRequest, ApiResponse } from './api-utils';
|
||||
|
||||
// 管理员接口数据类型定义
|
||||
export interface Administrator {
|
||||
id: number;
|
||||
username: string;
|
||||
name: string;
|
||||
role: string;
|
||||
status: number;
|
||||
createdAt: string;
|
||||
lastLogin: string;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
// 管理员详情接口
|
||||
export interface AdministratorDetail {
|
||||
id: number;
|
||||
username: string;
|
||||
name: string;
|
||||
authId: number;
|
||||
roleName: string;
|
||||
status: number;
|
||||
createdAt: string;
|
||||
lastLogin: string;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
// 分页响应数据类型
|
||||
export interface PaginatedResponse<T> {
|
||||
list: T[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员登录
|
||||
* @param account 账号
|
||||
* @param password 密码
|
||||
* @returns 登录结果
|
||||
*/
|
||||
export async function login(
|
||||
account: string,
|
||||
password: string
|
||||
): Promise<ApiResponse<{
|
||||
id: number;
|
||||
name: string;
|
||||
account: string;
|
||||
token: string;
|
||||
}>> {
|
||||
return apiRequest('/auth/login', 'POST', {
|
||||
account,
|
||||
password
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取管理员列表
|
||||
* @param page 页码
|
||||
* @param limit 每页数量
|
||||
* @param keyword 搜索关键词
|
||||
* @returns 管理员列表
|
||||
*/
|
||||
export async function getAdministrators(
|
||||
page: number = 1,
|
||||
limit: number = 10,
|
||||
keyword: string = ''
|
||||
): Promise<ApiResponse<PaginatedResponse<Administrator>>> {
|
||||
// 构建查询参数
|
||||
const params = new URLSearchParams();
|
||||
params.append('page', page.toString());
|
||||
params.append('limit', limit.toString());
|
||||
if (keyword) {
|
||||
params.append('keyword', keyword);
|
||||
}
|
||||
|
||||
return apiRequest(`/administrator/list?${params.toString()}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取管理员详情
|
||||
* @param id 管理员ID
|
||||
* @returns 管理员详情
|
||||
*/
|
||||
export async function getAdministratorDetail(id: number | string): Promise<ApiResponse<AdministratorDetail>> {
|
||||
return apiRequest(`/administrator/detail/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新管理员信息
|
||||
* @param id 管理员ID
|
||||
* @param data 更新的数据
|
||||
* @returns 更新结果
|
||||
*/
|
||||
export async function updateAdministrator(
|
||||
id: number | string,
|
||||
data: {
|
||||
username: string;
|
||||
name: string;
|
||||
password?: string;
|
||||
permissionIds?: number[];
|
||||
}
|
||||
): Promise<ApiResponse<null>> {
|
||||
return apiRequest('/administrator/update', 'POST', {
|
||||
id,
|
||||
...data
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加管理员
|
||||
* @param data 管理员数据
|
||||
* @returns 添加结果
|
||||
*/
|
||||
export async function addAdministrator(
|
||||
data: {
|
||||
username: string;
|
||||
name: string;
|
||||
password: string;
|
||||
permissionIds?: number[];
|
||||
}
|
||||
): Promise<ApiResponse<null>> {
|
||||
return apiRequest('/administrator/add', 'POST', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除管理员
|
||||
* @param id 管理员ID
|
||||
* @returns 删除结果
|
||||
*/
|
||||
export async function deleteAdministrator(id: number | string): Promise<ApiResponse<null>> {
|
||||
return apiRequest('/administrator/delete', 'POST', { id });
|
||||
}
|
||||
83
SuperAdmin/lib/api-utils.ts
Normal file
83
SuperAdmin/lib/api-utils.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { getConfig } from './config';
|
||||
import { getAdminInfo, clearAdminInfo } from './utils';
|
||||
|
||||
/**
|
||||
* API响应数据结构
|
||||
*/
|
||||
export interface ApiResponse<T = any> {
|
||||
code: number;
|
||||
msg: string;
|
||||
data: T | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用API请求函数
|
||||
* @param endpoint API端点
|
||||
* @param method HTTP方法
|
||||
* @param data 请求数据
|
||||
* @returns API响应
|
||||
*/
|
||||
export async function apiRequest<T = any>(
|
||||
endpoint: string,
|
||||
method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET',
|
||||
data?: any
|
||||
): Promise<ApiResponse<T>> {
|
||||
const { apiBaseUrl } = getConfig();
|
||||
const url = `${apiBaseUrl}${endpoint}`;
|
||||
|
||||
// 获取认证信息
|
||||
const adminInfo = getAdminInfo();
|
||||
|
||||
// 请求头
|
||||
const headers: HeadersInit = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
// 如果有认证信息,添加Cookie头
|
||||
if (adminInfo?.token) {
|
||||
// 添加认证令牌,作为Cookie发送
|
||||
document.cookie = `admin_id=${adminInfo.id}; path=/`;
|
||||
document.cookie = `admin_token=${adminInfo.token}; path=/`;
|
||||
}
|
||||
|
||||
// 请求配置
|
||||
const config: RequestInit = {
|
||||
method,
|
||||
headers,
|
||||
credentials: 'include', // 包含跨域请求的Cookie
|
||||
};
|
||||
|
||||
// 如果有请求数据,转换为JSON
|
||||
if (data && method !== 'GET') {
|
||||
config.body = JSON.stringify(data);
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(url, config);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`请求失败: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json() as ApiResponse<T>;
|
||||
|
||||
// 如果返回未授权错误,清除登录信息
|
||||
if (result.code === 401) {
|
||||
clearAdminInfo();
|
||||
// 如果在浏览器环境,跳转到登录页
|
||||
if (typeof window !== 'undefined') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('API请求错误:', error);
|
||||
|
||||
return {
|
||||
code: 500,
|
||||
msg: error instanceof Error ? error.message : '未知错误',
|
||||
data: null
|
||||
};
|
||||
}
|
||||
}
|
||||
12
SuperAdmin/lib/config.ts
Normal file
12
SuperAdmin/lib/config.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* 获取应用配置
|
||||
* @returns 应用配置
|
||||
*/
|
||||
export function getConfig() {
|
||||
// 优先获取环境变量中配置的API地址
|
||||
const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://yishi.com';
|
||||
|
||||
return {
|
||||
apiBaseUrl
|
||||
};
|
||||
}
|
||||
130
SuperAdmin/lib/menu-api.ts
Normal file
130
SuperAdmin/lib/menu-api.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import { apiRequest, ApiResponse } from './api-utils';
|
||||
|
||||
/**
|
||||
* 菜单项接口
|
||||
*/
|
||||
export interface MenuItem {
|
||||
id: number;
|
||||
title: string;
|
||||
path: string;
|
||||
icon?: string;
|
||||
parent_id: number;
|
||||
status: number;
|
||||
sort: number;
|
||||
children?: MenuItem[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取菜单树
|
||||
* @param onlyEnabled 是否只获取启用的菜单
|
||||
* @returns 菜单树
|
||||
*/
|
||||
export async function getMenus(onlyEnabled: boolean = true): Promise<MenuItem[]> {
|
||||
try {
|
||||
// 构建查询参数
|
||||
const params = new URLSearchParams();
|
||||
params.append('only_enabled', onlyEnabled ? '1' : '0');
|
||||
|
||||
// 禁用缓存,每次都获取最新的基于用户权限的菜单
|
||||
params.append('use_cache', '0');
|
||||
|
||||
const response = await apiRequest<MenuItem[]>(`/menu/tree?${params.toString()}`);
|
||||
|
||||
return response.data || [];
|
||||
} catch (error) {
|
||||
console.error('获取菜单树失败:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取菜单列表
|
||||
* @param page 页码
|
||||
* @param limit 每页数量
|
||||
* @returns 菜单列表
|
||||
*/
|
||||
export async function getMenuList(
|
||||
page: number = 1,
|
||||
limit: number = 20
|
||||
): Promise<ApiResponse<{
|
||||
list: MenuItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}>> {
|
||||
// 构建查询参数
|
||||
const params = new URLSearchParams();
|
||||
params.append('page', page.toString());
|
||||
params.append('limit', limit.toString());
|
||||
|
||||
return apiRequest(`/menu/list?${params.toString()}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存菜单(新增或更新)
|
||||
* @param menuData 菜单数据
|
||||
* @returns 保存结果
|
||||
*/
|
||||
export async function saveMenu(menuData: Partial<MenuItem>): Promise<boolean> {
|
||||
try {
|
||||
const response = await apiRequest('/menu/save', 'POST', menuData);
|
||||
|
||||
return response.code === 200;
|
||||
} catch (error) {
|
||||
console.error('保存菜单失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除菜单
|
||||
* @param id 菜单ID
|
||||
* @returns 删除结果
|
||||
*/
|
||||
export async function deleteMenu(id: number): Promise<boolean> {
|
||||
try {
|
||||
const response = await apiRequest(`/menu/delete/${id}`, 'DELETE');
|
||||
|
||||
return response.code === 200;
|
||||
} catch (error) {
|
||||
console.error('删除菜单失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新菜单状态
|
||||
* @param id 菜单ID
|
||||
* @param status 状态:1启用,0禁用
|
||||
* @returns 更新结果
|
||||
*/
|
||||
export async function updateMenuStatus(id: number, status: 0 | 1): Promise<boolean> {
|
||||
try {
|
||||
const response = await apiRequest('/menu/status', 'POST', {
|
||||
id,
|
||||
status
|
||||
});
|
||||
|
||||
return response.code === 200;
|
||||
} catch (error) {
|
||||
console.error('更新菜单状态失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一级菜单(用于权限设置)
|
||||
* @returns 一级菜单列表
|
||||
*/
|
||||
export async function getTopLevelMenus(): Promise<ApiResponse<MenuItem[]>> {
|
||||
try {
|
||||
return await apiRequest<MenuItem[]>('/menu/toplevel');
|
||||
} catch (error) {
|
||||
console.error('获取一级菜单失败:', error);
|
||||
return {
|
||||
code: 500,
|
||||
msg: '获取一级菜单失败',
|
||||
data: []
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -12,3 +12,64 @@ export function cn(...inputs: ClassValue[]) {
|
||||
export function md5(text: string): string {
|
||||
return crypto.createHash("md5").update(text).digest("hex")
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员信息
|
||||
*/
|
||||
export interface AdminInfo {
|
||||
id: number;
|
||||
name: string;
|
||||
account: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存管理员信息到本地存储
|
||||
* @param adminInfo 管理员信息
|
||||
*/
|
||||
export function saveAdminInfo(adminInfo: AdminInfo): void {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('admin_id', adminInfo.id.toString());
|
||||
localStorage.setItem('admin_name', adminInfo.name);
|
||||
localStorage.setItem('admin_account', adminInfo.account);
|
||||
localStorage.setItem('admin_token', adminInfo.token);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取管理员信息
|
||||
* @returns 管理员信息
|
||||
*/
|
||||
export function getAdminInfo(): AdminInfo | null {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const id = localStorage.getItem('admin_id');
|
||||
const name = localStorage.getItem('admin_name');
|
||||
const account = localStorage.getItem('admin_account');
|
||||
const token = localStorage.getItem('admin_token');
|
||||
|
||||
if (!id || !name || !account || !token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: parseInt(id, 10),
|
||||
name,
|
||||
account,
|
||||
token
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除管理员信息
|
||||
*/
|
||||
export function clearAdminInfo(): void {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.removeItem('admin_id');
|
||||
localStorage.removeItem('admin_name');
|
||||
localStorage.removeItem('admin_account');
|
||||
localStorage.removeItem('admin_token');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user