WMS_MAIN/app/model/role_permission.js
2026-03-23 17:10:07 +08:00

146 lines
3.4 KiB
JavaScript

'use strict';
module.exports = app => {
const { BIGINT, INTEGER, DATE } = app.Sequelize;
const RolePermission = app.model.define('role_permission', {
id: {
type: BIGINT.UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '关联ID',
},
role_id: {
type: BIGINT.UNSIGNED,
allowNull: false,
comment: '角色ID',
},
permission_id: {
type: INTEGER,
allowNull: false,
comment: '权限ID',
},
created_at: {
type: DATE,
allowNull: false,
comment: '创建时间',
},
}, {
tableName: 'wms_role_permission',
freezeTableName: true,
underscored: true,
timestamps: true,
paranoid: false, // 明确禁用软删除
createdAt: 'created_at',
updatedAt: false,
comment: '角色权限关联表',
indexes: [
{
name: 'uk_role_permission',
fields: [ 'role_id', 'permission_id' ],
unique: true,
},
{
name: 'idx_role_id',
fields: [ 'role_id' ],
},
{
name: 'idx_permission_id',
fields: [ 'permission_id' ],
},
],
});
// 关联关系
RolePermission.associate = function(models) {
const { Role, Permission } = app.model;
// 关联角色
RolePermission.belongsTo(Role, {
foreignKey: 'role_id',
as: 'role',
});
// 关联权限
RolePermission.belongsTo(Permission, {
foreignKey: 'permission_id',
as: 'permission',
});
};
// 实例方法:检查关联是否有效
RolePermission.prototype.isValid = function() {
// 这里可以添加更多的有效性检查
return this.role_id && this.permission_id;
};
// 类方法:批量创建角色权限关联
RolePermission.bulkAssign = async function(roleId, permissionIds) {
const { ctx } = this;
if (!permissionIds || permissionIds.length === 0) {
return [];
}
const rolePermissions = permissionIds.map(permissionId => ({
role_id: roleId,
permission_id: permissionId,
}));
try {
return await ctx.model.RolePermission.bulkCreate(rolePermissions, {
ignoreDuplicates: true, // 忽略重复项
});
} catch (error) {
// 处理批量创建中的错误
console.error('批量创建角色权限关联失败:', error);
throw error;
}
};
// 类方法:删除角色的所有权限
RolePermission.clearRolePermissions = async function(roleId) {
const { ctx } = this;
return await ctx.model.RolePermission.destroy({
where: { role_id: roleId },
});
};
// 类方法:获取角色的权限列表
RolePermission.getRolePermissions = async function(roleId, includePermissionDetails = false) {
const { ctx } = this;
const options = {
where: { role_id: roleId },
};
if (includePermissionDetails) {
options.include = [{
model: ctx.model.Permission,
as: 'permission',
where: { status: 1 },
required: false,
}];
}
return await ctx.model.RolePermission.findAll(options);
};
// 类方法:检查角色是否拥有某个权限
RolePermission.hasPermission = async function(roleId, permissionId) {
const { ctx } = this;
const rolePermission = await ctx.model.RolePermission.findOne({
where: {
role_id: roleId,
permission_id: permissionId,
},
});
return !!rolePermission;
};
return RolePermission;
};