WMS_MAIN/database/migrations/20260720160000-add-print-qty-log-export-permissions.js

203 lines
7.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 面单余额变更日志导出权限迁移。
*
* 变更内容:
* 1. 新增 2 条 api 权限记录:
* - storeWarehouse.store.exportPrintQuantityLogs — 导出面单余额变更日志
* - storeWarehouse.store.exportPrintQuantityLogsTaskProgress — 查询导出任务进度
* 2. 将上述权限授权给 财务以上角色组:
* - 货主管理员 (id=5)
* - 经理 (id=8)
* (超级管理员 id=2/7 的 permissions='*' 无需更新)
*
* 幂等设计:
* - 先查后插(按 path + type 唯一性判断)
* - 角色权限更新使用 JSON 数组合并去重
*/
const TABLE_PERMISSION = 'wms_permission';
const TABLE_ROLE = 'wms_role';
/** 需要授权的角色ID(财务以上:货主管理员 + 经理) */
const TARGET_ROLE_IDS = [ 5, 8 ];
/** @type {{path: string, name: string, meta_title: string, type: string}[]} */
const NEW_PERMISSIONS = [
{
path: 'storeWarehouse.store.exportPrintQuantityLogs',
name: 'storeWarehouse.store.exportPrintQuantityLogs',
meta_title: '导出面单余额变更日志',
type: 'api',
},
{
path: 'storeWarehouse.store.exportPrintQuantityLogsTaskProgress',
name: 'storeWarehouse.store.exportPrintQuantityLogsTaskProgress',
meta_title: '查询面单余额导出任务进度',
type: 'api',
},
];
/**
* 获取角色当前权限 ID 数组。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {number} roleId 角色ID
* @return {Promise<number[]>} 权限ID数组
*/
async function getRolePermissionIds(queryInterface, roleId) {
const [ rows ] = await queryInterface.sequelize.query(
`SELECT permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`,
{ replacements: { roleId } }
);
if (!rows || rows.length === 0) return [];
const raw = rows[0].permissions;
if (!raw || raw === '*') return [];
try {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
return parsed.map(Number).filter(n => Number.isFinite(n) && n > 0);
}
} catch (_) {
// ignore
}
return [];
}
/**
* 保存角色权限。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {number} roleId 角色ID
* @param {number[]} permissionIds 权限ID数组
* @return {Promise<void>}
*/
async function saveRolePermissions(queryInterface, roleId, permissionIds) {
const unique = Array.from(new Set(permissionIds)).sort((a, b) => a - b);
const json = JSON.stringify(unique);
await queryInterface.sequelize.query(
`UPDATE \`${TABLE_ROLE}\` SET permissions = :permissions, updated_at = NOW() WHERE id = :roleId`,
{ replacements: { roleId, permissions: json } }
);
}
/**
* 正向迁移。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @return {Promise<void>}
*/
module.exports.up = async queryInterface => {
// ─── 1. 插入新权限记录 ─────────────────────────────────
const insertedIds = [];
for (const perm of NEW_PERMISSIONS) {
const [ existing ] = await queryInterface.sequelize.query(
`SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type LIMIT 1`,
{ replacements: { path: perm.path, type: perm.type } }
);
if (existing && existing.length > 0) {
console.log(`[Migration] 权限已存在: ${perm.path} (id=${existing[0].id})`);
insertedIds.push(Number(existing[0].id));
continue;
}
const [ result ] = await queryInterface.sequelize.query(
`INSERT INTO \`${TABLE_PERMISSION}\` (path, name, meta_title, type, status, created_at, update_at)
VALUES (:path, :name, :meta_title, :type, 1, NOW(), NOW())`,
{ replacements: { path: perm.path, name: perm.name, meta_title: perm.meta_title, type: perm.type } }
);
const newId = Number(result);
insertedIds.push(newId);
console.log(`[Migration] 新增权限: ${perm.path} (id=${newId})`);
}
// ─── 2. 授权给财务以上角色组 ──────────────────────────
for (const roleId of TARGET_ROLE_IDS) {
const [ roleRows ] = await queryInterface.sequelize.query(
`SELECT id, permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`,
{ replacements: { roleId } }
);
if (!roleRows || roleRows.length === 0) {
console.log(`[Migration] 角色不存在: id=${roleId}`);
continue;
}
const raw = roleRows[0].permissions;
// 跳过 permissions='*' 的角色(已拥有全部权限)
if (raw === '*') {
console.log(`[Migration] 角色 id=${roleId} 已有全部权限(*),跳过`);
continue;
}
const currentIds = await getRolePermissionIds(queryInterface, roleId);
const newIds = insertedIds.filter(id => !currentIds.includes(id));
if (newIds.length === 0) {
console.log(`[Migration] 角色 id=${roleId} 已拥有目标权限,跳过`);
continue;
}
const merged = [ ...currentIds, ...newIds ];
await saveRolePermissions(queryInterface, roleId, merged);
console.log(`[Migration] 角色 id=${roleId} 授权成功,新增权限: [${newIds.join(', ')}]`);
}
console.log(
'[Migration] 面单余额导出权限迁移完成:' +
`新增 ${NEW_PERMISSIONS.length} 条权限,授权 ${TARGET_ROLE_IDS.length} 个角色`
);
};
/**
* 回滚迁移。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @return {Promise<void>}
*/
module.exports.down = async queryInterface => {
// ─── 1. 从角色权限中移除新增的权限ID ─────────────────
const allPaths = NEW_PERMISSIONS.map(p => p.path);
for (const roleId of TARGET_ROLE_IDS) {
const [ roleRows ] = await queryInterface.sequelize.query(
`SELECT id, permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`,
{ replacements: { roleId } }
);
if (!roleRows || roleRows.length === 0) continue;
const raw = roleRows[0].permissions;
if (!raw || raw === '*') continue;
const currentIds = await getRolePermissionIds(queryInterface, roleId);
// 查询需要移除的权限ID
const [ permRows ] = await queryInterface.sequelize.query(
`SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path IN (:paths) AND type = 'api'`,
{ replacements: { paths: allPaths } }
);
const removeIds = permRows.map(r => Number(r.id));
const filtered = currentIds.filter(id => !removeIds.includes(id));
if (filtered.length !== currentIds.length) {
await saveRolePermissions(queryInterface, roleId, filtered);
console.log(`[Migration] 角色 id=${roleId} 已移除导出权限`);
}
}
// ─── 2. 删除新增的权限记录 ───────────────────────────
for (const perm of NEW_PERMISSIONS) {
await queryInterface.sequelize.query(
`DELETE FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type`,
{ replacements: { path: perm.path, type: perm.type } }
);
console.log(`[Migration] 已删除权限: ${perm.path}`);
}
console.log('[Migration] 面单余额导出权限回滚完成');
};