'use strict'; module.exports = app => { const { BIGINT, STRING, DATE, TINYINT, TEXT } = app.Sequelize; const Role = app.model.define('role', { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false, comment: '角色ID', }, role_code: { type: STRING(50), allowNull: false, unique: true, validate: { notEmpty: { msg: '角色代码不能为空', }, len: { args: [ 1, 50 ], msg: '角色代码长度应在1-50个字符之间', }, is: { args: /^[a-zA-Z0-9_]+$/, msg: '角色代码只能包含字母、数字和下划线', }, }, comment: '角色代码', }, role_name: { type: STRING(100), allowNull: false, validate: { notEmpty: { msg: '角色名称不能为空', }, len: { args: [ 1, 100 ], msg: '角色名称长度应在1-100个字符之间', }, }, comment: '角色名称', }, description: { type: STRING(500), allowNull: true, comment: '角色描述', }, permissions: { type: TEXT, allowNull: true, comment: '角色权限集,JSON数组;* 表示所有权限', }, role_type: { type: TINYINT(4), allowNull: false, defaultValue: 1, validate: { isIn: { args: [[ 1, 2 ]], msg: '角色类型只能是1或2', }, }, comment: '角色类型:1-系统角色,2-自定义角色', }, scope: { type: TINYINT(4), allowNull: false, defaultValue: 1, validate: { isIn: { args: [[ 1, 2 ]], msg: '作用范围只能是1或2', }, }, comment: '作用范围:1-全局,2-指定仓库', }, is_system: { type: TINYINT(4), allowNull: false, defaultValue: 0, validate: { isIn: { args: [[ 0, 1 ]], msg: '是否系统预设只能是0或1', }, }, comment: '是否系统预设:0-否,1-是', }, status: { type: TINYINT(4), allowNull: false, defaultValue: 1, validate: { isIn: { args: [[ 0, 1 ]], msg: '状态只能是0或1', }, }, comment: '状态:0-禁用,1-启用', }, created_by: { type: BIGINT.UNSIGNED, allowNull: false, comment: '创建人', }, created_at: { type: DATE, allowNull: false, comment: '创建时间', }, updated_at: { type: DATE, allowNull: false, comment: '更新时间', }, store_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '所属仓库ID', }, pid: { type: BIGINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '父级角色ID,顶级为0', }, }, { tableName: 'wms_role', freezeTableName: true, underscored: true, timestamps: true, createdAt: 'created_at', updatedAt: 'updated_at', comment: '平台角色表', indexes: [ { name: 'uk_role_code', fields: [ 'role_code' ], unique: true, }, { name: 'idx_role_type', fields: [ 'role_type' ], }, { name: 'idx_scope', fields: [ 'scope' ], }, { name: 'idx_status', fields: [ 'status' ], }, { name: 'idx_pid', fields: [ 'pid' ], }, ], }); // 关联关系 Role.associate = function() { const { Account, Store, EmployeeRole } = app.model; // 创建人 Role.belongsTo(Account, { foreignKey: 'created_by', as: 'creator', }); // 所属仓库 Role.belongsTo(Store, { foreignKey: 'store_id', as: 'store', }); Role.hasMany(EmployeeRole, { foreignKey: 'role_id', sourceKey: 'id', as: 'employeeRoles', }); }; // 实例方法:检查角色是否启用 Role.prototype.isEnabled = function() { return this.status === 1; }; // 实例方法:检查是否是系统预设角色 Role.prototype.isSystemRole = function() { return this.is_system === 1; }; // 实例方法:获取角色类型名称 Role.prototype.getRoleTypeName = function() { return this.role_type === 1 ? '系统角色' : '自定义角色'; }; // 实例方法:获取作用范围名称 Role.prototype.getScopeName = function() { return this.scope === 1 ? '全局' : '指定仓库'; }; return Role; };