完善保险项目和养殖端小程序
This commit is contained in:
93
insurance_backend/check_db_structure.js
Normal file
93
insurance_backend/check_db_structure.js
Normal file
@@ -0,0 +1,93 @@
|
||||
const { sequelize } = require('./config/database');
|
||||
|
||||
async function checkDatabaseStructure() {
|
||||
try {
|
||||
console.log('🔍 检查数据库表结构...\n');
|
||||
|
||||
// 检查数据库连接
|
||||
await sequelize.authenticate();
|
||||
console.log('✅ 数据库连接成功\n');
|
||||
|
||||
// 检查所有表
|
||||
const [tables] = await sequelize.query('SHOW TABLES');
|
||||
console.log('📋 数据库中的表:');
|
||||
tables.forEach(table => {
|
||||
const tableName = Object.values(table)[0];
|
||||
console.log(` - ${tableName}`);
|
||||
});
|
||||
|
||||
console.log('\n🏗️ 检查关键表结构:\n');
|
||||
|
||||
// 检查users表
|
||||
try {
|
||||
const [usersStructure] = await sequelize.query('DESCRIBE users');
|
||||
console.log('👥 users表结构:');
|
||||
usersStructure.forEach(column => {
|
||||
console.log(` - ${column.Field}: ${column.Type} ${column.Null === 'NO' ? '(必填)' : '(可选)'} ${column.Key ? `[${column.Key}]` : ''}`);
|
||||
});
|
||||
} catch (error) {
|
||||
console.log('❌ users表不存在');
|
||||
}
|
||||
|
||||
console.log('');
|
||||
|
||||
// 检查permissions表
|
||||
try {
|
||||
const [permissionsStructure] = await sequelize.query('DESCRIBE permissions');
|
||||
console.log('🔐 permissions表结构:');
|
||||
permissionsStructure.forEach(column => {
|
||||
console.log(` - ${column.Field}: ${column.Type} ${column.Null === 'NO' ? '(必填)' : '(可选)'} ${column.Key ? `[${column.Key}]` : ''}`);
|
||||
});
|
||||
} catch (error) {
|
||||
console.log('❌ permissions表不存在');
|
||||
}
|
||||
|
||||
console.log('');
|
||||
|
||||
// 检查roles表
|
||||
try {
|
||||
const [rolesStructure] = await sequelize.query('DESCRIBE roles');
|
||||
console.log('👑 roles表结构:');
|
||||
rolesStructure.forEach(column => {
|
||||
console.log(` - ${column.Field}: ${column.Type} ${column.Null === 'NO' ? '(必填)' : '(可选)'} ${column.Key ? `[${column.Key}]` : ''}`);
|
||||
});
|
||||
} catch (error) {
|
||||
console.log('❌ roles表不存在');
|
||||
}
|
||||
|
||||
console.log('');
|
||||
|
||||
// 检查role_permissions表
|
||||
try {
|
||||
const [rolePermissionsStructure] = await sequelize.query('DESCRIBE role_permissions');
|
||||
console.log('🔗 role_permissions表结构:');
|
||||
rolePermissionsStructure.forEach(column => {
|
||||
console.log(` - ${column.Field}: ${column.Type} ${column.Null === 'NO' ? '(必填)' : '(可选)'} ${column.Key ? `[${column.Key}]` : ''}`);
|
||||
});
|
||||
} catch (error) {
|
||||
console.log('❌ role_permissions表不存在');
|
||||
}
|
||||
|
||||
console.log('\n📊 检查数据量:');
|
||||
|
||||
// 检查各表数据量
|
||||
const tables_to_check = ['users', 'permissions', 'roles', 'role_permissions'];
|
||||
|
||||
for (const tableName of tables_to_check) {
|
||||
try {
|
||||
const [result] = await sequelize.query(`SELECT COUNT(*) as count FROM ${tableName}`);
|
||||
console.log(` - ${tableName}: ${result[0].count} 条记录`);
|
||||
} catch (error) {
|
||||
console.log(` - ${tableName}: 表不存在或查询失败`);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 检查失败:', error.message);
|
||||
} finally {
|
||||
await sequelize.close();
|
||||
console.log('\n🔚 检查完成');
|
||||
}
|
||||
}
|
||||
|
||||
checkDatabaseStructure();
|
||||
@@ -264,6 +264,42 @@ const getChartData = async (req, res) => {
|
||||
date: item.dataValues.date,
|
||||
value: parseInt(item.dataValues.count)
|
||||
}));
|
||||
} else if (type === 'claims') {
|
||||
// 获取理赔数据趋势
|
||||
const claims = await Claim.findAll({
|
||||
where: {
|
||||
created_at: {
|
||||
[Op.gte]: startDate,
|
||||
[Op.lte]: endDate
|
||||
}
|
||||
},
|
||||
attributes: [
|
||||
[dbSequelize.fn('DATE', dbSequelize.col('created_at')), 'date'],
|
||||
[dbSequelize.fn('COUNT', dbSequelize.col('id')), 'count']
|
||||
],
|
||||
group: [dbSequelize.fn('DATE', dbSequelize.col('created_at'))],
|
||||
order: [[dbSequelize.fn('DATE', dbSequelize.col('created_at')), 'ASC']]
|
||||
});
|
||||
|
||||
chartData = claims.map(item => ({
|
||||
date: item.dataValues.date,
|
||||
value: parseInt(item.dataValues.count)
|
||||
}));
|
||||
} else if (type === 'policy_status') {
|
||||
// 获取保单状态分布数据
|
||||
const policyStatusData = await Policy.findAll({
|
||||
attributes: [
|
||||
'policy_status',
|
||||
[dbSequelize.fn('COUNT', dbSequelize.col('id')), 'count']
|
||||
],
|
||||
group: ['policy_status'],
|
||||
order: [[dbSequelize.fn('COUNT', dbSequelize.col('id')), 'DESC']]
|
||||
});
|
||||
|
||||
chartData = policyStatusData.map(item => ({
|
||||
status: item.dataValues.policy_status,
|
||||
count: parseInt(item.dataValues.count)
|
||||
}));
|
||||
}
|
||||
|
||||
console.log(`获取到 ${chartData.length} 条图表数据`);
|
||||
|
||||
@@ -6,32 +6,32 @@ const { Op } = require('sequelize');
|
||||
const getPolicies = async (req, res) => {
|
||||
try {
|
||||
const {
|
||||
policy_no,
|
||||
customer_name,
|
||||
policy_status,
|
||||
payment_status,
|
||||
policy_number, // 前端发送的参数名
|
||||
policyholder_name, // 前端发送的参数名
|
||||
insurance_type_id, // 前端发送的参数名
|
||||
status, // 前端发送的参数名
|
||||
page = 1,
|
||||
limit = 10
|
||||
pageSize = 10 // 前端发送的参数名
|
||||
} = req.query;
|
||||
|
||||
const whereClause = {};
|
||||
|
||||
// 保单编号筛选
|
||||
if (policy_no) {
|
||||
whereClause.policy_no = { [Op.like]: `%${policy_no}%` };
|
||||
if (policy_number) {
|
||||
whereClause.policy_no = { [Op.like]: `%${policy_number}%` };
|
||||
}
|
||||
|
||||
// 保单状态筛选
|
||||
if (policy_status) {
|
||||
whereClause.policy_status = policy_status;
|
||||
if (status) {
|
||||
whereClause.policy_status = status;
|
||||
}
|
||||
|
||||
// 支付状态筛选
|
||||
if (payment_status) {
|
||||
whereClause.payment_status = payment_status;
|
||||
// 保险类型筛选
|
||||
if (insurance_type_id) {
|
||||
whereClause.insurance_type_id = insurance_type_id;
|
||||
}
|
||||
|
||||
const offset = (page - 1) * limit;
|
||||
const offset = (page - 1) * pageSize;
|
||||
|
||||
const { count, rows } = await Policy.findAndCountAll({
|
||||
where: whereClause,
|
||||
@@ -52,16 +52,45 @@ const getPolicies = async (req, res) => {
|
||||
model: User,
|
||||
as: 'customer',
|
||||
attributes: ['id', 'real_name', 'username']
|
||||
},
|
||||
{
|
||||
model: InsuranceType,
|
||||
as: 'insurance_type',
|
||||
attributes: ['id', 'name']
|
||||
}
|
||||
],
|
||||
order: [['created_at', 'DESC']],
|
||||
offset,
|
||||
limit: parseInt(limit)
|
||||
limit: parseInt(pageSize)
|
||||
});
|
||||
|
||||
res.json(responseFormat.pagination(rows, {
|
||||
// 处理返回数据,确保前端能够正确解析
|
||||
const processedRows = rows.map(row => {
|
||||
const policy = row.toJSON();
|
||||
return {
|
||||
id: policy.id,
|
||||
policy_number: policy.policy_no, // 映射字段名
|
||||
policyholder_name: policy.application?.customer_name || policy.customer?.real_name || '',
|
||||
insured_name: policy.application?.customer_name || policy.customer?.real_name || '',
|
||||
insurance_type_id: policy.insurance_type_id,
|
||||
insurance_type_name: policy.insurance_type?.name || '',
|
||||
premium_amount: parseFloat(policy.premium_amount) || 0,
|
||||
coverage_amount: parseFloat(policy.coverage_amount) || 0,
|
||||
start_date: policy.start_date,
|
||||
end_date: policy.end_date,
|
||||
status: policy.policy_status, // 映射字段名
|
||||
phone: policy.application?.customer_phone || '',
|
||||
email: policy.customer?.email || '',
|
||||
address: policy.application?.address || '',
|
||||
remarks: policy.terms_and_conditions || '',
|
||||
created_at: policy.created_at,
|
||||
updated_at: policy.updated_at
|
||||
};
|
||||
});
|
||||
|
||||
res.json(responseFormat.pagination(processedRows, {
|
||||
page: parseInt(page),
|
||||
limit: parseInt(limit),
|
||||
pageSize: parseInt(pageSize),
|
||||
total: count
|
||||
}, '获取保单列表成功'));
|
||||
} catch (error) {
|
||||
|
||||
@@ -17,17 +17,21 @@ class RolePermissionController {
|
||||
order: [['id', 'ASC']]
|
||||
});
|
||||
|
||||
const rolesData = roles.map(role => {
|
||||
let permissions = [];
|
||||
if (Array.isArray(role.permissions)) {
|
||||
permissions = role.permissions;
|
||||
} else if (typeof role.permissions === 'string') {
|
||||
try {
|
||||
permissions = JSON.parse(role.permissions);
|
||||
} catch (e) {
|
||||
permissions = [];
|
||||
}
|
||||
}
|
||||
const rolesData = await Promise.all(roles.map(async (role) => {
|
||||
// 从RolePermission表获取权限
|
||||
const rolePermissions = await RolePermission.findAll({
|
||||
where: {
|
||||
role_id: role.id,
|
||||
granted: true
|
||||
},
|
||||
include: [{
|
||||
model: Permission,
|
||||
as: 'permission',
|
||||
attributes: ['id', 'name', 'code', 'description', 'module', 'type']
|
||||
}]
|
||||
});
|
||||
|
||||
const permissions = rolePermissions.map(rp => rp.permission.code);
|
||||
|
||||
return {
|
||||
id: role.id,
|
||||
@@ -37,7 +41,7 @@ class RolePermissionController {
|
||||
permissions: permissions,
|
||||
permissionCount: permissions.length
|
||||
};
|
||||
});
|
||||
}));
|
||||
|
||||
res.json(responseFormat.success({
|
||||
roles: rolesData,
|
||||
@@ -71,8 +75,10 @@ class RolePermissionController {
|
||||
async getRolePermissionDetail(req, res) {
|
||||
try {
|
||||
const { roleId } = req.params;
|
||||
console.log('获取角色权限详情,角色ID:', roleId);
|
||||
|
||||
const role = await Role.findByPk(roleId);
|
||||
console.log('角色查询结果:', role ? role.name : '未找到');
|
||||
|
||||
if (!role) {
|
||||
return res.status(404).json(responseFormat.error('角色不存在'));
|
||||
@@ -83,26 +89,25 @@ class RolePermissionController {
|
||||
attributes: ['id', 'name', 'code', 'description', 'module', 'type', 'parent_id'],
|
||||
order: [['module', 'ASC'], ['id', 'ASC']]
|
||||
});
|
||||
console.log('权限查询结果:', allPermissions.length, '个权限');
|
||||
|
||||
// 构建权限树结构
|
||||
const controller = this;
|
||||
const permissionTree = controller.buildPermissionTree(allPermissions);
|
||||
|
||||
// 获取角色已分配的权限代码
|
||||
let assignedPermissionCodes = [];
|
||||
if (Array.isArray(role.permissions)) {
|
||||
assignedPermissionCodes = role.permissions;
|
||||
} else if (typeof role.permissions === 'string') {
|
||||
try {
|
||||
assignedPermissionCodes = JSON.parse(role.permissions);
|
||||
} catch (e) {
|
||||
assignedPermissionCodes = [];
|
||||
}
|
||||
}
|
||||
|
||||
// 标记已分配的权限
|
||||
const markedPermissions = controller.markAssignedPermissionsByCode(permissionTree, assignedPermissionCodes);
|
||||
// 从RolePermission表获取角色已分配的权限
|
||||
const rolePermissions = await RolePermission.findAll({
|
||||
where: {
|
||||
role_id: roleId,
|
||||
granted: true
|
||||
},
|
||||
include: [{
|
||||
model: Permission,
|
||||
as: 'permission',
|
||||
attributes: ['id', 'name', 'code', 'description', 'module', 'type']
|
||||
}]
|
||||
});
|
||||
|
||||
const assignedPermissionCodes = rolePermissions.map(rp => rp.permission.code);
|
||||
console.log('已分配权限代码:', assignedPermissionCodes.length, '个');
|
||||
|
||||
// 暂时返回简化数据,不构建权限树
|
||||
res.json(responseFormat.success({
|
||||
role: {
|
||||
id: role.id,
|
||||
@@ -111,12 +116,22 @@ class RolePermissionController {
|
||||
status: role.status
|
||||
},
|
||||
assignedPermissions: assignedPermissionCodes,
|
||||
allPermissions: markedPermissions,
|
||||
allPermissions: allPermissions.map(p => ({
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
code: p.code,
|
||||
description: p.description,
|
||||
module: p.module,
|
||||
type: p.type,
|
||||
parent_id: p.parent_id,
|
||||
assigned: assignedPermissionCodes.includes(p.code)
|
||||
})),
|
||||
assignedCount: assignedPermissionCodes.length,
|
||||
totalCount: allPermissions.length
|
||||
}, '获取角色权限详情成功'));
|
||||
} catch (error) {
|
||||
console.error('获取角色权限详情失败:', error);
|
||||
console.error('错误堆栈:', error.stack);
|
||||
res.status(500).json(responseFormat.error('获取角色权限详情失败'));
|
||||
}
|
||||
}
|
||||
@@ -129,14 +144,24 @@ class RolePermissionController {
|
||||
const { roleId } = req.params;
|
||||
const { permissionIds, operation = 'replace' } = req.body;
|
||||
|
||||
console.log('=== 批量分配权限开始 ===');
|
||||
console.log('角色ID:', roleId);
|
||||
console.log('权限ID列表:', permissionIds);
|
||||
console.log('操作类型:', operation);
|
||||
console.log('请求体:', JSON.stringify(req.body, null, 2));
|
||||
|
||||
if (!Array.isArray(permissionIds)) {
|
||||
console.log('❌ 权限ID列表格式错误');
|
||||
return res.status(400).json(responseFormat.error('权限ID列表格式错误'));
|
||||
}
|
||||
|
||||
const role = await Role.findByPk(roleId);
|
||||
if (!role) {
|
||||
console.log('❌ 角色不存在');
|
||||
return res.status(404).json(responseFormat.error('角色不存在'));
|
||||
}
|
||||
|
||||
console.log('找到角色:', role.name);
|
||||
|
||||
// 验证权限ID是否存在
|
||||
const validPermissions = await Permission.findAll({
|
||||
@@ -147,14 +172,21 @@ class RolePermissionController {
|
||||
const validPermissionIds = validPermissions.map(p => p.id);
|
||||
const invalidIds = permissionIds.filter(id => !validPermissionIds.includes(id));
|
||||
|
||||
console.log('有效权限ID:', validPermissionIds);
|
||||
console.log('无效权限ID:', invalidIds);
|
||||
|
||||
if (invalidIds.length > 0) {
|
||||
console.log('❌ 存在无效的权限ID');
|
||||
return res.status(400).json(responseFormat.error(`无效的权限ID: ${invalidIds.join(', ')}`));
|
||||
}
|
||||
|
||||
// 根据操作类型处理权限分配
|
||||
if (operation === 'replace') {
|
||||
console.log('执行替换模式权限分配');
|
||||
|
||||
// 替换模式:删除现有权限,添加新权限
|
||||
await RolePermission.destroy({ where: { role_id: roleId } });
|
||||
const deletedCount = await RolePermission.destroy({ where: { role_id: roleId } });
|
||||
console.log('删除现有权限数量:', deletedCount);
|
||||
|
||||
if (permissionIds.length > 0) {
|
||||
const rolePermissions = permissionIds.map(permissionId => ({
|
||||
@@ -162,7 +194,10 @@ class RolePermissionController {
|
||||
permission_id: permissionId,
|
||||
granted: true
|
||||
}));
|
||||
await RolePermission.bulkCreate(rolePermissions);
|
||||
console.log('准备创建的权限记录:', rolePermissions);
|
||||
|
||||
const createdPermissions = await RolePermission.bulkCreate(rolePermissions);
|
||||
console.log('成功创建的权限记录数量:', createdPermissions.length);
|
||||
}
|
||||
} else if (operation === 'add') {
|
||||
// 添加模式:只添加新权限
|
||||
@@ -191,11 +226,15 @@ class RolePermissionController {
|
||||
});
|
||||
}
|
||||
|
||||
console.log('✅ 权限分配完成');
|
||||
res.json(responseFormat.success(null, `${operation === 'replace' ? '替换' : operation === 'add' ? '添加' : '移除'}角色权限成功`));
|
||||
} catch (error) {
|
||||
console.error('批量分配角色权限失败:', error);
|
||||
console.error('❌ 批量分配权限失败:', error);
|
||||
console.error('错误堆栈:', error.stack);
|
||||
res.status(500).json(responseFormat.error('批量分配角色权限失败'));
|
||||
}
|
||||
|
||||
console.log('=== 批量分配权限结束 ===');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,7 +6,7 @@ async function generateTestData() {
|
||||
port: 9527,
|
||||
user: 'root',
|
||||
password: 'aiotAiot123!',
|
||||
database: 'insurance_data'
|
||||
database: 'nxxmdata'
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -62,8 +62,8 @@ async function generateTestData() {
|
||||
status, application_date, review_notes, reviewer_id, review_date)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`, [
|
||||
app[0], app[1], app[2], app[3], app[4], app[5], app[6], app[8], app[9],
|
||||
app[10], app[11], app[12], app[13], app[14]
|
||||
app[0], app[1], app[2], app[3], app[4], app[5], app[6], app[7], app[8],
|
||||
app[9], app[10], app[11], app[12], app[13]
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ const checkPermission = (resource, action) => {
|
||||
// 如果JWT中没有权限信息,或者JWT权限不足,从数据库查询最新权限
|
||||
if (permissions.length === 0 || !hasPermission) {
|
||||
console.log('JWT权限不足或为空,从数据库获取最新权限...');
|
||||
const { Role } = require('../models');
|
||||
const { Role, RolePermission, Permission } = require('../models');
|
||||
const userRole = await Role.findByPk(user.role_id);
|
||||
|
||||
if (!userRole) {
|
||||
@@ -141,21 +141,21 @@ const checkPermission = (resource, action) => {
|
||||
return res.status(403).json(responseFormat.error('用户角色不存在'));
|
||||
}
|
||||
|
||||
let rolePermissions = userRole.permissions || [];
|
||||
// 从RolePermission表获取权限
|
||||
const rolePermissions = await RolePermission.findAll({
|
||||
where: {
|
||||
role_id: user.role_id,
|
||||
granted: true
|
||||
},
|
||||
include: [{
|
||||
model: Permission,
|
||||
as: 'permission',
|
||||
attributes: ['code']
|
||||
}]
|
||||
});
|
||||
|
||||
// 如果permissions是字符串,尝试解析为JSON
|
||||
if (typeof rolePermissions === 'string') {
|
||||
try {
|
||||
permissions = JSON.parse(rolePermissions);
|
||||
} catch (e) {
|
||||
console.log('数据库权限解析失败:', e.message);
|
||||
permissions = [];
|
||||
}
|
||||
} else if (Array.isArray(rolePermissions)) {
|
||||
permissions = rolePermissions;
|
||||
}
|
||||
|
||||
console.log('从数据库获取的最新权限:', permissions);
|
||||
permissions = rolePermissions.map(rp => rp.permission.code);
|
||||
console.log('从RolePermission表获取的最新权限:', permissions);
|
||||
|
||||
// 重新检查权限
|
||||
hasPermission = permissions.includes(requiredPermission) ||
|
||||
|
||||
@@ -172,7 +172,7 @@ router.get('/recent-activities', jwtAuth, checkPermission('dashboard', 'read'),
|
||||
* name: type
|
||||
* schema:
|
||||
* type: string
|
||||
* enum: [applications, policies, claims]
|
||||
* enum: [applications, policies, claims, policy_status]
|
||||
* default: applications
|
||||
* description: 图表数据类型
|
||||
* - in: query
|
||||
|
||||
@@ -9,27 +9,27 @@ const {
|
||||
deleteLivestockPolicy,
|
||||
getLivestockPolicyStats
|
||||
} = require('../controllers/livestockPolicyController');
|
||||
const { authenticateToken, requirePermission } = require('../middleware/auth');
|
||||
const { jwtAuth, checkPermission } = require('../middleware/auth');
|
||||
|
||||
// 获取生资保单列表
|
||||
router.get('/', authenticateToken, requirePermission('livestock_policy:read'), getLivestockPolicies);
|
||||
router.get('/', jwtAuth, checkPermission('insurance:policy', 'view'), getLivestockPolicies);
|
||||
|
||||
// 获取生资保单统计
|
||||
router.get('/stats', authenticateToken, requirePermission('livestock_policy:read'), getLivestockPolicyStats);
|
||||
router.get('/stats', jwtAuth, checkPermission('insurance:policy', 'view'), getLivestockPolicyStats);
|
||||
|
||||
// 获取单个生资保单详情
|
||||
router.get('/:id', authenticateToken, requirePermission('livestock_policy:read'), getLivestockPolicyById);
|
||||
router.get('/:id', jwtAuth, checkPermission('insurance:policy', 'view'), getLivestockPolicyById);
|
||||
|
||||
// 创建生资保单
|
||||
router.post('/', authenticateToken, requirePermission('livestock_policy:create'), createLivestockPolicy);
|
||||
router.post('/', jwtAuth, checkPermission('insurance:policy', 'create'), createLivestockPolicy);
|
||||
|
||||
// 更新生资保单
|
||||
router.put('/:id', authenticateToken, requirePermission('livestock_policy:update'), updateLivestockPolicy);
|
||||
router.put('/:id', jwtAuth, checkPermission('insurance:policy', 'edit'), updateLivestockPolicy);
|
||||
|
||||
// 更新生资保单状态
|
||||
router.patch('/:id/status', authenticateToken, requirePermission('livestock_policy:update'), updateLivestockPolicyStatus);
|
||||
router.patch('/:id/status', jwtAuth, checkPermission('insurance:policy', 'edit'), updateLivestockPolicyStatus);
|
||||
|
||||
// 删除生资保单
|
||||
router.delete('/:id', authenticateToken, requirePermission('livestock_policy:delete'), deleteLivestockPolicy);
|
||||
router.delete('/:id', jwtAuth, checkPermission('insurance:policy', 'delete'), deleteLivestockPolicy);
|
||||
|
||||
module.exports = router;
|
||||
@@ -9,27 +9,27 @@ const {
|
||||
deleteLivestockType,
|
||||
batchUpdateLivestockTypeStatus
|
||||
} = require('../controllers/livestockTypeController');
|
||||
const { authenticateToken, requirePermission } = require('../middleware/auth');
|
||||
const { jwtAuth, checkPermission } = require('../middleware/auth');
|
||||
|
||||
// 获取牲畜类型列表
|
||||
router.get('/', authenticateToken, requirePermission('livestock_type:read'), getLivestockTypes);
|
||||
router.get('/', jwtAuth, checkPermission('insurance_type', 'read'), getLivestockTypes);
|
||||
|
||||
// 获取所有启用的牲畜类型(用于下拉选择)
|
||||
router.get('/active', authenticateToken, getActiveLivestockTypes);
|
||||
router.get('/active', getActiveLivestockTypes);
|
||||
|
||||
// 获取单个牲畜类型详情
|
||||
router.get('/:id', authenticateToken, requirePermission('livestock_type:read'), getLivestockTypeById);
|
||||
router.get('/:id', jwtAuth, checkPermission('insurance_type', 'read'), getLivestockTypeById);
|
||||
|
||||
// 创建牲畜类型
|
||||
router.post('/', authenticateToken, requirePermission('livestock_type:create'), createLivestockType);
|
||||
router.post('/', jwtAuth, checkPermission('insurance_type', 'create'), createLivestockType);
|
||||
|
||||
// 更新牲畜类型
|
||||
router.put('/:id', authenticateToken, requirePermission('livestock_type:update'), updateLivestockType);
|
||||
router.put('/:id', jwtAuth, checkPermission('insurance_type', 'edit'), updateLivestockType);
|
||||
|
||||
// 删除牲畜类型
|
||||
router.delete('/:id', authenticateToken, requirePermission('livestock_type:delete'), deleteLivestockType);
|
||||
router.delete('/:id', jwtAuth, checkPermission('insurance_type', 'delete'), deleteLivestockType);
|
||||
|
||||
// 批量更新牲畜类型状态
|
||||
router.patch('/batch/status', authenticateToken, requirePermission('livestock_type:update'), batchUpdateLivestockTypeStatus);
|
||||
router.patch('/batch/status', jwtAuth, checkPermission('insurance_type', 'edit'), batchUpdateLivestockTypeStatus);
|
||||
|
||||
module.exports = router;
|
||||
@@ -4,32 +4,32 @@ const policyController = require('../controllers/policyController');
|
||||
const { jwtAuth, checkPermission } = require('../middleware/auth');
|
||||
|
||||
// 获取保单统计(必须在动态路由之前)
|
||||
router.get('/stats/overview', jwtAuth, checkPermission('policy', 'read'),
|
||||
router.get('/stats/overview', jwtAuth, checkPermission('insurance:policy', 'view'),
|
||||
policyController.getPolicyStats
|
||||
);
|
||||
|
||||
// 获取保单列表
|
||||
router.get('/', jwtAuth, checkPermission('policy', 'read'),
|
||||
router.get('/', jwtAuth, checkPermission('insurance:policy', 'view'),
|
||||
policyController.getPolicies
|
||||
);
|
||||
|
||||
// 创建保单
|
||||
router.post('/', jwtAuth, checkPermission('policy', 'create'),
|
||||
router.post('/', jwtAuth, checkPermission('insurance:policy', 'create'),
|
||||
policyController.createPolicy
|
||||
);
|
||||
|
||||
// 获取单个保单详情
|
||||
router.get('/:id', jwtAuth, checkPermission('policy', 'read'),
|
||||
router.get('/:id', jwtAuth, checkPermission('insurance:policy', 'view'),
|
||||
policyController.getPolicyById
|
||||
);
|
||||
|
||||
// 更新保单
|
||||
router.put('/:id', jwtAuth, checkPermission('policy', 'update'),
|
||||
router.put('/:id', jwtAuth, checkPermission('insurance:policy', 'edit'),
|
||||
policyController.updatePolicy
|
||||
);
|
||||
|
||||
// 更新保单状态
|
||||
router.patch('/:id/status', jwtAuth, checkPermission('policy', 'update'),
|
||||
router.patch('/:id/status', jwtAuth, checkPermission('insurance:policy', 'edit'),
|
||||
policyController.updatePolicyStatus
|
||||
);
|
||||
|
||||
|
||||
156
insurance_backend/scripts/add_missing_permissions.js
Normal file
156
insurance_backend/scripts/add_missing_permissions.js
Normal file
@@ -0,0 +1,156 @@
|
||||
const { Permission, Role, RolePermission } = require('../models');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
// 需要添加的权限列表
|
||||
const missingPermissions = [
|
||||
// 用户管理权限
|
||||
{ code: 'user:read', name: '用户查看', description: '查看用户信息', module: 'user', type: 'operation' },
|
||||
{ code: 'user:create', name: '用户创建', description: '创建新用户', module: 'user', type: 'operation' },
|
||||
{ code: 'user:update', name: '用户更新', description: '更新用户信息', module: 'user', type: 'operation' },
|
||||
{ code: 'user:delete', name: '用户删除', description: '删除用户', module: 'user', type: 'operation' },
|
||||
|
||||
// 保单管理权限
|
||||
{ code: 'insurance:policy:create', name: '保单创建', description: '创建保单', module: 'insurance', type: 'operation' },
|
||||
{ code: 'insurance:policy:edit', name: '保单编辑', description: '编辑保单信息', module: 'insurance', type: 'operation' },
|
||||
{ code: 'insurance:policy:delete', name: '保单删除', description: '删除保单', module: 'insurance', type: 'operation' },
|
||||
|
||||
// 保险申请权限
|
||||
{ code: 'insurance:read', name: '保险申请查看', description: '查看保险申请', module: 'insurance', type: 'operation' },
|
||||
{ code: 'insurance:create', name: '保险申请创建', description: '创建保险申请', module: 'insurance', type: 'operation' },
|
||||
{ code: 'insurance:update', name: '保险申请更新', description: '更新保险申请', module: 'insurance', type: 'operation' },
|
||||
{ code: 'insurance:review', name: '保险申请审核', description: '审核保险申请', module: 'insurance', type: 'operation' },
|
||||
{ code: 'insurance:delete', name: '保险申请删除', description: '删除保险申请', module: 'insurance', type: 'operation' },
|
||||
|
||||
// 系统管理权限
|
||||
{ code: 'system:read', name: '系统查看', description: '查看系统信息', module: 'system', type: 'operation' },
|
||||
{ code: 'system:update', name: '系统更新', description: '更新系统配置', module: 'system', type: 'operation' },
|
||||
{ code: 'system:admin', name: '系统管理', description: '系统管理操作', module: 'system', type: 'operation' },
|
||||
{ code: 'system:export', name: '系统导出', description: '导出系统数据', module: 'system', type: 'operation' },
|
||||
|
||||
// 监管任务权限
|
||||
{ code: 'supervision_tasks:read', name: '监管任务查看', description: '查看监管任务', module: 'supervision', type: 'operation' },
|
||||
{ code: 'supervision_tasks:create', name: '监管任务创建', description: '创建监管任务', module: 'supervision', type: 'operation' },
|
||||
{ code: 'supervision_tasks:update', name: '监管任务更新', description: '更新监管任务', module: 'supervision', type: 'operation' },
|
||||
{ code: 'supervision_tasks:delete', name: '监管任务删除', description: '删除监管任务', module: 'supervision', type: 'operation' },
|
||||
|
||||
// 监管任务完成权限
|
||||
{ code: 'regulatory_task:read', name: '监管任务完成查看', description: '查看监管任务完成情况', module: 'regulatory', type: 'operation' },
|
||||
{ code: 'regulatory_task:create', name: '监管任务完成创建', description: '创建监管任务完成记录', module: 'regulatory', type: 'operation' },
|
||||
{ code: 'regulatory_task:update', name: '监管任务完成更新', description: '更新监管任务完成记录', module: 'regulatory', type: 'operation' },
|
||||
{ code: 'regulatory_task:delete', name: '监管任务完成删除', description: '删除监管任务完成记录', module: 'regulatory', type: 'operation' },
|
||||
{ code: 'regulatory_task:review', name: '监管任务完成审核', description: '审核监管任务完成记录', module: 'regulatory', type: 'operation' },
|
||||
|
||||
// 安装任务权限
|
||||
{ code: 'installation_tasks:read', name: '安装任务查看', description: '查看安装任务', module: 'installation', type: 'operation' },
|
||||
{ code: 'installation_tasks:create', name: '安装任务创建', description: '创建安装任务', module: 'installation', type: 'operation' },
|
||||
{ code: 'installation_tasks:update', name: '安装任务更新', description: '更新安装任务', module: 'installation', type: 'operation' },
|
||||
{ code: 'installation_tasks:delete', name: '安装任务删除', description: '删除安装任务', module: 'installation', type: 'operation' },
|
||||
|
||||
// 生资理赔权限
|
||||
{ code: 'livestock_claim:read', name: '生资理赔查看', description: '查看生资理赔', module: 'livestock', type: 'operation' },
|
||||
{ code: 'livestock_claim:create', name: '生资理赔创建', description: '创建生资理赔', module: 'livestock', type: 'operation' },
|
||||
{ code: 'livestock_claim:review', name: '生资理赔审核', description: '审核生资理赔', module: 'livestock', type: 'operation' },
|
||||
{ code: 'livestock_claim:payment', name: '生资理赔支付', description: '处理生资理赔支付', module: 'livestock', type: 'operation' },
|
||||
|
||||
// 设备管理权限
|
||||
{ code: 'device:read', name: '设备查看', description: '查看设备信息', module: 'device', type: 'operation' },
|
||||
{ code: 'device:create', name: '设备创建', description: '创建设备', module: 'device', type: 'operation' },
|
||||
{ code: 'device:update', name: '设备更新', description: '更新设备信息', module: 'device', type: 'operation' },
|
||||
{ code: 'device:delete', name: '设备删除', description: '删除设备', module: 'device', type: 'operation' },
|
||||
|
||||
// 设备告警权限
|
||||
{ code: 'device_alerts:read', name: '设备告警查看', description: '查看设备告警', module: 'device', type: 'operation' },
|
||||
{ code: 'device_alerts:create', name: '设备告警创建', description: '创建设备告警', module: 'device', type: 'operation' },
|
||||
{ code: 'device_alerts:update', name: '设备告警更新', description: '更新设备告警', module: 'device', type: 'operation' },
|
||||
{ code: 'device_alerts:delete', name: '设备告警删除', description: '删除设备告警', module: 'device', type: 'operation' },
|
||||
|
||||
// 理赔管理权限
|
||||
{ code: 'claim:read', name: '理赔查看', description: '查看理赔信息', module: 'claim', type: 'operation' },
|
||||
{ code: 'claim:create', name: '理赔创建', description: '创建理赔', module: 'claim', type: 'operation' },
|
||||
{ code: 'claim:update', name: '理赔更新', description: '更新理赔信息', module: 'claim', type: 'operation' },
|
||||
{ code: 'claim:delete', name: '理赔删除', description: '删除理赔', module: 'claim', type: 'operation' },
|
||||
{ code: 'claim:review', name: '理赔审核', description: '审核理赔', module: 'claim', type: 'operation' },
|
||||
|
||||
// 数据仓库权限
|
||||
{ code: 'data_warehouse:read', name: '数据仓库查看', description: '查看数据仓库', module: 'data', type: 'operation' },
|
||||
{ code: 'data_warehouse:export', name: '数据仓库导出', description: '导出数据仓库数据', module: 'data', type: 'operation' }
|
||||
];
|
||||
|
||||
async function addMissingPermissions() {
|
||||
try {
|
||||
console.log('开始添加缺失的权限...');
|
||||
|
||||
// 获取现有权限
|
||||
const existingPermissions = await Permission.findAll({
|
||||
attributes: ['code']
|
||||
});
|
||||
const existingCodes = existingPermissions.map(p => p.code);
|
||||
|
||||
// 过滤出需要添加的权限
|
||||
const permissionsToAdd = missingPermissions.filter(p => !existingCodes.includes(p.code));
|
||||
|
||||
console.log(`找到 ${permissionsToAdd.length} 个需要添加的权限`);
|
||||
|
||||
if (permissionsToAdd.length === 0) {
|
||||
console.log('所有权限都已存在,无需添加');
|
||||
return;
|
||||
}
|
||||
|
||||
// 批量创建权限
|
||||
const createdPermissions = await Permission.bulkCreate(permissionsToAdd, {
|
||||
ignoreDuplicates: true
|
||||
});
|
||||
|
||||
console.log(`成功创建 ${createdPermissions.length} 个权限`);
|
||||
|
||||
// 获取admin角色
|
||||
const adminRole = await Role.findOne({
|
||||
where: { name: 'admin' }
|
||||
});
|
||||
|
||||
if (!adminRole) {
|
||||
console.log('未找到admin角色,跳过权限分配');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`找到admin角色,ID: ${adminRole.id}`);
|
||||
|
||||
// 获取新创建的权限ID
|
||||
const newPermissions = await Permission.findAll({
|
||||
where: {
|
||||
code: {
|
||||
[Op.in]: permissionsToAdd.map(p => p.code)
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 为admin角色分配新权限
|
||||
const rolePermissions = newPermissions.map(permission => ({
|
||||
role_id: adminRole.id,
|
||||
permission_id: permission.id,
|
||||
granted: true,
|
||||
granted_by: 1, // 假设用户ID为1
|
||||
granted_at: new Date()
|
||||
}));
|
||||
|
||||
await RolePermission.bulkCreate(rolePermissions, {
|
||||
ignoreDuplicates: true
|
||||
});
|
||||
|
||||
console.log(`成功为admin角色分配 ${rolePermissions.length} 个权限`);
|
||||
|
||||
console.log('权限添加完成!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('添加权限失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 运行脚本
|
||||
addMissingPermissions().then(() => {
|
||||
console.log('脚本执行完成');
|
||||
process.exit(0);
|
||||
}).catch(error => {
|
||||
console.error('脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,4 +1,10 @@
|
||||
require('dotenv').config({ path: require('path').join(__dirname, '../.env') });
|
||||
|
||||
// 设置默认环境变量
|
||||
if (!process.env.JWT_SECRET) {
|
||||
process.env.JWT_SECRET = 'insurance_super_secret_jwt_key_2024_very_long_and_secure';
|
||||
}
|
||||
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const helmet = require('helmet');
|
||||
|
||||
Reference in New Issue
Block a user