feat: 完成用户角色管理功能开发
本次提交实现了完整的用户角色管理体系: 1. 新增数据库表sys_user_role和sys_role_menu,完善权限关联结构 2. 新增角色状态字段,支持启用/禁用角色 3. 实现角色增删改查分页查询,新增角色列表接口 4. 实现用户分配角色、查询用户已分配角色的接口 5. 在前端用户管理页面添加角色分配功能,新增角色搜索筛选状态 6. 配置tauri命令自动收集,优化后端命令注册流程 7. 修复代码格式与依赖配置细节问题
This commit is contained in:
parent
faf181e67a
commit
27341c8a53
86
rust.sql
86
rust.sql
|
|
@ -1,9 +1,54 @@
|
||||||
-- Database export: rust
|
-- Database export: rust
|
||||||
-- Date: 2026-07-28 17:51:45
|
-- Date: 2026-07-30 14:07:55
|
||||||
-- Generated by DBX
|
-- Generated by DBX
|
||||||
|
|
||||||
SET FOREIGN_KEY_CHECKS = 0;
|
SET FOREIGN_KEY_CHECKS = 0;
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS `sys_user_role`;
|
||||||
|
|
||||||
|
CREATE TABLE `sys_user_role` (
|
||||||
|
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||||
|
`user_id` bigint(20) NOT NULL COMMENT '用户ID',
|
||||||
|
`role_id` bigint(20) NOT NULL COMMENT '角色ID',
|
||||||
|
`creater` bigint(20) NOT NULL DEFAULT '0' COMMENT '创建人ID',
|
||||||
|
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_user_role` (`user_id`,`role_id`),
|
||||||
|
KEY `idx_role_id` (`role_id`)
|
||||||
|
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COMMENT='用户角色关联表';
|
||||||
|
|
||||||
|
INSERT INTO `sys_user_role` (`id`, `user_id`, `role_id`, `creater`, `create_time`) VALUES
|
||||||
|
(1, 1, 4, 0, '2026-07-30 06:03:51'),
|
||||||
|
(2, 1, 5, 0, '2026-07-30 06:03:51'),
|
||||||
|
(4, 2, 6, 0, '2026-07-30 06:04:40');
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS `sys_menu`;
|
||||||
|
|
||||||
|
CREATE TABLE `sys_menu` (
|
||||||
|
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '菜单ID',
|
||||||
|
`parent_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '父菜单ID(0为顶级菜单)',
|
||||||
|
`name` varchar(50) NOT NULL COMMENT '菜单名称(唯一标识,用于权限控制)',
|
||||||
|
`title` varchar(50) NOT NULL COMMENT '菜单标题(界面显示名称)',
|
||||||
|
`path` varchar(200) DEFAULT '' COMMENT '路由路径(Vue Router 路径)',
|
||||||
|
`component` varchar(200) DEFAULT '' COMMENT '组件路径(前端组件位置)',
|
||||||
|
`icon` varchar(100) DEFAULT '' COMMENT '菜单图标(如 el-icon-setting)',
|
||||||
|
`perms` varchar(200) DEFAULT '' COMMENT '权限标识(如 sys:user:list)',
|
||||||
|
`menu_type` tinyint(4) NOT NULL DEFAULT '1' COMMENT '菜单类型(1=目录, 2=菜单, 3=按钮)',
|
||||||
|
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序权重(数值越小越靠前)',
|
||||||
|
`visible` bit(1) NOT NULL DEFAULT b'1' COMMENT '是否显示(0=隐藏, 1=显示)',
|
||||||
|
`status` bit(1) NOT NULL DEFAULT b'1' COMMENT '状态(0=禁用, 1=启用)',
|
||||||
|
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_parent_id` (`parent_id`),
|
||||||
|
KEY `idx_name` (`name`)
|
||||||
|
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COMMENT='系统菜单表';
|
||||||
|
|
||||||
|
INSERT INTO `sys_menu` (`id`, `parent_id`, `name`, `title`, `path`, `component`, `icon`, `perms`, `menu_type`, `sort`, `visible`, `status`, `create_time`, `update_time`) VALUES
|
||||||
|
(3, 0, 'Home', '首页', '/home', '/home', 'Home', '', 1, 10, b'1', b'1', '2026-07-29 03:54:25', '2026-07-29 03:54:25'),
|
||||||
|
(4, 0, 'System', '系统管理', '/system', '', 'Coin', '', 0, 20, b'1', b'1', '2026-07-29 03:55:43', '2026-07-29 03:55:43'),
|
||||||
|
(5, 4, 'SysUser', '用户管理', '/system/user', '/system/user', 'User', '', 1, 10, b'1', b'1', '2026-07-29 03:56:21', '2026-07-29 03:56:21');
|
||||||
|
|
||||||
DROP TABLE IF EXISTS `sys_user`;
|
DROP TABLE IF EXISTS `sys_user`;
|
||||||
|
|
||||||
CREATE TABLE `sys_user` (
|
CREATE TABLE `sys_user` (
|
||||||
|
|
@ -24,23 +69,38 @@ CREATE TABLE `sys_user` (
|
||||||
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COMMENT='系统用户表';
|
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COMMENT='系统用户表';
|
||||||
|
|
||||||
INSERT INTO `sys_user` (`id`, `nick_name`, `avatar`, `user_name`, `password`, `email`, `phone`, `age`, `sex`, `creater`, `create_time`) VALUES
|
INSERT INTO `sys_user` (`id`, `nick_name`, `avatar`, `user_name`, `password`, `email`, `phone`, `age`, `sex`, `creater`, `create_time`) VALUES
|
||||||
(1, '管理员', '', 'admin', '123456', 'wu434425608@163.com', '18866668888', 18, 1, 1, '2026-07-27 14:37:35'),
|
(1, '管理员', 'https://q6.itc.cn/q_70/images03/20250306/355fba6a5cb049f5b98c2ed9f03cc5e1.jpeg', 'admin', '123456', 'wu434425608@163.com', '18866668888', 18, 1, 1, '2026-07-27 14:37:35'),
|
||||||
(2, '用户', '', 'user', '123456', '122', '1', 0, 0, 0, '2026-07-27 07:20:45');
|
(2, '用户', 'https://q6.itc.cn/q_70/images03/20250306/355fba6a5cb049f5b98c2ed9f03cc5e1.jpeg', 'user', '123456', '122', '1', 0, 0, 0, '2026-07-27 07:20:45');
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS `sys_role_menu`;
|
||||||
|
|
||||||
|
CREATE TABLE `sys_role_menu` (
|
||||||
|
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||||
|
`role_id` bigint(20) NOT NULL COMMENT '角色ID',
|
||||||
|
`menu_id` bigint(20) NOT NULL COMMENT '菜单ID',
|
||||||
|
`creater` bigint(20) NOT NULL DEFAULT '0' COMMENT '创建人ID',
|
||||||
|
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_role_menu` (`role_id`,`menu_id`),
|
||||||
|
KEY `idx_menu_id` (`menu_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色菜单关联表';
|
||||||
|
|
||||||
DROP TABLE IF EXISTS `sys_role`;
|
DROP TABLE IF EXISTS `sys_role`;
|
||||||
|
|
||||||
CREATE TABLE `sys_role` (
|
CREATE TABLE `sys_role` (
|
||||||
`id` bigint(20) NOT NULL AUTO_INCREMENT,
|
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||||
`role_key` varchar(50) DEFAULT '',
|
`role_key` varchar(50) DEFAULT '' COMMENT '编码',
|
||||||
`role_name` varchar(50) DEFAULT '',
|
`role_name` varchar(50) DEFAULT '' COMMENT '名称',
|
||||||
`sort` int(11) DEFAULT '0',
|
`sort` int(11) DEFAULT '0' COMMENT '排序',
|
||||||
`creater` bigint(20) DEFAULT '0',
|
`status` bit(1) DEFAULT b'1' COMMENT '状态',
|
||||||
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
|
`creater` bigint(20) DEFAULT '0' COMMENT '创建人',
|
||||||
|
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='系统角色';
|
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COMMENT='系统角色';
|
||||||
|
|
||||||
INSERT INTO `sys_role` (`id`, `role_key`, `role_name`, `sort`, `creater`, `create_time`) VALUES
|
INSERT INTO `sys_role` (`id`, `role_key`, `role_name`, `sort`, `status`, `creater`, `create_time`) VALUES
|
||||||
(1, 'admin', '管理员', 10, 0, '2026-07-28 09:25:19'),
|
(4, 'admin', '管理员', 20, b'1', 0, '2026-07-29 03:53:32'),
|
||||||
(3, 'user', '用户', 30, 0, '2026-07-28 09:32:13');
|
(5, 'superadmin', '超级管理员', 10, b'1', 0, '2026-07-29 03:53:46'),
|
||||||
|
(6, 'inventory', '仓管员', 30, b'1', 0, '2026-07-30 06:04:34');
|
||||||
|
|
||||||
SET FOREIGN_KEY_CHECKS = 1;
|
SET FOREIGN_KEY_CHECKS = 1;
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,7 @@ sqlx = { version = "0.9.0", features = [
|
||||||
"chrono",
|
"chrono",
|
||||||
] }
|
] }
|
||||||
aws-sdk-s3 = "1.140.0"
|
aws-sdk-s3 = "1.140.0"
|
||||||
aws-config = {version = "1.10.1", features = ["behavior-version-latest"] }
|
aws-config = { version = "1.10.1", features = ["behavior-version-latest"] }
|
||||||
aws-credential-types = "1.3.0"
|
aws-credential-types = "1.3.0"
|
||||||
aws-types = "1.5.0"
|
aws-types = "1.5.0"
|
||||||
tauri-helper = "0.2.1"
|
tauri-helper = "0.2.1"
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
fn main() {
|
fn main() {
|
||||||
// tauri_build::build()
|
|
||||||
tauri_helper::generate_command_file(tauri_helper::TauriHelperOptions::default());
|
tauri_helper::generate_command_file(tauri_helper::TauriHelperOptions::default());
|
||||||
|
tauri_build::build()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
|
||||||
use sqlx::{FromRow, MySqlPool, QueryBuilder};
|
use sqlx::{FromRow, MySqlPool, QueryBuilder};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use tauri::State;
|
use tauri::State;
|
||||||
|
use tauri_helper::auto_collect_command;
|
||||||
|
|
||||||
#[derive(Debug, Serialize, FromRow)]
|
#[derive(Debug, Serialize, FromRow)]
|
||||||
struct SysMenu {
|
struct SysMenu {
|
||||||
|
|
@ -89,6 +90,7 @@ pub struct MenuSaveReq {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn menu_list(
|
pub async fn menu_list(
|
||||||
pool: State<'_, MySqlPool>,
|
pool: State<'_, MySqlPool>,
|
||||||
params: MenuQueryReq,
|
params: MenuQueryReq,
|
||||||
|
|
@ -160,6 +162,7 @@ fn build_children(parent_id: i64, menu_map: &HashMap<i64, Vec<MenuTree>>) -> Vec
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn menu_save(
|
pub async fn menu_save(
|
||||||
pool: State<'_, MySqlPool>,
|
pool: State<'_, MySqlPool>,
|
||||||
params: MenuSaveReq,
|
params: MenuSaveReq,
|
||||||
|
|
@ -184,6 +187,7 @@ pub async fn menu_save(
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn menu_update(
|
pub async fn menu_update(
|
||||||
pool: State<'_, MySqlPool>,
|
pool: State<'_, MySqlPool>,
|
||||||
params: MenuSaveReq,
|
params: MenuSaveReq,
|
||||||
|
|
@ -208,6 +212,7 @@ pub async fn menu_update(
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn menu_del(pool: State<'_, MySqlPool>, id: i64) -> Result<ApiResponse<()>, String> {
|
pub async fn menu_del(pool: State<'_, MySqlPool>, id: i64) -> Result<ApiResponse<()>, String> {
|
||||||
sqlx::query("DELETE FROM sys_menu WHERE id = ?")
|
sqlx::query("DELETE FROM sys_menu WHERE id = ?")
|
||||||
.bind(id)
|
.bind(id)
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sqlx::{MySqlPool, QueryBuilder};
|
use sqlx::{MySqlPool, QueryBuilder};
|
||||||
use tauri::State;
|
use tauri::State;
|
||||||
|
use tauri_helper::auto_collect_command;
|
||||||
|
|
||||||
use crate::models::{ApiResponse, PageResult};
|
use crate::models::{ApiResponse, PageResult};
|
||||||
|
|
||||||
|
|
@ -10,6 +11,7 @@ struct SysRole {
|
||||||
role_key: String,
|
role_key: String,
|
||||||
role_name: String,
|
role_name: String,
|
||||||
sort: i32,
|
sort: i32,
|
||||||
|
status: bool,
|
||||||
creater: i64,
|
creater: i64,
|
||||||
create_time: chrono::NaiveDateTime,
|
create_time: chrono::NaiveDateTime,
|
||||||
}
|
}
|
||||||
|
|
@ -20,6 +22,7 @@ pub struct RoleInfo {
|
||||||
pub role_key: String,
|
pub role_key: String,
|
||||||
pub role_name: String,
|
pub role_name: String,
|
||||||
pub sort: i32,
|
pub sort: i32,
|
||||||
|
pub status: bool,
|
||||||
pub create_time: chrono::NaiveDateTime,
|
pub create_time: chrono::NaiveDateTime,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -30,6 +33,7 @@ impl From<SysRole> for RoleInfo {
|
||||||
role_key: role.role_key,
|
role_key: role.role_key,
|
||||||
role_name: role.role_name,
|
role_name: role.role_name,
|
||||||
sort: role.sort,
|
sort: role.sort,
|
||||||
|
status: role.status,
|
||||||
create_time: role.create_time,
|
create_time: role.create_time,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -41,6 +45,7 @@ pub struct RolePageReq {
|
||||||
pub page_size: i32,
|
pub page_size: i32,
|
||||||
pub role_key: Option<String>,
|
pub role_key: Option<String>,
|
||||||
pub role_name: Option<String>,
|
pub role_name: Option<String>,
|
||||||
|
pub status: Option<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
|
@ -49,9 +54,11 @@ pub struct RoleSaveReq {
|
||||||
pub role_key: String,
|
pub role_key: String,
|
||||||
pub role_name: String,
|
pub role_name: String,
|
||||||
pub sort: i32,
|
pub sort: i32,
|
||||||
|
pub status: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn role_save(
|
pub async fn role_save(
|
||||||
pool: State<'_, MySqlPool>,
|
pool: State<'_, MySqlPool>,
|
||||||
params: RoleSaveReq,
|
params: RoleSaveReq,
|
||||||
|
|
@ -65,10 +72,11 @@ pub async fn role_save(
|
||||||
if exist > 0 {
|
if exist > 0 {
|
||||||
return Ok(ApiResponse::error(2001, "角色_key已存在"));
|
return Ok(ApiResponse::error(2001, "角色_key已存在"));
|
||||||
}
|
}
|
||||||
let result = sqlx::query("INSERT INTO sys_role (role_key, role_name, sort) VALUES (?, ?, ?)")
|
let result = sqlx::query("INSERT INTO sys_role (role_key, role_name, sort, status) VALUES (?, ?, ?, ?)")
|
||||||
.bind(¶ms.role_key)
|
.bind(¶ms.role_key)
|
||||||
.bind(¶ms.role_name)
|
.bind(¶ms.role_name)
|
||||||
.bind(¶ms.sort)
|
.bind(¶ms.sort)
|
||||||
|
.bind(¶ms.status)
|
||||||
.execute(&*pool)
|
.execute(&*pool)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
@ -77,6 +85,7 @@ pub async fn role_save(
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn role_page(
|
pub async fn role_page(
|
||||||
pool: State<'_, MySqlPool>,
|
pool: State<'_, MySqlPool>,
|
||||||
params: RolePageReq,
|
params: RolePageReq,
|
||||||
|
|
@ -94,8 +103,9 @@ pub async fn role_page(
|
||||||
.role_name
|
.role_name
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map_or(false, |role_name| !role_name.is_empty());
|
.map_or(false, |role_name| !role_name.is_empty());
|
||||||
|
let has_status = params.status.unwrap_or(false);
|
||||||
|
|
||||||
if has_role_key || has_role_name {
|
if has_role_key || has_role_name || has_status {
|
||||||
count_builder.push(" WHERE 1=1");
|
count_builder.push(" WHERE 1=1");
|
||||||
if has_role_key {
|
if has_role_key {
|
||||||
count_builder.push(" AND role_key LIKE ");
|
count_builder.push(" AND role_key LIKE ");
|
||||||
|
|
@ -105,6 +115,10 @@ pub async fn role_page(
|
||||||
count_builder.push(" AND role_name LIKE ");
|
count_builder.push(" AND role_name LIKE ");
|
||||||
count_builder.push_bind(format!("%{}%", params.role_name.as_deref().unwrap()));
|
count_builder.push_bind(format!("%{}%", params.role_name.as_deref().unwrap()));
|
||||||
}
|
}
|
||||||
|
if has_status {
|
||||||
|
count_builder.push(" AND status = ");
|
||||||
|
count_builder.push_bind(¶ms.status);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let total: i64 = count_builder
|
let total: i64 = count_builder
|
||||||
.build_query_scalar()
|
.build_query_scalar()
|
||||||
|
|
@ -113,7 +127,7 @@ pub async fn role_page(
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
let mut query_builder = QueryBuilder::new("SELECT * FROM sys_role");
|
let mut query_builder = QueryBuilder::new("SELECT * FROM sys_role");
|
||||||
if has_role_key || has_role_name {
|
if has_role_key || has_role_name || has_status {
|
||||||
query_builder.push(" WHERE 1=1");
|
query_builder.push(" WHERE 1=1");
|
||||||
if has_role_key {
|
if has_role_key {
|
||||||
query_builder.push(" AND role_key LIKE ");
|
query_builder.push(" AND role_key LIKE ");
|
||||||
|
|
@ -123,6 +137,10 @@ pub async fn role_page(
|
||||||
query_builder.push(" AND role_name LIKE ");
|
query_builder.push(" AND role_name LIKE ");
|
||||||
query_builder.push_bind(format!("%{}%", params.role_name.as_deref().unwrap()));
|
query_builder.push_bind(format!("%{}%", params.role_name.as_deref().unwrap()));
|
||||||
}
|
}
|
||||||
|
if has_status {
|
||||||
|
query_builder.push(" AND status = ");
|
||||||
|
query_builder.push_bind(params.status);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
query_builder.push(" ORDER BY sort ASC LIMIT ");
|
query_builder.push(" ORDER BY sort ASC LIMIT ");
|
||||||
query_builder.push_bind(page_size);
|
query_builder.push_bind(page_size);
|
||||||
|
|
@ -147,24 +165,27 @@ pub async fn role_page(
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn role_update(
|
pub async fn role_update(
|
||||||
pool: State<'_, MySqlPool>,
|
pool: State<'_, MySqlPool>,
|
||||||
params: RoleSaveReq,
|
params: RoleSaveReq,
|
||||||
) -> Result<ApiResponse<()>, String> {
|
) -> Result<ApiResponse<()>, String> {
|
||||||
let exist: i64 = sqlx::query_scalar("SELECT COUNT(id) FROM sys_role WHERE role_key = ? AND id != ?")
|
let exist: i64 =
|
||||||
.bind(¶ms.role_key)
|
sqlx::query_scalar("SELECT COUNT(id) FROM sys_role WHERE role_key = ? AND id != ?")
|
||||||
.bind(¶ms.id)
|
.bind(¶ms.role_key)
|
||||||
.fetch_one(&*pool)
|
.bind(¶ms.id)
|
||||||
.await
|
.fetch_one(&*pool)
|
||||||
.map_err(|e| e.to_string())?;
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
if exist > 0 {
|
if exist > 0 {
|
||||||
return Ok(ApiResponse::error(2001, "角色_key已存在"));
|
return Ok(ApiResponse::error(2001, "角色_key已存在"));
|
||||||
}
|
}
|
||||||
|
|
||||||
sqlx::query("UPDATE sys_role SET role_key = ?, role_name = ?, sort = ? WHERE id = ?")
|
sqlx::query("UPDATE sys_role SET role_key = ?, role_name = ?, sort = ?, status = ? WHERE id = ?")
|
||||||
.bind(¶ms.role_key)
|
.bind(¶ms.role_key)
|
||||||
.bind(¶ms.role_name)
|
.bind(¶ms.role_name)
|
||||||
.bind(¶ms.sort)
|
.bind(¶ms.sort)
|
||||||
|
.bind(¶ms.status)
|
||||||
.bind(¶ms.id)
|
.bind(¶ms.id)
|
||||||
.execute(&*pool)
|
.execute(&*pool)
|
||||||
.await
|
.await
|
||||||
|
|
@ -173,6 +194,7 @@ pub async fn role_update(
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn role_del(pool: State<'_, MySqlPool>, id: i64) -> Result<ApiResponse<()>, String> {
|
pub async fn role_del(pool: State<'_, MySqlPool>, id: i64) -> Result<ApiResponse<()>, String> {
|
||||||
sqlx::query("DELETE FROM sys_role WHERE id = ?")
|
sqlx::query("DELETE FROM sys_role WHERE id = ?")
|
||||||
.bind(id)
|
.bind(id)
|
||||||
|
|
@ -181,3 +203,14 @@ pub async fn role_del(pool: State<'_, MySqlPool>, id: i64) -> Result<ApiResponse
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
Ok(ApiResponse::success(()))
|
Ok(ApiResponse::success(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
|
pub async fn role_list(pool: State<'_, MySqlPool>) -> Result<ApiResponse<Vec<RoleInfo>>, String> {
|
||||||
|
let roles = sqlx::query_as::<_, SysRole>("SELECT * FROM sys_role WHERE status = 1")
|
||||||
|
.fetch_all(&*pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let role_list = roles.into_iter().map(|role| RoleInfo::from(role)).collect();
|
||||||
|
Ok(ApiResponse::success(role_list))
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sqlx::{MySqlPool, QueryBuilder};
|
use sqlx::{MySqlPool, QueryBuilder};
|
||||||
use tauri::State;
|
use tauri::State;
|
||||||
|
use tauri_helper::auto_collect_command;
|
||||||
|
|
||||||
use crate::models::{ApiResponse, PageResult};
|
use crate::models::{ApiResponse, PageResult};
|
||||||
|
|
||||||
|
|
@ -67,7 +68,14 @@ impl From<SysUser> for UserInfo {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct UserAssignRole {
|
||||||
|
pub user_id: i64,
|
||||||
|
pub role_id: i64,
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn login(
|
pub async fn login(
|
||||||
pool: State<'_, MySqlPool>,
|
pool: State<'_, MySqlPool>,
|
||||||
user_name: &str,
|
user_name: &str,
|
||||||
|
|
@ -92,6 +100,7 @@ pub async fn login(
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn get_user_page(
|
pub async fn get_user_page(
|
||||||
pool: State<'_, MySqlPool>,
|
pool: State<'_, MySqlPool>,
|
||||||
params: UserPageReq,
|
params: UserPageReq,
|
||||||
|
|
@ -165,6 +174,7 @@ pub async fn get_user_page(
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn register(
|
pub async fn register(
|
||||||
pool: State<'_, MySqlPool>,
|
pool: State<'_, MySqlPool>,
|
||||||
params: UserSaveReq,
|
params: UserSaveReq,
|
||||||
|
|
@ -196,6 +206,7 @@ pub async fn register(
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn del_user(pool: State<'_, MySqlPool>, id: i64) -> Result<ApiResponse<()>, String> {
|
pub async fn del_user(pool: State<'_, MySqlPool>, id: i64) -> Result<ApiResponse<()>, String> {
|
||||||
sqlx::query("DELETE FROM sys_user WHERE id = ?")
|
sqlx::query("DELETE FROM sys_user WHERE id = ?")
|
||||||
.bind(id)
|
.bind(id)
|
||||||
|
|
@ -206,6 +217,7 @@ pub async fn del_user(pool: State<'_, MySqlPool>, id: i64) -> Result<ApiResponse
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn update_user(
|
pub async fn update_user(
|
||||||
pool: State<'_, MySqlPool>,
|
pool: State<'_, MySqlPool>,
|
||||||
params: UserSaveReq,
|
params: UserSaveReq,
|
||||||
|
|
@ -235,6 +247,7 @@ pub async fn update_user(
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
pub async fn get_user_by_id(
|
pub async fn get_user_by_id(
|
||||||
pool: State<'_, MySqlPool>,
|
pool: State<'_, MySqlPool>,
|
||||||
id: i64,
|
id: i64,
|
||||||
|
|
@ -246,3 +259,42 @@ pub async fn get_user_by_id(
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
Ok(ApiResponse::success(UserInfo::from(user)))
|
Ok(ApiResponse::success(UserInfo::from(user)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
|
pub async fn assign_role(
|
||||||
|
pool: State<'_, MySqlPool>,
|
||||||
|
list: Vec<UserAssignRole>,
|
||||||
|
) -> Result<ApiResponse<()>, String> {
|
||||||
|
let user_id = match list.first() {
|
||||||
|
Some(first) => first.user_id,
|
||||||
|
None => return Ok(ApiResponse::<()>::success_empty()),
|
||||||
|
};
|
||||||
|
sqlx::query("DELETE FROM sys_user_role WHERE user_id = ?")
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(&*pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let mut query_builder = QueryBuilder::new("INSERT INTO sys_user_role (user_id, role_id)");
|
||||||
|
query_builder.push_values(&list, |mut b, item| {
|
||||||
|
b.push_bind(item.user_id).push_bind(item.role_id);
|
||||||
|
});
|
||||||
|
let _ = query_builder.build().execute(&*pool).await.map_err(|e| e.to_string())?;
|
||||||
|
Ok(ApiResponse::<()>::success_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
#[auto_collect_command]
|
||||||
|
pub async fn get_user_role_ids(
|
||||||
|
pool: State<'_, MySqlPool>,
|
||||||
|
user_id: i64,
|
||||||
|
) -> Result<ApiResponse<Vec<i64>>, String> {
|
||||||
|
let ids: Vec<i64> =
|
||||||
|
sqlx::query_scalar::<_, i64>("SELECT role_id FROM sys_user_role WHERE user_id = ?")
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_all(&*pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(ApiResponse::success(ids))
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,9 @@ pub mod commands;
|
||||||
pub mod models;
|
pub mod models;
|
||||||
pub mod services;
|
pub mod services;
|
||||||
|
|
||||||
|
use commands::menu::*;
|
||||||
|
use commands::role::*;
|
||||||
|
use commands::user::*;
|
||||||
use services::db::create_db_pool;
|
use services::db::create_db_pool;
|
||||||
use services::s3::{S3Client, S3Config};
|
use services::s3::{S3Client, S3Config};
|
||||||
use tauri::Manager;
|
use tauri::Manager;
|
||||||
|
|
|
||||||
|
|
@ -1,41 +1,48 @@
|
||||||
import { invoke } from "@tauri-apps/api/core"
|
import {invoke} from "@tauri-apps/api/core"
|
||||||
import { ApiResponse, PageResult } from "@/types"
|
import {ApiResponse, PageResult} from "@/types"
|
||||||
|
|
||||||
export interface RoleInfo {
|
interface RoleInfo {
|
||||||
id: number
|
id: number
|
||||||
role_key: string
|
role_key: string
|
||||||
role_name: string
|
role_name: string
|
||||||
sort: number
|
sort: number
|
||||||
create_time?: string
|
status: boolean
|
||||||
|
create_time?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RolePageReq {
|
interface RolePageReq {
|
||||||
page: number
|
page: number
|
||||||
page_size: number
|
page_size: number
|
||||||
role_key?: string
|
role_key?: string
|
||||||
role_name?: string
|
role_name?: string
|
||||||
|
status?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RoleSaveReq {
|
interface RoleSaveReq {
|
||||||
id?: number
|
id?: number
|
||||||
role_key: string
|
role_key: string
|
||||||
role_name: string
|
role_name: string
|
||||||
sort: number
|
sort: number
|
||||||
|
status: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const RoleApi = {
|
const RoleApi = {
|
||||||
rolePage: async (params: RolePageReq): Promise<ApiResponse<PageResult<RoleInfo>>> => {
|
rolePage: async (params: RolePageReq): Promise<ApiResponse<PageResult<RoleInfo>>> => {
|
||||||
return await invoke("role_page", { params })
|
return await invoke("role_page", {params})
|
||||||
},
|
},
|
||||||
roleSave: async (params: RoleSaveReq): Promise<ApiResponse<number>> => {
|
roleSave: async (params: RoleSaveReq): Promise<ApiResponse<number>> => {
|
||||||
return await invoke("role_save", { params })
|
return await invoke("role_save", {params})
|
||||||
},
|
},
|
||||||
roleUpdate: async (params: RoleSaveReq): Promise<ApiResponse<any>> => {
|
roleUpdate: async (params: RoleSaveReq): Promise<ApiResponse<any>> => {
|
||||||
return await invoke("role_update", { params })
|
return await invoke("role_update", {params})
|
||||||
},
|
},
|
||||||
roleDel: async (id: number): Promise<ApiResponse<any>> => {
|
roleDel: async (id: number): Promise<ApiResponse<any>> => {
|
||||||
return await invoke("role_del", { id })
|
return await invoke("role_del", {id})
|
||||||
},
|
},
|
||||||
|
roleList: async (): Promise<ApiResponse<RoleInfo[]>> => {
|
||||||
|
return await invoke("role_list")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default RoleApi
|
export default RoleApi
|
||||||
|
export type {RoleInfo, RoleSaveReq, RolePageReq}
|
||||||
|
|
@ -1,63 +1,77 @@
|
||||||
import { invoke } from "@tauri-apps/api/core"
|
import {invoke} from "@tauri-apps/api/core"
|
||||||
import { ApiResponse, PageResult } from "@/types"
|
import {ApiResponse, PageResult} from "@/types"
|
||||||
|
|
||||||
export interface UserInfo {
|
interface UserInfo {
|
||||||
id: number
|
id: number
|
||||||
nick_name: string
|
nick_name: string
|
||||||
avatar: string
|
avatar: string
|
||||||
user_name: string
|
user_name: string
|
||||||
email: string
|
email: string
|
||||||
phone: string
|
phone: string
|
||||||
age: number
|
age: number
|
||||||
sex: number
|
sex: number
|
||||||
create_time?: string
|
create_time?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserPageReq {
|
interface UserPageReq {
|
||||||
page: number
|
page: number
|
||||||
page_size: number
|
page_size: number
|
||||||
nick_name?: string
|
nick_name?: string
|
||||||
user_name?: string
|
user_name?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserSaveReq {
|
interface UserSaveReq {
|
||||||
id?: number
|
id?: number
|
||||||
nick_name: string
|
nick_name: string
|
||||||
avatar: string
|
avatar: string
|
||||||
user_name: string
|
user_name: string
|
||||||
password: string
|
password: string
|
||||||
email: string
|
email: string
|
||||||
phone: string
|
phone: string
|
||||||
age: number
|
age: number
|
||||||
sex: number
|
sex: number
|
||||||
creater: number
|
creater: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AssignRoleReq {
|
||||||
|
user_id: number
|
||||||
|
role_id: number
|
||||||
}
|
}
|
||||||
|
|
||||||
const UserApi = {
|
const UserApi = {
|
||||||
// 登录
|
// 登录
|
||||||
login: async (userName: string, password: string): Promise<ApiResponse<UserInfo>> => {
|
login: async (userName: string, password: string): Promise<ApiResponse<UserInfo>> => {
|
||||||
return await invoke("login", { userName, password })
|
return await invoke("login", {userName, password})
|
||||||
},
|
},
|
||||||
// 获取用户分页列表
|
// 获取用户分页列表
|
||||||
getUserPage: async (params: UserPageReq): Promise<ApiResponse<PageResult<UserInfo>>> => {
|
getUserPage: async (params: UserPageReq): Promise<ApiResponse<PageResult<UserInfo>>> => {
|
||||||
return await invoke("get_user_page", { params })
|
return await invoke("get_user_page", {params})
|
||||||
},
|
},
|
||||||
// 注册
|
// 注册
|
||||||
register: async (params: UserSaveReq): Promise<ApiResponse<UserInfo>> => {
|
register: async (params: UserSaveReq): Promise<ApiResponse<UserInfo>> => {
|
||||||
return await invoke("register", { params })
|
return await invoke("register", {params})
|
||||||
},
|
},
|
||||||
// 删除用户
|
// 删除用户
|
||||||
delUser: async (id: number): Promise<ApiResponse<any>> => {
|
delUser: async (id: number): Promise<ApiResponse<any>> => {
|
||||||
return await invoke("del_user", { id })
|
return await invoke("del_user", {id})
|
||||||
},
|
},
|
||||||
// 更新用户
|
// 更新用户
|
||||||
update_user: async (params: UserSaveReq): Promise<ApiResponse<any>> => {
|
update_user: async (params: UserSaveReq): Promise<ApiResponse<any>> => {
|
||||||
return await invoke("update_user", { params })
|
return await invoke("update_user", {params})
|
||||||
},
|
},
|
||||||
// 根据ID获取用户信息
|
// 根据ID获取用户信息
|
||||||
getUserById: async (id: number): Promise<ApiResponse<UserInfo>> => {
|
getUserById: async (id: number): Promise<ApiResponse<UserInfo>> => {
|
||||||
return await invoke("get_user_by_id", { id })
|
return await invoke("get_user_by_id", {id})
|
||||||
},
|
},
|
||||||
|
// 给用户分配角色
|
||||||
|
assignRole: async (list: AssignRoleReq[]): Promise<ApiResponse<any>> => {
|
||||||
|
return await invoke("assign_role", {list})
|
||||||
|
},
|
||||||
|
// 获取用户角色id
|
||||||
|
getUserRole: async (userId: number): Promise<ApiResponse<number[]>> => {
|
||||||
|
return await invoke("get_user_role_ids", {userId})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default UserApi
|
export default UserApi
|
||||||
|
export type {UserInfo, UserSaveReq, UserPageReq, AssignRoleReq}
|
||||||
|
|
@ -12,6 +12,7 @@
|
||||||
<n-space align="center" :wrap="true" :size="12">
|
<n-space align="center" :wrap="true" :size="12">
|
||||||
<n-input v-model:value="searchForm.role_key" placeholder="角色标识" clearable :style="{ width: '180px' }" @keyup.enter="handleSearch" />
|
<n-input v-model:value="searchForm.role_key" placeholder="角色标识" clearable :style="{ width: '180px' }" @keyup.enter="handleSearch" />
|
||||||
<n-input v-model:value="searchForm.role_name" placeholder="角色名称" clearable :style="{ width: '180px' }" @keyup.enter="handleSearch" />
|
<n-input v-model:value="searchForm.role_name" placeholder="角色名称" clearable :style="{ width: '180px' }" @keyup.enter="handleSearch" />
|
||||||
|
<n-select v-model:value="searchForm.status" :options="statusSearchOptions" placeholder="状态" clearable :style="{ width: '100px' }" />
|
||||||
<n-button type="primary" size="small" @click="handleSearch">
|
<n-button type="primary" size="small" @click="handleSearch">
|
||||||
<template #icon><n-icon :component="SearchOutline" /></template>查询
|
<template #icon><n-icon :component="SearchOutline" /></template>查询
|
||||||
</n-button>
|
</n-button>
|
||||||
|
|
@ -48,6 +49,12 @@
|
||||||
<n-form-item label="排序" path="sort">
|
<n-form-item label="排序" path="sort">
|
||||||
<n-input-number v-model:value="formData.sort" :min="0" :max="999" :style="{ width: '100%' }" />
|
<n-input-number v-model:value="formData.sort" :min="0" :max="999" :style="{ width: '100%' }" />
|
||||||
</n-form-item>
|
</n-form-item>
|
||||||
|
<n-form-item label="状态" path="status">
|
||||||
|
<n-switch v-model:value="formData.status" :checked-value="true" :unchecked-value="false">
|
||||||
|
<template #checked>启用</template>
|
||||||
|
<template #unchecked>禁用</template>
|
||||||
|
</n-switch>
|
||||||
|
</n-form-item>
|
||||||
</n-form>
|
</n-form>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<n-space justify="end">
|
<n-space justify="end">
|
||||||
|
|
@ -70,7 +77,12 @@ const message = useMessage()
|
||||||
const dialog = useDialog()
|
const dialog = useDialog()
|
||||||
|
|
||||||
// ─── 搜索 ───
|
// ─── 搜索 ───
|
||||||
const searchForm = reactive({ role_key: '', role_name: '' })
|
const searchForm = reactive<{ role_key: string; role_name: string; status?: boolean }>({ role_key: '', role_name: '', status: undefined })
|
||||||
|
|
||||||
|
const statusSearchOptions = [
|
||||||
|
{ label: '启用', value: true },
|
||||||
|
{ label: '禁用', value: false },
|
||||||
|
]
|
||||||
|
|
||||||
// ─── 分页 ───
|
// ─── 分页 ───
|
||||||
const pagination = reactive({ page: 1, page_size: 10 })
|
const pagination = reactive({ page: 1, page_size: 10 })
|
||||||
|
|
@ -86,6 +98,10 @@ const columns: DataTableColumns<RoleInfo> = [
|
||||||
{ title: '角色标识', key: 'role_key', width: 140, ellipsis: { tooltip: true } },
|
{ title: '角色标识', key: 'role_key', width: 140, ellipsis: { tooltip: true } },
|
||||||
{ title: '角色名称', key: 'role_name', width: 160, ellipsis: { tooltip: true } },
|
{ title: '角色名称', key: 'role_name', width: 160, ellipsis: { tooltip: true } },
|
||||||
{ title: '排序', key: 'sort', width: 70, align: 'center' },
|
{ title: '排序', key: 'sort', width: 70, align: 'center' },
|
||||||
|
{
|
||||||
|
title: '状态', key: 'status', width: 80, align: 'center',
|
||||||
|
render(row) { return row.status ? h('n-tag', { type: 'success', size: 'small' }, { default: () => '启用' }) : h('n-tag', { type: 'default', size: 'small' }, { default: () => '禁用' }) },
|
||||||
|
},
|
||||||
{ title: '创建时间', key: 'create_time', width: 170, render(row) { return row.create_time ?? '-' } },
|
{ title: '创建时间', key: 'create_time', width: 170, render(row) { return row.create_time ?? '-' } },
|
||||||
{
|
{
|
||||||
title: '操作', key: 'actions', width: 150, align: 'center',
|
title: '操作', key: 'actions', width: 150, align: 'center',
|
||||||
|
|
@ -113,6 +129,7 @@ async function fetchData() {
|
||||||
page_size: pagination.page_size,
|
page_size: pagination.page_size,
|
||||||
role_key: searchForm.role_key || undefined,
|
role_key: searchForm.role_key || undefined,
|
||||||
role_name: searchForm.role_name || undefined,
|
role_name: searchForm.role_name || undefined,
|
||||||
|
status: searchForm.status,
|
||||||
})
|
})
|
||||||
if (res.success && res.data) {
|
if (res.success && res.data) {
|
||||||
tableData.value = res.data.list ?? []
|
tableData.value = res.data.list ?? []
|
||||||
|
|
@ -128,7 +145,7 @@ async function fetchData() {
|
||||||
fetchData()
|
fetchData()
|
||||||
|
|
||||||
function handleSearch() { pagination.page = 1; fetchData() }
|
function handleSearch() { pagination.page = 1; fetchData() }
|
||||||
function handleReset() { searchForm.role_key = ''; searchForm.role_name = ''; pagination.page = 1; fetchData() }
|
function handleReset() { searchForm.role_key = ''; searchForm.role_name = ''; searchForm.status = undefined; pagination.page = 1; fetchData() }
|
||||||
function handlePageChange(page: number) { pagination.page = page; fetchData() }
|
function handlePageChange(page: number) { pagination.page = page; fetchData() }
|
||||||
function handlePageSizeChange(size: number) { pagination.page_size = size; pagination.page = 1; fetchData() }
|
function handlePageSizeChange(size: number) { pagination.page_size = size; pagination.page = 1; fetchData() }
|
||||||
|
|
||||||
|
|
@ -140,7 +157,7 @@ const isEdit = ref(false)
|
||||||
const editingId = ref<number>(0)
|
const editingId = ref<number>(0)
|
||||||
|
|
||||||
const formData = reactive<RoleSaveReq>({
|
const formData = reactive<RoleSaveReq>({
|
||||||
id: 0, role_key: '', role_name: '', sort: 0,
|
id: 0, role_key: '', role_name: '', sort: 0, status: true,
|
||||||
})
|
})
|
||||||
|
|
||||||
const formRules: FormRules = {
|
const formRules: FormRules = {
|
||||||
|
|
@ -154,14 +171,14 @@ const modalTitle = computed(() => isEdit.value ? '编辑角色' : '新增角色'
|
||||||
function openEdit(row: RoleInfo) {
|
function openEdit(row: RoleInfo) {
|
||||||
isEdit.value = true
|
isEdit.value = true
|
||||||
editingId.value = row.id
|
editingId.value = row.id
|
||||||
Object.assign(formData, { id: row.id, role_key: row.role_key, role_name: row.role_name, sort: row.sort })
|
Object.assign(formData, { id: row.id, role_key: row.role_key, role_name: row.role_name, sort: row.sort, status: row.status })
|
||||||
showAddModal.value = true
|
showAddModal.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetForm() {
|
function resetForm() {
|
||||||
isEdit.value = false
|
isEdit.value = false
|
||||||
editingId.value = 0
|
editingId.value = 0
|
||||||
Object.assign(formData, { id: 0, role_key: '', role_name: '', sort: 0 })
|
Object.assign(formData, { id: 0, role_key: '', role_name: '', sort: 0, status: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleSubmit() {
|
async function handleSubmit() {
|
||||||
|
|
|
||||||
|
|
@ -131,6 +131,27 @@
|
||||||
</n-space>
|
</n-space>
|
||||||
</template>
|
</template>
|
||||||
</n-modal>
|
</n-modal>
|
||||||
|
|
||||||
|
<!-- 分配角色弹窗 -->
|
||||||
|
<n-modal v-model:show="showRoleModal" preset="card" :title="'分配角色 - ' + selectedRoleUser.user_name" :style="{ width: '460px' }" :mask-closable="false">
|
||||||
|
<div v-if="allRoles.length > 0" style="max-height: 360px; overflow-y: auto; padding: 4px 0;">
|
||||||
|
<n-checkbox-group v-model:value="checkedRoleIds">
|
||||||
|
<n-space vertical :size="4">
|
||||||
|
<n-checkbox v-for="role in allRoles" :key="role.id" :value="role.id">
|
||||||
|
<span style="font-weight: 500;">{{ role.role_name }}</span>
|
||||||
|
<span style="color: #86909C; font-size: 12px; margin-left: 8px;">{{ role.role_key }}</span>
|
||||||
|
</n-checkbox>
|
||||||
|
</n-space>
|
||||||
|
</n-checkbox-group>
|
||||||
|
</div>
|
||||||
|
<n-empty v-else description="暂无可用角色" style="padding: 24px 0;" />
|
||||||
|
<template #footer>
|
||||||
|
<n-space justify="end">
|
||||||
|
<n-button @click="showRoleModal = false">取消</n-button>
|
||||||
|
<n-button type="primary" :loading="roleSubmitting" @click="handleRoleSubmit">确定</n-button>
|
||||||
|
</n-space>
|
||||||
|
</template>
|
||||||
|
</n-modal>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|
@ -138,8 +159,9 @@
|
||||||
import { ref, reactive, h } from 'vue'
|
import { ref, reactive, h } from 'vue'
|
||||||
import { NButton, NIcon, useMessage, useDialog } from 'naive-ui'
|
import { NButton, NIcon, useMessage, useDialog } from 'naive-ui'
|
||||||
import type { DataTableColumns, FormInst, FormRules } from 'naive-ui'
|
import type { DataTableColumns, FormInst, FormRules } from 'naive-ui'
|
||||||
import { SearchOutline, PersonAddOutline, CreateOutline, TrashOutline } from '@vicons/ionicons5'
|
import { SearchOutline, PersonAddOutline, CreateOutline, TrashOutline, ShieldCheckmarkOutline } from '@vicons/ionicons5'
|
||||||
import UserApi, { type UserInfo, type UserSaveReq } from '@/api/system/user'
|
import UserApi, { type UserInfo, type UserSaveReq } from '@/api/system/user'
|
||||||
|
import RoleApi, { type RoleInfo } from '@/api/system/role'
|
||||||
|
|
||||||
const message = useMessage()
|
const message = useMessage()
|
||||||
const dialog = useDialog()
|
const dialog = useDialog()
|
||||||
|
|
@ -173,10 +195,14 @@ const columns: DataTableColumns<UserInfo> = [
|
||||||
title: '创建时间', key: 'create_time', width: 170,
|
title: '创建时间', key: 'create_time', width: 170,
|
||||||
render(row) { return row.create_time ?? '-' },
|
render(row) { return row.create_time ?? '-' },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '操作', key: 'actions', width: 150, align: 'center',
|
title: '操作', key: 'actions', width: 220, align: 'center',
|
||||||
render(row) {
|
render(row) {
|
||||||
return h('div', { style: { display: 'flex', gap: '8px', justifyContent: 'center' } }, [
|
return h('div', { style: { display: 'flex', gap: '8px', justifyContent: 'center' } }, [
|
||||||
|
h(NButton, {
|
||||||
|
text: true, size: 'tiny', type: 'info',
|
||||||
|
onClick: (e: Event) => { e.stopPropagation(); openRoleModal(row) },
|
||||||
|
}, { icon: () => h(NIcon, null, { default: () => h(ShieldCheckmarkOutline) }), default: () => '角色' }),
|
||||||
h(NButton, {
|
h(NButton, {
|
||||||
text: true, size: 'tiny', type: 'primary',
|
text: true, size: 'tiny', type: 'primary',
|
||||||
onClick: (e: Event) => { e.stopPropagation(); openEditModal(row) },
|
onClick: (e: Event) => { e.stopPropagation(); openEditModal(row) },
|
||||||
|
|
@ -324,6 +350,54 @@ function handleDelete(row: UserInfo) {
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── 分配角色 ───
|
||||||
|
const showRoleModal = ref(false)
|
||||||
|
const roleSubmitting = ref(false)
|
||||||
|
const allRoles = ref<RoleInfo[]>([])
|
||||||
|
const checkedRoleIds = ref<number[]>([])
|
||||||
|
const selectedRoleUser = ref<UserInfo>({ id: 0, nick_name: '', user_name: '', email: '', phone: '', avatar: '', age: 0, sex: 0 })
|
||||||
|
|
||||||
|
async function openRoleModal(row: UserInfo) {
|
||||||
|
selectedRoleUser.value = row
|
||||||
|
try {
|
||||||
|
const [rolesRes, roleIdsRes] = await Promise.all([
|
||||||
|
RoleApi.roleList(),
|
||||||
|
UserApi.getUserRole(row.id),
|
||||||
|
])
|
||||||
|
if (rolesRes.success && rolesRes.data) {
|
||||||
|
allRoles.value = rolesRes.data
|
||||||
|
}
|
||||||
|
if (roleIdsRes.success && roleIdsRes.data) {
|
||||||
|
checkedRoleIds.value = roleIdsRes.data
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.toString() ?? '加载角色信息失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
showRoleModal.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRoleSubmit() {
|
||||||
|
roleSubmitting.value = true
|
||||||
|
try {
|
||||||
|
const list = checkedRoleIds.value.map(role_id => ({
|
||||||
|
user_id: selectedRoleUser.value.id,
|
||||||
|
role_id,
|
||||||
|
}))
|
||||||
|
const res = await UserApi.assignRole(list)
|
||||||
|
if (res.success) {
|
||||||
|
message.success('分配角色成功')
|
||||||
|
showRoleModal.value = false
|
||||||
|
} else {
|
||||||
|
message.error(res.message)
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.toString() ?? '分配角色失败')
|
||||||
|
} finally {
|
||||||
|
roleSubmitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue