225 lines
6.2 KiB
JavaScript
225 lines
6.2 KiB
JavaScript
const fs = require('fs');
|
|
const path = require('path');
|
|
const mysql = require('mysql2/promise');
|
|
|
|
const ROOT = process.cwd();
|
|
const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js');
|
|
|
|
function parseArgs(argv) {
|
|
const args = {
|
|
dryRun: false,
|
|
dbClient: 'wms',
|
|
configPath: DEFAULT_CONFIG_PATH,
|
|
};
|
|
|
|
for (const item of argv) {
|
|
if (item === '--dry-run') {
|
|
args.dryRun = true;
|
|
continue;
|
|
}
|
|
|
|
if (item.startsWith('--db-client=')) {
|
|
args.dbClient = String(item.split('=')[1] || '').trim() || 'wms';
|
|
continue;
|
|
}
|
|
|
|
if (item.startsWith('--config-path=')) {
|
|
const raw = String(item.split('=')[1] || '').trim();
|
|
args.configPath = path.resolve(ROOT, raw);
|
|
continue;
|
|
}
|
|
}
|
|
|
|
return args;
|
|
}
|
|
|
|
function loadConfig(configPath) {
|
|
if (!fs.existsSync(configPath)) {
|
|
throw new Error(`Config file not found: ${configPath}`);
|
|
}
|
|
|
|
const configFactory = require(configPath);
|
|
return typeof configFactory === 'function'
|
|
? configFactory({ name: 'wms-role-permissions-backfill' })
|
|
: configFactory;
|
|
}
|
|
|
|
function normalizeRolePermissions(rawValue) {
|
|
if (rawValue === undefined || rawValue === null) {
|
|
return { allAccess: false, permissionIds: [] };
|
|
}
|
|
|
|
if (Array.isArray(rawValue)) {
|
|
const normalizedItems = rawValue.map(item => (typeof item === 'string' ? item.trim() : item));
|
|
if (normalizedItems.some(item => item === '*')) {
|
|
return { allAccess: true, permissionIds: [] };
|
|
}
|
|
|
|
const permissionIds = normalizedItems
|
|
.map(item => Number(item))
|
|
.filter(item => Number.isFinite(item) && item > 0)
|
|
.map(item => Math.floor(item));
|
|
|
|
return {
|
|
allAccess: false,
|
|
permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b),
|
|
};
|
|
}
|
|
|
|
if (typeof rawValue === 'number') {
|
|
return normalizeRolePermissions([ rawValue ]);
|
|
}
|
|
|
|
if (typeof rawValue === 'string') {
|
|
const trimmed = rawValue.trim();
|
|
if (!trimmed) {
|
|
return { allAccess: false, permissionIds: [] };
|
|
}
|
|
if (trimmed === '*') {
|
|
return { allAccess: true, permissionIds: [] };
|
|
}
|
|
|
|
try {
|
|
const parsed = JSON.parse(trimmed);
|
|
if (parsed !== rawValue) {
|
|
return normalizeRolePermissions(parsed);
|
|
}
|
|
} catch (_) {
|
|
// ignore parse failure and continue.
|
|
}
|
|
|
|
if (trimmed.includes(',')) {
|
|
return normalizeRolePermissions(trimmed.split(','));
|
|
}
|
|
|
|
return normalizeRolePermissions([ trimmed ]);
|
|
}
|
|
|
|
return { allAccess: false, permissionIds: [] };
|
|
}
|
|
|
|
function serializeRolePermissions(rawValue) {
|
|
const state = normalizeRolePermissions(rawValue);
|
|
return state.allAccess ? '*' : JSON.stringify(state.permissionIds);
|
|
}
|
|
|
|
async function main() {
|
|
const args = parseArgs(process.argv.slice(2));
|
|
const cfg = loadConfig(args.configPath);
|
|
const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[args.dbClient];
|
|
|
|
if (!dbClient) {
|
|
throw new Error(`MySQL client not found in config.mysql.clients: ${args.dbClient}`);
|
|
}
|
|
|
|
const conn = await mysql.createConnection({
|
|
host: dbClient.host,
|
|
port: Number(dbClient.port),
|
|
user: dbClient.user,
|
|
password: dbClient.password,
|
|
database: dbClient.database,
|
|
charset: dbClient.charset || 'utf8mb4',
|
|
});
|
|
|
|
try {
|
|
const [ roleRows ] = await conn.query(
|
|
'SELECT id, role_code, permissions FROM wms_role ORDER BY id ASC'
|
|
);
|
|
const [ legacyRows ] = await conn.query(
|
|
'SELECT role_id, permission_id FROM wms_role_permission ORDER BY role_id ASC, permission_id ASC'
|
|
);
|
|
|
|
const legacyMap = new Map();
|
|
for (const row of legacyRows) {
|
|
const roleId = Number(row.role_id);
|
|
const permissionId = Number(row.permission_id);
|
|
if (!Number.isFinite(roleId) || roleId <= 0 || !Number.isFinite(permissionId) || permissionId <= 0) {
|
|
continue;
|
|
}
|
|
if (!legacyMap.has(roleId)) {
|
|
legacyMap.set(roleId, []);
|
|
}
|
|
legacyMap.get(roleId).push(permissionId);
|
|
}
|
|
|
|
const updates = [];
|
|
for (const row of roleRows) {
|
|
const roleId = Number(row.id);
|
|
const legacyPermissionIds = Array.from(new Set((legacyMap.get(roleId) || [])
|
|
.map(item => Number(item))
|
|
.filter(item => Number.isFinite(item) && item > 0)))
|
|
.sort((a, b) => a - b);
|
|
|
|
if (legacyPermissionIds.length === 0) {
|
|
continue;
|
|
}
|
|
|
|
const currentState = normalizeRolePermissions(row.permissions);
|
|
const nextValue = currentState.allAccess
|
|
? '*'
|
|
: serializeRolePermissions([ ...currentState.permissionIds, ...legacyPermissionIds ]);
|
|
const currentValue = currentState.allAccess
|
|
? '*'
|
|
: serializeRolePermissions(currentState.permissionIds);
|
|
|
|
if (nextValue !== currentValue) {
|
|
updates.push({
|
|
roleId,
|
|
roleCode: row.role_code || '',
|
|
before: row.permissions,
|
|
after: nextValue,
|
|
legacyCount: legacyPermissionIds.length,
|
|
});
|
|
}
|
|
}
|
|
|
|
if (args.dryRun) {
|
|
console.log('[backfill-role-permissions] dry-run summary');
|
|
console.log(JSON.stringify({
|
|
mode: 'dry-run',
|
|
totalRoles: roleRows.length,
|
|
legacyRelationCount: legacyRows.length,
|
|
affectedRoleCount: updates.length,
|
|
sample: updates.slice(0, 20),
|
|
}, null, 2));
|
|
return;
|
|
}
|
|
|
|
if (updates.length === 0) {
|
|
console.log('[backfill-role-permissions] nothing to update');
|
|
return;
|
|
}
|
|
|
|
await conn.beginTransaction();
|
|
try {
|
|
for (const item of updates) {
|
|
await conn.query(
|
|
'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?',
|
|
[ item.after, item.roleId ]
|
|
);
|
|
}
|
|
await conn.commit();
|
|
} catch (error) {
|
|
await conn.rollback();
|
|
throw error;
|
|
}
|
|
|
|
console.log('[backfill-role-permissions] apply summary');
|
|
console.log(JSON.stringify({
|
|
mode: 'apply',
|
|
totalRoles: roleRows.length,
|
|
legacyRelationCount: legacyRows.length,
|
|
updatedRoleCount: updates.length,
|
|
sample: updates.slice(0, 20),
|
|
}, null, 2));
|
|
} finally {
|
|
await conn.end();
|
|
}
|
|
}
|
|
|
|
main().catch(error => {
|
|
console.error('[backfill-role-permissions] failed');
|
|
console.error(error && error.stack ? error.stack : String(error));
|
|
process.exit(1);
|
|
});
|