- receiving_completed/rejected 只通知仓库收货群,不再通知货主(货主端链接不再生成) - receiving_reviewed 货主侧三级回退:货主收货群→货主售后群→仓库异常群(sendToWarehouseChannel 支持 fallbackTargets 回退链) - 新增 receiving_store_bound:收货单创建/首次绑定货主时提醒货主填写车牌号/快递单号,路由同三级回退 - qimen order.cancel 两个拦截分支仅限有运单时创建拦截工单并通知对应快递群,与正常货主发起拦截一致 - 新增 script/backfill-inbox-permissions.cjs:客服/仓库组主管员工回填 inbox 页面与 API 权限(已执行 dev 与线上)
218 lines
7.4 KiB
JavaScript
218 lines
7.4 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 回填 inbox(消息和自动回复/群列表/消息记录 + inbox.* API)权限到指定角色。
|
||
* 默认角色:客服组-主管(28)、客服组-员工(30)、仓库组-主管(26)、仓库组-员工(27)。
|
||
* permissions='*' 的全量角色自动跳过。
|
||
*
|
||
* 用法:
|
||
* node script/backfill-inbox-permissions.cjs --dry-run
|
||
* node script/backfill-inbox-permissions.cjs
|
||
* node script/backfill-inbox-permissions.cjs --role-ids=28,30
|
||
*/
|
||
|
||
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');
|
||
const DEFAULT_ROLE_IDS = [ 28, 30, 26, 27 ];
|
||
// inbox 全部权限:页面 492/493/494 + API 491、495~503、531
|
||
const INBOX_PERMISSION_IDS = [
|
||
491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 531,
|
||
];
|
||
|
||
function parseArgs(argv) {
|
||
const args = {
|
||
dryRun: false,
|
||
roleIds: DEFAULT_ROLE_IDS,
|
||
dbClient: 'wms',
|
||
configPath: DEFAULT_CONFIG_PATH,
|
||
};
|
||
|
||
for (const item of argv) {
|
||
if (item === '--dry-run') {
|
||
args.dryRun = true;
|
||
continue;
|
||
}
|
||
if (item.startsWith('--role-ids=')) {
|
||
args.roleIds = String(item.split('=')[1] || '')
|
||
.split(',')
|
||
.map(id => Number(id.trim()))
|
||
.filter(id => Number.isFinite(id) && id > 0);
|
||
continue;
|
||
}
|
||
if (item.startsWith('--db-client=')) {
|
||
args.dbClient = String(item.split('=')[1] || '').trim() || 'wms';
|
||
continue;
|
||
}
|
||
if (item.startsWith('--config-path=')) {
|
||
args.configPath = path.resolve(ROOT, String(item.split('=')[1] || '').trim());
|
||
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-inbox-permissions-backfill' })
|
||
: configFactory;
|
||
}
|
||
|
||
function normalizeRolePermissions(rawValue) {
|
||
if (rawValue === undefined || rawValue === null) {
|
||
return { allAccess: false, permissionIds: [] };
|
||
}
|
||
if (Array.isArray(rawValue)) {
|
||
const items = rawValue.map(item => (typeof item === 'string' ? item.trim() : item));
|
||
if (items.some(item => item === '*')) {
|
||
return { allAccess: true, permissionIds: [] };
|
||
}
|
||
return {
|
||
allAccess: false,
|
||
permissionIds: Array.from(new Set(items
|
||
.map(item => Number(item))
|
||
.filter(item => Number.isFinite(item) && item > 0)
|
||
.map(item => Math.floor(item)))).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 (_) { /* 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));
|
||
if (args.roleIds.length === 0) {
|
||
throw new Error('roleIds 不能为空');
|
||
}
|
||
|
||
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, role_name, permissions FROM wms_role WHERE id IN (?) AND deleted_at IS NULL ORDER BY id ASC',
|
||
[ args.roleIds ]
|
||
);
|
||
|
||
const updates = [];
|
||
const skipped = [];
|
||
for (const row of roleRows) {
|
||
const currentState = normalizeRolePermissions(row.permissions);
|
||
if (currentState.allAccess) {
|
||
skipped.push({ id: Number(row.id), role_code: row.role_code, reason: 'all_access(*)' });
|
||
continue;
|
||
}
|
||
const nextIds = Array.from(new Set([ ...currentState.permissionIds, ...INBOX_PERMISSION_IDS ]))
|
||
.sort((a, b) => a - b);
|
||
const nextValue = JSON.stringify(nextIds);
|
||
const currentValue = serializeRolePermissions(row.permissions);
|
||
if (nextValue !== currentValue) {
|
||
const addedIds = nextIds.filter(id => !currentState.permissionIds.includes(id));
|
||
updates.push({
|
||
roleId: Number(row.id),
|
||
roleCode: row.role_code || '',
|
||
roleName: row.role_name || '',
|
||
addedCount: addedIds.length,
|
||
beforeCount: currentState.permissionIds.length,
|
||
afterCount: nextIds.length,
|
||
before: currentValue,
|
||
after: nextValue,
|
||
});
|
||
}
|
||
}
|
||
|
||
console.log(`[backfill-inbox-permissions] 目标角色=${args.roleIds.join(',')},inbox 权限=${INBOX_PERMISSION_IDS.length} 项`);
|
||
console.log(`跳过(全量标记): ${skipped.length ? JSON.stringify(skipped) : '无'}`);
|
||
|
||
if (args.dryRun) {
|
||
console.log('[dry-run] 将更新的角色:');
|
||
for (const item of updates) {
|
||
console.log(` role ${item.roleId} ${item.roleName}(${item.roleCode}): +${item.addedCount} 项 inbox 权限(${item.beforeCount} → ${item.afterCount})`);
|
||
}
|
||
if (updates.length === 0) console.log(' (无变化,所有角色已含 inbox 权限)');
|
||
return;
|
||
}
|
||
|
||
if (updates.length === 0) {
|
||
console.log('无需更新,所有目标角色已包含 inbox 权限');
|
||
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('[applied] 更新结果:');
|
||
for (const item of updates) {
|
||
console.log(` role ${item.roleId} ${item.roleName}(${item.roleCode}): ${item.beforeCount} → ${item.afterCount} 项权限`);
|
||
}
|
||
|
||
// 回读验证
|
||
const [ verifyRows ] = await conn.query(
|
||
'SELECT id, role_name, permissions FROM wms_role WHERE id IN (?) AND deleted_at IS NULL ORDER BY id ASC',
|
||
[ args.roleIds ]
|
||
);
|
||
console.log('[verify] 回读校验:');
|
||
for (const row of verifyRows) {
|
||
const state = normalizeRolePermissions(row.permissions);
|
||
const hasAllInbox = state.allAccess || INBOX_PERMISSION_IDS.every(id => state.permissionIds.includes(id));
|
||
console.log(` role ${row.id} ${row.role_name}: ${state.allAccess ? '*(全量)' : `${state.permissionIds.length} 项`},inbox 权限完整=${hasAllInbox}`);
|
||
}
|
||
} finally {
|
||
await conn.end();
|
||
}
|
||
}
|
||
|
||
main().catch(error => {
|
||
console.error('[backfill-inbox-permissions] failed:', error.message);
|
||
process.exit(1);
|
||
});
|