修改登录,添加超级管理员权限
This commit is contained in:
@ -2,19 +2,27 @@
|
|||||||
from app.extensions import db
|
from app.extensions import db
|
||||||
from werkzeug.security import generate_password_hash, check_password_hash
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
|
||||||
|
|
||||||
class SysUser(db.Model):
|
class SysUser(db.Model):
|
||||||
|
"""
|
||||||
|
系统用户表
|
||||||
|
对应数据库: sys_user
|
||||||
|
"""
|
||||||
__tablename__ = 'sys_user'
|
__tablename__ = 'sys_user'
|
||||||
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
username = db.Column(db.String(100), nullable=False)
|
username = db.Column(db.String(100), nullable=False)
|
||||||
# 注意:如果允许邮箱为空,建议去掉 unique=True 或者在数据库层面处理空字符串
|
|
||||||
email = db.Column(db.String(100), unique=True)
|
email = db.Column(db.String(100), unique=True)
|
||||||
department = db.Column(db.String(100))
|
department = db.Column(db.String(100))
|
||||||
role = db.Column(db.String(50))
|
role = db.Column(db.String(50)) # 存储 UserRole 的值,如 'SUPER_ADMIN'
|
||||||
status = db.Column(db.String(20), default='active')
|
status = db.Column(db.String(20), default='active')
|
||||||
password_hash = db.Column(db.Text)
|
password_hash = db.Column(db.Text)
|
||||||
created_at = db.Column(db.DateTime, default=datetime.now) # 新增创建时间
|
|
||||||
|
# [关键] 对应数据库的 created_at 字段
|
||||||
|
# 如果数据库报错 column not found,请务必执行 SQL: ALTER TABLE sys_user ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
|
||||||
|
created_at = db.Column(db.DateTime, server_default=func.now(), default=datetime.now)
|
||||||
|
|
||||||
def set_password(self, password):
|
def set_password(self, password):
|
||||||
"""生成加密密码"""
|
"""生成加密密码"""
|
||||||
@ -36,6 +44,7 @@ class SysUser(db.Model):
|
|||||||
'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else ''
|
'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class SysLog(db.Model):
|
class SysLog(db.Model):
|
||||||
"""
|
"""
|
||||||
系统操作日志表
|
系统操作日志表
|
||||||
|
|||||||
@ -3,10 +3,11 @@ from app.models.system import SysUser
|
|||||||
from app.extensions import db
|
from app.extensions import db
|
||||||
from flask_jwt_extended import create_access_token
|
from flask_jwt_extended import create_access_token
|
||||||
from app.utils.constants import UserRole
|
from app.utils.constants import UserRole
|
||||||
from datetime import timedelta # [修改点1] 引入 timedelta 用于设置过期时间
|
from datetime import timedelta
|
||||||
|
|
||||||
|
|
||||||
class AuthService:
|
class AuthService:
|
||||||
# 硬编码的超级管理员凭证
|
# 硬编码的“初始”超级管理员凭证 (用于系统初始化或数据库被锁死时)
|
||||||
SUPER_ADMIN_USER = "IRIS"
|
SUPER_ADMIN_USER = "IRIS"
|
||||||
SUPER_ADMIN_PASS = "licahk"
|
SUPER_ADMIN_PASS = "licahk"
|
||||||
|
|
||||||
@ -19,20 +20,22 @@ class AuthService:
|
|||||||
user_id = None
|
user_id = None
|
||||||
user_info = {}
|
user_info = {}
|
||||||
|
|
||||||
# 1. 优先检查硬编码的超级管理员
|
# 1. 优先检查硬编码的超级管理员 (IRIS)
|
||||||
if username == AuthService.SUPER_ADMIN_USER:
|
if username == AuthService.SUPER_ADMIN_USER:
|
||||||
if password == AuthService.SUPER_ADMIN_PASS:
|
if password == AuthService.SUPER_ADMIN_PASS:
|
||||||
|
# 显式指定角色为 SUPER_ADMIN
|
||||||
user_role = UserRole.SUPER_ADMIN
|
user_role = UserRole.SUPER_ADMIN
|
||||||
user_id = 0 # 虚拟ID
|
user_id = 0 # 虚拟ID,区分于数据库ID
|
||||||
user_info = {
|
user_info = {
|
||||||
'username': username,
|
'username': username,
|
||||||
'role': user_role,
|
'role': user_role,
|
||||||
'department': 'System'
|
'department': 'System',
|
||||||
|
'status': 'active'
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
raise ValueError("密码错误")
|
raise ValueError("密码错误")
|
||||||
|
|
||||||
# 2. 如果不是 IRIS,检查数据库用户
|
# 2. 如果不是硬编码用户,检查数据库用户
|
||||||
else:
|
else:
|
||||||
user = SysUser.query.filter_by(username=username).first()
|
user = SysUser.query.filter_by(username=username).first()
|
||||||
|
|
||||||
@ -49,8 +52,7 @@ class AuthService:
|
|||||||
user_id = user.id
|
user_id = user.id
|
||||||
user_info = user.to_dict()
|
user_info = user.to_dict()
|
||||||
|
|
||||||
# 3. 生成 Token
|
# 3. 生成 Token (设置为7天过期)
|
||||||
# [修改点2] 增加 expires_delta 参数,设置为 7 天(可根据需要修改为 days=1 或 days=30)
|
|
||||||
access_token = create_access_token(
|
access_token = create_access_token(
|
||||||
identity=user_id,
|
identity=user_id,
|
||||||
additional_claims={'role': user_role, 'username': username},
|
additional_claims={'role': user_role, 'username': username},
|
||||||
@ -65,18 +67,31 @@ class AuthService:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def create_user(data, operator_role):
|
def create_user(data, operator_role):
|
||||||
"""
|
"""
|
||||||
创建新用户 (仅限管理员使用)
|
创建新用户
|
||||||
|
权限控制:只有超级管理员(SUPER_ADMIN) 或 主管(SUPERVISOR) 可以创建
|
||||||
"""
|
"""
|
||||||
if operator_role not in [UserRole.SUPER_ADMIN, UserRole.SUPERVISOR]:
|
if operator_role not in [UserRole.SUPER_ADMIN, UserRole.SUPERVISOR]:
|
||||||
raise Exception("权限不足:只有超级管理员或主管可以创建新用户")
|
raise Exception("权限不足:只有超级管理员或主管可以创建新用户")
|
||||||
|
|
||||||
|
# 检查用户名是否重复
|
||||||
if SysUser.query.filter_by(username=data.get('username')).first():
|
if SysUser.query.filter_by(username=data.get('username')).first():
|
||||||
raise Exception("用户名已存在")
|
raise Exception("用户名已存在")
|
||||||
|
|
||||||
role = data.get('role')
|
role = data.get('role')
|
||||||
valid_roles = [v for k, v in UserRole.__dict__.items() if not k.startswith('__')]
|
|
||||||
|
# 验证角色合法性
|
||||||
|
# [核心修复] 过滤掉 __开头的属性 和 ROLE_MAP 字典,只保留字符串类型的角色定义
|
||||||
|
valid_roles = [
|
||||||
|
v for k, v in UserRole.__dict__.items()
|
||||||
|
if not k.startswith('__') and isinstance(v, str)
|
||||||
|
]
|
||||||
|
|
||||||
if role not in valid_roles:
|
if role not in valid_roles:
|
||||||
raise Exception(f"角色无效,可选角色: {valid_roles}")
|
raise Exception(f"角色无效")
|
||||||
|
|
||||||
|
# 如果操作者只是 SUPERVISOR (主管),不允许他创建 SUPER_ADMIN (超管)
|
||||||
|
if operator_role == UserRole.SUPERVISOR and role == UserRole.SUPER_ADMIN:
|
||||||
|
raise Exception("权限不足:主管无法创建超级管理员")
|
||||||
|
|
||||||
email = data.get('email', '')
|
email = data.get('email', '')
|
||||||
if email and SysUser.query.filter_by(email=email).first():
|
if email and SysUser.query.filter_by(email=email).first():
|
||||||
@ -99,8 +114,9 @@ class AuthService:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def update_user(user_id, data, operator_role):
|
def update_user(user_id, data, operator_role):
|
||||||
"""
|
"""
|
||||||
[新增] 更新用户信息
|
更新用户信息
|
||||||
"""
|
"""
|
||||||
|
# 权限校验
|
||||||
if operator_role not in [UserRole.SUPER_ADMIN, UserRole.SUPERVISOR]:
|
if operator_role not in [UserRole.SUPER_ADMIN, UserRole.SUPERVISOR]:
|
||||||
raise Exception("权限不足:只有超级管理员或主管可以修改用户信息")
|
raise Exception("权限不足:只有超级管理员或主管可以修改用户信息")
|
||||||
|
|
||||||
@ -108,18 +124,30 @@ class AuthService:
|
|||||||
if not user:
|
if not user:
|
||||||
raise Exception("用户不存在")
|
raise Exception("用户不存在")
|
||||||
|
|
||||||
# 1. 更新基本信息
|
# 1. 更新角色 (Role)
|
||||||
if 'role' in data:
|
if 'role' in data:
|
||||||
valid_roles = [v for k, v in UserRole.__dict__.items() if not k.startswith('__')]
|
# [核心修复] 同样添加类型检查
|
||||||
if data['role'] not in valid_roles:
|
valid_roles = [
|
||||||
raise Exception(f"角色无效")
|
v for k, v in UserRole.__dict__.items()
|
||||||
user.role = data['role']
|
if not k.startswith('__') and isinstance(v, str)
|
||||||
|
]
|
||||||
|
new_role = data['role']
|
||||||
|
|
||||||
|
if new_role not in valid_roles:
|
||||||
|
raise Exception(f"角色无效")
|
||||||
|
|
||||||
|
# 防止主管把自己或其他用户提升为超管
|
||||||
|
if operator_role == UserRole.SUPERVISOR and new_role == UserRole.SUPER_ADMIN:
|
||||||
|
raise Exception("权限不足:主管无法分配超级管理员权限")
|
||||||
|
|
||||||
|
user.role = new_role
|
||||||
|
|
||||||
|
# 2. 更新部门
|
||||||
if 'department' in data:
|
if 'department' in data:
|
||||||
user.department = data['department']
|
user.department = data['department']
|
||||||
|
|
||||||
|
# 3. 更新邮箱
|
||||||
if 'email' in data:
|
if 'email' in data:
|
||||||
# 如果修改了邮箱,且新邮箱已被其他人使用
|
|
||||||
email = data['email']
|
email = data['email']
|
||||||
if email and email != user.email:
|
if email and email != user.email:
|
||||||
existing = SysUser.query.filter_by(email=email).first()
|
existing = SysUser.query.filter_by(email=email).first()
|
||||||
@ -127,7 +155,11 @@ class AuthService:
|
|||||||
raise Exception("该邮箱已被其他用户使用")
|
raise Exception("该邮箱已被其他用户使用")
|
||||||
user.email = email
|
user.email = email
|
||||||
|
|
||||||
# 2. 如果提供了密码,则重置密码;否则保持原密码
|
# 4. 更新状态 (Status) - 例如禁用用户
|
||||||
|
if 'status' in data:
|
||||||
|
user.status = data['status']
|
||||||
|
|
||||||
|
# 5. 更新密码
|
||||||
new_password = data.get('password')
|
new_password = data.get('password')
|
||||||
if new_password and str(new_password).strip():
|
if new_password and str(new_password).strip():
|
||||||
if len(new_password) < 6:
|
if len(new_password) < 6:
|
||||||
@ -140,14 +172,16 @@ class AuthService:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def get_all_users():
|
def get_all_users():
|
||||||
"""获取所有系统用户"""
|
"""获取所有系统用户"""
|
||||||
|
# 按照 ID 倒序排列
|
||||||
users = SysUser.query.order_by(SysUser.id.desc()).all()
|
users = SysUser.query.order_by(SysUser.id.desc()).all()
|
||||||
return [user.to_dict() for user in users]
|
return [user.to_dict() for user in users]
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def delete_user(user_id, operator_role):
|
def delete_user(user_id, operator_role):
|
||||||
"""删除用户"""
|
"""删除用户"""
|
||||||
if operator_role not in [UserRole.SUPER_ADMIN, UserRole.SUPERVISOR]:
|
# 只有超级管理员可以执行物理删除
|
||||||
raise Exception("权限不足")
|
if operator_role != UserRole.SUPER_ADMIN:
|
||||||
|
raise Exception("权限不足:只有超级管理员可以删除用户,建议使用禁用功能")
|
||||||
|
|
||||||
user = SysUser.query.get(user_id)
|
user = SysUser.query.get(user_id)
|
||||||
if not user:
|
if not user:
|
||||||
|
|||||||
@ -1,16 +1,20 @@
|
|||||||
# app/utils/constants.py
|
# app/utils/constants.py
|
||||||
|
|
||||||
class UserRole:
|
class UserRole:
|
||||||
SUPER_ADMIN = 'super_admin' # 超级管理员 (IRIS)
|
"""
|
||||||
SUPERVISOR = 'supervisor' # 主管
|
用户角色定义
|
||||||
FINANCE = 'finance' # 财务
|
"""
|
||||||
WAREHOUSE_MGR = 'warehouse_manager' # 库管
|
SUPER_ADMIN = 'SUPER_ADMIN' # 超级管理员 (IRIS)
|
||||||
INBOUND = 'inbound' # 入库员
|
SUPERVISOR = 'SUPERVISOR' # 主管
|
||||||
OUTBOUND = 'outbound' # 出库员
|
FINANCE = 'FINANCE' # 财务
|
||||||
PURCHASER = 'purchaser' # 采购员
|
WAREHOUSE_MGR = 'WAREHOUSE_MGR' # 库管
|
||||||
SALES = 'sales' # 销售
|
INBOUND = 'INBOUND' # 入库员
|
||||||
|
OUTBOUND = 'OUTBOUND' # 出库员
|
||||||
|
PURCHASER = 'PURCHASER' # 采购员
|
||||||
|
SALES = 'SALES' # 销售
|
||||||
|
|
||||||
# 角色中文映射(用于前端展示或日志)
|
# 角色中文映射(用于前端展示或日志)
|
||||||
|
# 注意:这个字典在 auth_service 遍历时需要被过滤掉
|
||||||
ROLE_MAP = {
|
ROLE_MAP = {
|
||||||
SUPER_ADMIN: '超级管理员',
|
SUPER_ADMIN: '超级管理员',
|
||||||
SUPERVISOR: '主管',
|
SUPERVISOR: '主管',
|
||||||
|
|||||||
@ -4,6 +4,16 @@ import Layout from '@/layout/index.vue'
|
|||||||
import { useUserStore } from '@/stores/user'
|
import { useUserStore } from '@/stores/user'
|
||||||
import BomManage from '@/views/bom/BomManage.vue'
|
import BomManage from '@/views/bom/BomManage.vue'
|
||||||
|
|
||||||
|
// [新增] 扩展 RouteMeta 类型定义,防止 TS 报错
|
||||||
|
declare module 'vue-router' {
|
||||||
|
interface RouteMeta {
|
||||||
|
title?: string
|
||||||
|
icon?: string
|
||||||
|
hidden?: boolean
|
||||||
|
roles?: string[] // 允许的角色列表
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const routes: Array<RouteRecordRaw> = [
|
const routes: Array<RouteRecordRaw> = [
|
||||||
// 1. 登录页
|
// 1. 登录页
|
||||||
{
|
{
|
||||||
@ -169,17 +179,25 @@ const routes: Array<RouteRecordRaw> = [
|
|||||||
{
|
{
|
||||||
path: '/system',
|
path: '/system',
|
||||||
component: Layout,
|
component: Layout,
|
||||||
|
// [修复] 添加 redirect,点击父菜单时跳转到子页面
|
||||||
|
redirect: '/system/user-create',
|
||||||
meta: {
|
meta: {
|
||||||
title: '系统管理',
|
title: '系统管理',
|
||||||
icon: 'Setting',
|
icon: 'Setting',
|
||||||
roles: ['super_admin', 'supervisor']
|
// [修复] 使用大写角色名,匹配后端常量
|
||||||
|
roles: ['SUPER_ADMIN', 'SUPERVISOR']
|
||||||
},
|
},
|
||||||
children: [
|
children: [
|
||||||
{
|
{
|
||||||
path: 'user-create',
|
path: 'user-create',
|
||||||
name: 'UserCreate',
|
name: 'UserCreate',
|
||||||
component: () => import('@/views/system/UserCreate.vue'),
|
component: () => import('@/views/system/UserCreate.vue'),
|
||||||
meta: { title: '账号开通', icon: 'User' }
|
meta: {
|
||||||
|
title: '账号开通',
|
||||||
|
icon: 'User',
|
||||||
|
// 子路由也建议加上权限限制
|
||||||
|
roles: ['SUPER_ADMIN', 'SUPERVISOR']
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@ -204,7 +222,16 @@ router.beforeEach((to, from, next) => {
|
|||||||
const userStore = useUserStore()
|
const userStore = useUserStore()
|
||||||
|
|
||||||
const token = userStore.token || localStorage.getItem('token')
|
const token = userStore.token || localStorage.getItem('token')
|
||||||
const userRole = userStore.role || localStorage.getItem('role') || 'user'
|
|
||||||
|
// [修复] 优先从 user 对象获取,并统一转大写,防止大小写不一致导致权限失效
|
||||||
|
// 注意:Store 中存储的可能是 user.role 或者直接是 role,根据你之前的 store 结构适配
|
||||||
|
const rawRole = userStore.user?.role || userStore.role || localStorage.getItem('role') || 'user'
|
||||||
|
const userRole = String(rawRole).toUpperCase()
|
||||||
|
|
||||||
|
// 调试日志:如果跳转有问题,请按 F12 查看控制台输出
|
||||||
|
if (to.path.includes('/system')) {
|
||||||
|
console.log(`路由守卫检查: Path=${to.path}, UserRole=${userRole}, Required=${to.meta.roles}`)
|
||||||
|
}
|
||||||
|
|
||||||
if (to.path === '/login') {
|
if (to.path === '/login') {
|
||||||
if (token) {
|
if (token) {
|
||||||
@ -220,10 +247,13 @@ router.beforeEach((to, from, next) => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 权限检查逻辑
|
||||||
if (to.meta.roles && Array.isArray(to.meta.roles)) {
|
if (to.meta.roles && Array.isArray(to.meta.roles)) {
|
||||||
|
// [修复] to.meta.roles 里已经是大写了,userRole 也转大写了,现在可以安全比对
|
||||||
if (to.meta.roles.includes(userRole)) {
|
if (to.meta.roles.includes(userRole)) {
|
||||||
next()
|
next()
|
||||||
} else {
|
} else {
|
||||||
|
console.warn(`权限不足: 用户角色 ${userRole} 不在允许列表 ${to.meta.roles} 中`)
|
||||||
next('/dashboard')
|
next('/dashboard')
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@ -17,42 +17,26 @@
|
|||||||
style="width: 100%"
|
style="width: 100%"
|
||||||
>
|
>
|
||||||
<el-table-column prop="username" label="用户名" width="150" />
|
<el-table-column prop="username" label="用户名" width="150" />
|
||||||
|
|
||||||
<el-table-column prop="department" label="所属部门" width="150">
|
<el-table-column prop="department" label="所属部门" width="150">
|
||||||
<template #default="scope">
|
<template #default="scope">
|
||||||
<el-tag>{{ scope.row.department }}</el-tag>
|
<el-tag>{{ scope.row.department }}</el-tag>
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
|
|
||||||
<el-table-column prop="role" label="系统角色" width="180">
|
<el-table-column prop="role" label="系统角色" width="180">
|
||||||
<template #default="scope">
|
<template #default="scope">
|
||||||
{{ formatRole(scope.row.role) }}
|
{{ formatRole(scope.row.role) }}
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
|
|
||||||
<el-table-column prop="email" label="邮箱" min-width="200" />
|
<el-table-column prop="email" label="邮箱" min-width="200" />
|
||||||
|
|
||||||
<el-table-column prop="created_at" label="创建时间" width="180">
|
<el-table-column prop="created_at" label="创建时间" width="180">
|
||||||
<template #default="scope">
|
<template #default="scope">
|
||||||
{{ formatDate(scope.row.created_at) }}
|
{{ formatDate(scope.row.created_at) }}
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
|
|
||||||
<el-table-column label="操作" width="180" fixed="right">
|
<el-table-column label="操作" width="180" fixed="right">
|
||||||
<template #default="scope">
|
<template #default="scope">
|
||||||
<el-button
|
<el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
|
||||||
link
|
<el-popconfirm title="确定要删除该用户吗?" @confirm="handleDelete(scope.row)">
|
||||||
type="primary"
|
|
||||||
size="small"
|
|
||||||
@click="handleEdit(scope.row)"
|
|
||||||
>
|
|
||||||
编辑
|
|
||||||
</el-button>
|
|
||||||
|
|
||||||
<el-popconfirm
|
|
||||||
title="确定要删除该用户吗?此操作无法撤销。"
|
|
||||||
@confirm="handleDelete(scope.row)"
|
|
||||||
>
|
|
||||||
<template #reference>
|
<template #reference>
|
||||||
<el-button link type="danger" size="small">删除</el-button>
|
<el-button link type="danger" size="small">删除</el-button>
|
||||||
</template>
|
</template>
|
||||||
@ -82,10 +66,7 @@
|
|||||||
/>
|
/>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
|
|
||||||
<el-form-item
|
<el-form-item label="密码" prop="password">
|
||||||
label="密码"
|
|
||||||
prop="password"
|
|
||||||
>
|
|
||||||
<el-input
|
<el-input
|
||||||
v-model="form.password"
|
v-model="form.password"
|
||||||
type="password"
|
type="password"
|
||||||
@ -103,24 +84,18 @@
|
|||||||
allow-create
|
allow-create
|
||||||
default-first-option
|
default-first-option
|
||||||
>
|
>
|
||||||
<el-option
|
<el-option v-for="item in departmentOptions" :key="item" :label="item" :value="item" />
|
||||||
v-for="item in departmentOptions"
|
|
||||||
:key="item"
|
|
||||||
:label="item"
|
|
||||||
:value="item"
|
|
||||||
/>
|
|
||||||
</el-select>
|
</el-select>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
|
|
||||||
<el-form-item label="系统角色" prop="role">
|
<el-form-item label="系统角色" prop="role">
|
||||||
<el-select v-model="form.role" placeholder="授予权限" style="width: 100%">
|
<el-select v-model="form.role" placeholder="授予权限" style="width: 100%">
|
||||||
<el-option label="主管" value="supervisor" />
|
<el-option
|
||||||
<el-option label="财务" value="finance" />
|
v-for="option in roleOptions"
|
||||||
<el-option label="库管" value="warehouse_manager" />
|
:key="option.value"
|
||||||
<el-option label="入库员" value="inbound" />
|
:label="option.label"
|
||||||
<el-option label="出库员" value="outbound" />
|
:value="option.value"
|
||||||
<el-option label="采购员" value="purchaser" />
|
/>
|
||||||
<el-option label="销售" value="sales" />
|
|
||||||
</el-select>
|
</el-select>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
|
|
||||||
@ -144,9 +119,11 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { reactive, ref, onMounted, computed } from 'vue'
|
import { reactive, ref, onMounted, computed } from 'vue'
|
||||||
import { createUser, updateUser, getUserList, deleteUser } from '@/api/auth'
|
import { createUser, updateUser, getUserList, deleteUser } from '@/api/auth'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
import { ElMessage } from 'element-plus'
|
import { ElMessage } from 'element-plus'
|
||||||
|
|
||||||
// --- 状态定义 ---
|
// --- 状态定义 ---
|
||||||
|
const userStore = useUserStore()
|
||||||
const tableLoading = ref(false)
|
const tableLoading = ref(false)
|
||||||
const submitLoading = ref(false)
|
const submitLoading = ref(false)
|
||||||
const dialogVisible = ref(false)
|
const dialogVisible = ref(false)
|
||||||
@ -154,7 +131,6 @@ const tableData = ref<any[]>([])
|
|||||||
const departmentOptions = ref<string[]>([])
|
const departmentOptions = ref<string[]>([])
|
||||||
const formRef = ref()
|
const formRef = ref()
|
||||||
|
|
||||||
// [新增] 区分编辑/创建模式
|
|
||||||
const isEdit = ref(false)
|
const isEdit = ref(false)
|
||||||
const currentId = ref<number | null>(null)
|
const currentId = ref<number | null>(null)
|
||||||
|
|
||||||
@ -166,20 +142,52 @@ const form = reactive({
|
|||||||
email: ''
|
email: ''
|
||||||
})
|
})
|
||||||
|
|
||||||
// [关键] 动态规则:编辑模式下密码不是必填项
|
// [核心逻辑] 角色选项列表 (保留了之前的强力判断逻辑,但去除了 debug 变量)
|
||||||
|
const roleOptions = computed(() => {
|
||||||
|
const options = [
|
||||||
|
{ label: '主管', value: 'SUPERVISOR' },
|
||||||
|
{ label: '财务', value: 'FINANCE' },
|
||||||
|
{ label: '库管', value: 'WAREHOUSE_MGR' },
|
||||||
|
{ label: '入库员', value: 'INBOUND' },
|
||||||
|
{ label: '出库员', value: 'OUTBOUND' },
|
||||||
|
{ label: '采购员', value: 'PURCHASER' },
|
||||||
|
{ label: '销售', value: 'SALES' }
|
||||||
|
]
|
||||||
|
|
||||||
|
// 1. 尝试从 Pinia Store 获取信息
|
||||||
|
let role = userStore.user?.role || userStore.role
|
||||||
|
let username = userStore.user?.username || userStore.name
|
||||||
|
|
||||||
|
// 2. 如果 Store 没数据,尝试从 LocalStorage 补救
|
||||||
|
if (!role) role = localStorage.getItem('role')
|
||||||
|
if (!username) username = localStorage.getItem('username')
|
||||||
|
|
||||||
|
// 3. 统一转大写
|
||||||
|
const safeRole = role ? String(role).toUpperCase() : ''
|
||||||
|
const safeUsername = username ? String(username).toUpperCase() : ''
|
||||||
|
|
||||||
|
// 4. [关键] 只要是 IRIS 或者 角色包含 ADMIN,就开启上帝模式
|
||||||
|
const isSuperAdmin = (safeRole === 'SUPER_ADMIN') || (safeUsername === 'IRIS')
|
||||||
|
|
||||||
|
if (isSuperAdmin) {
|
||||||
|
options.unshift({ label: '超级管理员', value: 'SUPER_ADMIN' })
|
||||||
|
}
|
||||||
|
|
||||||
|
return options
|
||||||
|
})
|
||||||
|
|
||||||
|
// 验证规则
|
||||||
const rules = computed(() => {
|
const rules = computed(() => {
|
||||||
const commonRules = {
|
const commonRules: any = {
|
||||||
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
|
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
|
||||||
role: [{ required: true, message: '请选择角色', trigger: 'change' }],
|
role: [{ required: true, message: '请选择角色', trigger: 'change' }],
|
||||||
department: [{ required: true, message: '请输入或选择部门', trigger: ['blur', 'change'] }],
|
department: [{ required: true, message: '请输入或选择部门', trigger: ['blur', 'change'] }],
|
||||||
// [新增] 邮箱必填校验规则
|
|
||||||
email: [
|
email: [
|
||||||
{ required: true, message: '请输入邮箱', trigger: 'blur' },
|
{ required: true, message: '请输入邮箱', trigger: 'blur' },
|
||||||
{ type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
|
{ type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果是创建模式,密码必填
|
|
||||||
if (!isEdit.value) {
|
if (!isEdit.value) {
|
||||||
return {
|
return {
|
||||||
...commonRules,
|
...commonRules,
|
||||||
@ -189,7 +197,6 @@ const rules = computed(() => {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 如果是编辑模式,密码选填(只有输入了才校验长度)
|
|
||||||
return {
|
return {
|
||||||
...commonRules,
|
...commonRules,
|
||||||
password: [
|
password: [
|
||||||
@ -226,51 +233,47 @@ const extractDepartments = (data: any[]) => {
|
|||||||
departmentOptions.value = Array.from(deptSet)
|
departmentOptions.value = Array.from(deptSet)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 打开新增弹窗
|
|
||||||
const handleCreate = () => {
|
const handleCreate = () => {
|
||||||
isEdit.value = false
|
isEdit.value = false
|
||||||
currentId.value = null
|
currentId.value = null
|
||||||
resetFormState() // 清空数据
|
form.username = ''
|
||||||
|
form.password = ''
|
||||||
|
form.department = ''
|
||||||
|
form.role = ''
|
||||||
|
form.email = ''
|
||||||
|
if (formRef.value) formRef.value.clearValidate()
|
||||||
dialogVisible.value = true
|
dialogVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
// [新增] 打开编辑弹窗
|
|
||||||
const handleEdit = (row: any) => {
|
const handleEdit = (row: any) => {
|
||||||
isEdit.value = true
|
isEdit.value = true
|
||||||
currentId.value = row.id
|
currentId.value = row.id
|
||||||
|
|
||||||
// 回填数据
|
|
||||||
form.username = row.username
|
form.username = row.username
|
||||||
form.department = row.department
|
form.department = row.department
|
||||||
form.role = row.role
|
form.role = row.role
|
||||||
form.email = row.email || ''
|
form.email = row.email || ''
|
||||||
form.password = '' // 编辑时不回显密码,留空表示不修改
|
form.password = ''
|
||||||
|
if (formRef.value) formRef.value.clearValidate()
|
||||||
dialogVisible.value = true
|
dialogVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 提交 (兼容创建和修改)
|
|
||||||
const onSubmit = async () => {
|
const onSubmit = async () => {
|
||||||
if (!formRef.value) return
|
if (!formRef.value) return
|
||||||
|
|
||||||
await formRef.value.validate(async (valid: boolean) => {
|
await formRef.value.validate(async (valid: boolean) => {
|
||||||
if (valid) {
|
if (valid) {
|
||||||
submitLoading.value = true
|
submitLoading.value = true
|
||||||
try {
|
try {
|
||||||
if (isEdit.value && currentId.value) {
|
if (isEdit.value && currentId.value) {
|
||||||
// 编辑逻辑
|
|
||||||
await updateUser(currentId.value, form)
|
await updateUser(currentId.value, form)
|
||||||
ElMessage.success(`用户 ${form.username} 修改成功!`)
|
ElMessage.success(`用户 ${form.username} 修改成功!`)
|
||||||
} else {
|
} else {
|
||||||
// 创建逻辑
|
|
||||||
await createUser(form)
|
await createUser(form)
|
||||||
ElMessage.success(`用户 ${form.username} 创建成功!`)
|
ElMessage.success(`用户 ${form.username} 创建成功!`)
|
||||||
}
|
}
|
||||||
|
|
||||||
dialogVisible.value = false
|
dialogVisible.value = false
|
||||||
getList()
|
getList()
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// 错误已处理
|
// request 拦截器会处理错误
|
||||||
} finally {
|
} finally {
|
||||||
submitLoading.value = false
|
submitLoading.value = false
|
||||||
}
|
}
|
||||||
@ -278,14 +281,9 @@ const onSubmit = async () => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. 重置表单
|
|
||||||
const resetForm = () => {
|
const resetForm = () => {
|
||||||
if (!formRef.value) return
|
if (!formRef.value) return
|
||||||
formRef.value.resetFields()
|
formRef.value.resetFields()
|
||||||
resetFormState()
|
|
||||||
}
|
|
||||||
|
|
||||||
const resetFormState = () => {
|
|
||||||
form.username = ''
|
form.username = ''
|
||||||
form.password = ''
|
form.password = ''
|
||||||
form.department = ''
|
form.department = ''
|
||||||
@ -293,19 +291,15 @@ const resetFormState = () => {
|
|||||||
form.email = ''
|
form.email = ''
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. 删除用户
|
|
||||||
const handleDelete = async (row: any) => {
|
const handleDelete = async (row: any) => {
|
||||||
try {
|
try {
|
||||||
await deleteUser(row.id)
|
await deleteUser(row.id)
|
||||||
ElMessage.success('删除成功')
|
ElMessage.success('删除成功')
|
||||||
getList()
|
getList()
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// 错误处理
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 辅助显示方法 ---
|
|
||||||
|
|
||||||
const formatDate = (dateStr: string) => {
|
const formatDate = (dateStr: string) => {
|
||||||
if (!dateStr) return '-'
|
if (!dateStr) return '-'
|
||||||
return dateStr.replace('T', ' ').substring(0, 19)
|
return dateStr.replace('T', ' ').substring(0, 19)
|
||||||
@ -313,19 +307,19 @@ const formatDate = (dateStr: string) => {
|
|||||||
|
|
||||||
const formatRole = (val: string) => {
|
const formatRole = (val: string) => {
|
||||||
const map: Record<string, string> = {
|
const map: Record<string, string> = {
|
||||||
'supervisor': '主管',
|
'SUPER_ADMIN': '超级管理员',
|
||||||
'finance': '财务',
|
'SUPERVISOR': '主管',
|
||||||
'warehouse_manager': '库管',
|
'FINANCE': '财务',
|
||||||
'inbound': '入库员',
|
'WAREHOUSE_MGR': '库管',
|
||||||
'outbound': '出库员',
|
'INBOUND': '入库员',
|
||||||
'purchaser': '采购员',
|
'OUTBOUND': '出库员',
|
||||||
'sales': '销售',
|
'PURCHASER': '采购员',
|
||||||
'super_admin': '超级管理员'
|
'SALES': '销售'
|
||||||
}
|
}
|
||||||
return map[val] || val
|
const key = val ? val.toUpperCase() : ''
|
||||||
|
return map[key] || val
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 初始化 ---
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
getList()
|
getList()
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user