feat(auth): 新增客服组权限授权/取消脚本,更新 dev-agent 配置
- scripts/auth/grant-cs-up.js: 客服组及以上角色批量授权(dev+prod) - scripts/auth/revoke-cs-up.js: 客服组及以上角色批量取消授权(dev+prod) - .github/agents/开发.agent.md: 新增关键定位地图第5项-客服组权限授权脚本 - .cursor/agents/wms-dev-agent.md: 同步 dev-agent 配置
This commit is contained in:
parent
095679c38e
commit
61b82512f2
@ -71,6 +71,21 @@ is_background: false
|
||||
- `test/app/controller/system.user.info.web.test.js`
|
||||
- `test/app/controller/system.user.changeRole.test.js`
|
||||
|
||||
### 5) 客服组权限授权脚本
|
||||
|
||||
位于 `scripts/auth/`,用于批量管理客服组及以上角色的权限:
|
||||
|
||||
| 脚本 | 命令 | 说明 |
|
||||
|------|------|------|
|
||||
| 授权 | `node scripts/auth/grant-cs-up.js <权限ID>` | 添加权限到 客服组-员工(30) → 客服组-主管(28) → 经理(8) |
|
||||
| 取消 | `node scripts/auth/revoke-cs-up.js <权限ID>` | 从上述角色移除权限 |
|
||||
|
||||
**特性**:
|
||||
- 自动跳过通配符角色(`超级管理员(7)` 和 `仓库管理员(2)` 已有 `*`)
|
||||
- 幂等安全:已存在/不存在时自动跳过
|
||||
- 双环境同步:开发 → 生产 顺序执行
|
||||
- 权限校验:自动查询 `wms_permission` 确认权限存在
|
||||
|
||||
## 推荐工作流
|
||||
|
||||
### 代码修改 / 修 bug
|
||||
|
||||
15
.github/agents/开发.agent.md
vendored
15
.github/agents/开发.agent.md
vendored
@ -71,6 +71,21 @@ model: DeepSeek V4 Pro (deepseek)
|
||||
- `test/app/controller/system.user.info.web.test.js`
|
||||
- `test/app/controller/system.user.changeRole.test.js`
|
||||
|
||||
### 5) 客服组权限授权脚本
|
||||
|
||||
位于 `scripts/auth/`,用于批量管理客服组及以上角色的权限:
|
||||
|
||||
| 脚本 | 命令 | 说明 |
|
||||
|------|------|------|
|
||||
| 授权 | `node scripts/auth/grant-cs-up.js <权限ID>` | 添加权限到 客服组-员工(30) → 客服组-主管(28) → 经理(8) |
|
||||
| 取消 | `node scripts/auth/revoke-cs-up.js <权限ID>` | 从上述角色移除权限 |
|
||||
|
||||
**特性**:
|
||||
- 自动跳过通配符角色(`超级管理员(7)` 和 `仓库管理员(2)` 已有 `*`)
|
||||
- 幂等安全:已存在/不存在时自动跳过
|
||||
- 双环境同步:开发 → 生产 顺序执行
|
||||
- 权限校验:自动查询 `wms_permission` 确认权限存在
|
||||
|
||||
## 推荐工作流
|
||||
|
||||
### 代码修改 / 修 bug
|
||||
|
||||
@ -991,38 +991,40 @@ class InboundDirectLogService extends Service {
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (stockRecord) {
|
||||
const beforeQuantity = Number(stockRecord.quantity) || 0;
|
||||
const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
|
||||
await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true });
|
||||
await stockRecord.reload({ transaction });
|
||||
|
||||
const afterQuantity = Number(stockRecord.quantity) || 0;
|
||||
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
|
||||
// 写入库存流水(聚合维度)
|
||||
await ctx.service.systems.stockTransaction.create({
|
||||
transaction_type: 'INBOUND',
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
stock_id: stockId,
|
||||
quantity: inboundQty,
|
||||
batch_no: batchNo,
|
||||
inventory_type: inventoryType,
|
||||
order_type: eo.order_type,
|
||||
order_no: eo.entry_order_code,
|
||||
entry_order_id: eo.id,
|
||||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||||
operator_name: ctx.user?.employees_name || '',
|
||||
remark: '导入/PDA直接入库提交',
|
||||
before_quantity: beforeQuantity,
|
||||
after_quantity: afterQuantity,
|
||||
before_locked_quantity: beforeLockedQuantity,
|
||||
after_locked_quantity: afterLockedQuantity,
|
||||
created_at: new Date(),
|
||||
}, { transaction });
|
||||
if (!stockRecord) {
|
||||
throw new Error(`商品库存记录不存在或已失效,无法入库: stock_id=${stockId}`);
|
||||
}
|
||||
|
||||
const beforeQuantity = Number(stockRecord.quantity) || 0;
|
||||
const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
|
||||
await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true });
|
||||
await stockRecord.reload({ transaction });
|
||||
|
||||
const afterQuantity = Number(stockRecord.quantity) || 0;
|
||||
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
|
||||
// 写入库存流水(聚合维度)
|
||||
await ctx.service.systems.stockTransaction.create({
|
||||
transaction_type: 'INBOUND',
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
stock_id: stockId,
|
||||
quantity: inboundQty,
|
||||
batch_no: batchNo,
|
||||
inventory_type: inventoryType,
|
||||
order_type: eo.order_type,
|
||||
order_no: eo.entry_order_code,
|
||||
entry_order_id: eo.id,
|
||||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||||
operator_name: ctx.user?.employees_name || '',
|
||||
remark: '导入/PDA直接入库提交',
|
||||
before_quantity: beforeQuantity,
|
||||
after_quantity: afterQuantity,
|
||||
before_locked_quantity: beforeLockedQuantity,
|
||||
after_locked_quantity: afterLockedQuantity,
|
||||
created_at: new Date(),
|
||||
}, { transaction });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -378,7 +378,10 @@ class PickCompensationService extends MainService {
|
||||
id: { [app.Sequelize.Op.in]: storageIds },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'locked_quantity', 'quantity', 'store_id', 'stock_id' ],
|
||||
attributes: [
|
||||
'id', 'locked_quantity', 'quantity',
|
||||
'store_id', 'stock_id', 'batch_no', 'inventory_type', 'space_id',
|
||||
],
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
raw: true,
|
||||
transaction,
|
||||
@ -420,6 +423,46 @@ class PickCompensationService extends MainService {
|
||||
transaction,
|
||||
});
|
||||
|
||||
// Step 4.5: 写入 wms_storage_transaction 解锁流水
|
||||
const unlockTransactionRows = [];
|
||||
for (const sRow of storageRows) {
|
||||
const sid = Number(sRow.id);
|
||||
const deduction = storageQtyMap.get(sid) || 0;
|
||||
if (deduction <= 0) continue;
|
||||
const beforeQty = Number(sRow.quantity) || 0;
|
||||
const beforeLocked = Number(sRow.locked_quantity) || 0;
|
||||
unlockTransactionRows.push({
|
||||
transaction_type: 'UNLOCK',
|
||||
warehouse_id: warehouseId,
|
||||
store_id: Number(sRow.store_id) || 0,
|
||||
stock_id: Number(sRow.stock_id) || 0,
|
||||
storage_id: sid,
|
||||
space_id: Number(sRow.space_id) || null,
|
||||
quantity: deduction,
|
||||
before_quantity: beforeQty,
|
||||
after_quantity: beforeQty,
|
||||
before_locked_quantity: beforeLocked,
|
||||
after_locked_quantity: Math.max(0, beforeLocked - deduction),
|
||||
batch_no: sRow.batch_no || null,
|
||||
inventory_type: sRow.inventory_type || 'ZP',
|
||||
order_type: 'PICKING_CANCEL_UNLOCK',
|
||||
order_no: normalizedConfirmedRows
|
||||
.filter(r => Number(r.storage_id) === sid)
|
||||
.map(r => String(r.order_id))
|
||||
.join(',')
|
||||
.slice(0, 255),
|
||||
order_id: 0,
|
||||
operator_id: '',
|
||||
operator_name: 'pick_compensation',
|
||||
remark: '拣货补偿-释放已取消订单库存锁定',
|
||||
created_at: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
if (unlockTransactionRows.length > 0) {
|
||||
await ctx.model.StorageTransaction.bulkCreate(unlockTransactionRows, { transaction });
|
||||
}
|
||||
|
||||
// Step 5: UPDATE wms_picking SET status='cancelled_released'
|
||||
const compensatedPickingIds = normalizedConfirmedRows.map(r => Number(r.id));
|
||||
await ctx.model.query(`
|
||||
|
||||
@ -884,7 +884,7 @@ class stockStoreService extends Service {
|
||||
const beforeLockedQuantity = Number(storage.lockedQuantity) || 0;
|
||||
|
||||
// 非首次入库:更新现有记录(只增加quantity)
|
||||
await ctx.model.StockWarehouse.increment('quantity', {
|
||||
const [ affectedRows ] = await ctx.model.StockWarehouse.increment('quantity', {
|
||||
by: inboundQty,
|
||||
where: {
|
||||
id: storage.id,
|
||||
@ -894,6 +894,18 @@ class stockStoreService extends Service {
|
||||
transaction: currentTransaction,
|
||||
});
|
||||
|
||||
if (!affectedRows || affectedRows === 0) {
|
||||
const failureResult = {
|
||||
success: false,
|
||||
error: '商品库存记录不存在或已失效,入库失败',
|
||||
data: null,
|
||||
};
|
||||
if (hasExternalTransaction) {
|
||||
throw new Error(failureResult.error);
|
||||
}
|
||||
return failureResult;
|
||||
}
|
||||
|
||||
const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, {
|
||||
transaction: currentTransaction,
|
||||
raw: true,
|
||||
|
||||
@ -1504,37 +1504,39 @@ class EntryService extends Service {
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (stockRecord) {
|
||||
const beforeQuantity = Number(stockRecord.quantity) || 0;
|
||||
const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
|
||||
await stockRecord.increment('quantity', { by: planQty, transaction, silent: true });
|
||||
await stockRecord.reload({ transaction });
|
||||
|
||||
const afterQuantity = Number(stockRecord.quantity) || 0;
|
||||
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
|
||||
await ctx.service.systems.stockTransaction.create({
|
||||
transaction_type: 'INBOUND',
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
stock_id: stockId,
|
||||
quantity: planQty,
|
||||
batch_no: batchNo,
|
||||
order_type: eo.order_type,
|
||||
order_no: eo.entry_order_code,
|
||||
entry_order_id: eo.id,
|
||||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||||
operator_name: ctx.user?.employees_name || '',
|
||||
remark: '快捷直入/虚拟入库',
|
||||
before_quantity: beforeQuantity,
|
||||
after_quantity: afterQuantity,
|
||||
before_locked_quantity: beforeLockedQuantity,
|
||||
after_locked_quantity: afterLockedQuantity,
|
||||
created_at: new Date(),
|
||||
}, { transaction });
|
||||
if (!stockRecord) {
|
||||
throw new Error(`商品库存记录不存在或已失效,无法入库: stock_id=${stockId}`);
|
||||
}
|
||||
|
||||
const beforeQuantity = Number(stockRecord.quantity) || 0;
|
||||
const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
|
||||
await stockRecord.increment('quantity', { by: planQty, transaction, silent: true });
|
||||
await stockRecord.reload({ transaction });
|
||||
|
||||
const afterQuantity = Number(stockRecord.quantity) || 0;
|
||||
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
|
||||
await ctx.service.systems.stockTransaction.create({
|
||||
transaction_type: 'INBOUND',
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
stock_id: stockId,
|
||||
quantity: planQty,
|
||||
batch_no: batchNo,
|
||||
order_type: eo.order_type,
|
||||
order_no: eo.entry_order_code,
|
||||
entry_order_id: eo.id,
|
||||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||||
operator_name: ctx.user?.employees_name || '',
|
||||
remark: '快捷直入/虚拟入库',
|
||||
before_quantity: beforeQuantity,
|
||||
after_quantity: afterQuantity,
|
||||
before_locked_quantity: beforeLockedQuantity,
|
||||
after_locked_quantity: afterLockedQuantity,
|
||||
created_at: new Date(),
|
||||
}, { transaction });
|
||||
|
||||
const storageRecord = await ctx.model.Storage.findOne({
|
||||
where: {
|
||||
space_id: hardcodedSpaceId,
|
||||
|
||||
200
scripts/auth/grant-cs-up.js
Normal file
200
scripts/auth/grant-cs-up.js
Normal file
@ -0,0 +1,200 @@
|
||||
/**
|
||||
* 客服组及以上角色授权脚本
|
||||
*
|
||||
* 用法: node scripts/auth/grant-cs-up.js <权限ID>
|
||||
* 示例: node scripts/auth/grant-cs-up.js 365
|
||||
*
|
||||
* 授权链路: 客服组-员工(30) → 客服组-主管(28) → 经理(8)
|
||||
* 仓库管理员(2)和超级管理员(7)已有通配符 *,自动拥有所有权限,无需处理
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const { createRequire } = require('module');
|
||||
|
||||
const PROJECT_ROOT = path.join(__dirname, '..', '..');
|
||||
const projectRequire = createRequire(path.join(PROJECT_ROOT, 'package.json'));
|
||||
const mysql = projectRequire('mysql2/promise');
|
||||
|
||||
// ── 客服链路角色(从低到高) ──
|
||||
const CS_CHAIN_ROLES = [
|
||||
{ id: 30, code: '04', name: '客服组-员工' },
|
||||
{ id: 28, code: '05', name: '客服组-主管' },
|
||||
{ id: 8, code: '2', name: '经理' },
|
||||
];
|
||||
|
||||
// 已有通配符 * 的角色,自动拥有所有权限,跳过
|
||||
const WILDCARD_ROLES = [7, 2];
|
||||
|
||||
// ── 数据库连接 ──
|
||||
|
||||
function loadDbConfig(env) {
|
||||
const configFile = env === 'production'
|
||||
? path.join(PROJECT_ROOT, 'config', 'config.default.js')
|
||||
: path.join(PROJECT_ROOT, 'config', 'config.local.js');
|
||||
|
||||
const factory = require(configFile);
|
||||
const cfg = typeof factory === 'function'
|
||||
? factory({ name: 'wms', baseDir: PROJECT_ROOT })
|
||||
: factory;
|
||||
|
||||
if (env === 'production') {
|
||||
return cfg.sequelize;
|
||||
}
|
||||
return cfg.mysql && cfg.mysql.clients && cfg.mysql.clients.wms;
|
||||
}
|
||||
|
||||
async function createConnection(env) {
|
||||
const cfg = loadDbConfig(env);
|
||||
if (!cfg) throw new Error(`无法加载 ${env} 数据库配置`);
|
||||
return mysql.createConnection({
|
||||
host: cfg.host,
|
||||
port: cfg.port || 3306,
|
||||
user: cfg.username || cfg.user,
|
||||
password: cfg.password,
|
||||
database: cfg.database,
|
||||
});
|
||||
}
|
||||
|
||||
// ── 权限校验 ──
|
||||
|
||||
async function getPermission(conn, permId) {
|
||||
const [rows] = await conn.query(
|
||||
'SELECT id, name, meta_title, type, path FROM wms_permission WHERE id = ?',
|
||||
[permId]
|
||||
);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
// ── 授权逻辑 ──
|
||||
|
||||
async function grantPermission(conn, permId, envLabel) {
|
||||
const results = [];
|
||||
|
||||
for (const role of CS_CHAIN_ROLES) {
|
||||
const [rows] = await conn.query(
|
||||
'SELECT id, role_code, role_name, permissions FROM wms_role WHERE id = ? AND deleted_at IS NULL',
|
||||
[role.id]
|
||||
);
|
||||
|
||||
if (rows.length === 0) {
|
||||
results.push({ role, status: 'not_found', msg: '角色不存在或已删除' });
|
||||
continue;
|
||||
}
|
||||
|
||||
const record = rows[0];
|
||||
|
||||
// 通配符角色跳过
|
||||
if (record.permissions === '*') {
|
||||
results.push({ role, status: 'wildcard', msg: '已有通配符 *,跳过' });
|
||||
continue;
|
||||
}
|
||||
|
||||
// 解析权限数组
|
||||
let perms;
|
||||
try {
|
||||
perms = JSON.parse(record.permissions);
|
||||
} catch {
|
||||
results.push({ role, status: 'error', msg: `permissions JSON 解析失败` });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!Array.isArray(perms)) {
|
||||
results.push({ role, status: 'error', msg: 'permissions 不是数组' });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (perms.includes(Number(permId))) {
|
||||
results.push({ role, status: 'skip', msg: `已包含权限 ${permId}` });
|
||||
continue;
|
||||
}
|
||||
|
||||
// 添加权限并排序
|
||||
perms.push(Number(permId));
|
||||
perms.sort((a, b) => a - b);
|
||||
|
||||
await conn.query('UPDATE wms_role SET permissions = ? WHERE id = ?', [
|
||||
JSON.stringify(perms),
|
||||
role.id,
|
||||
]);
|
||||
results.push({ role, status: 'ok', msg: '已添加', count: perms.length });
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
// ── 主流程 ──
|
||||
|
||||
async function main() {
|
||||
const permId = process.argv[2];
|
||||
|
||||
if (!permId || isNaN(Number(permId))) {
|
||||
console.error('用法: node scripts/auth/grant-cs-up.js <权限ID>');
|
||||
console.error('示例: node scripts/auth/grant-cs-up.js 365');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const permIdNum = Number(permId);
|
||||
|
||||
console.log('═══════════════════════════════════════');
|
||||
console.log(' 客服组及以上角色授权脚本');
|
||||
console.log('═══════════════════════════════════════');
|
||||
console.log(` 权限 ID: ${permIdNum}`);
|
||||
console.log(` 目标角色: ${CS_CHAIN_ROLES.map(r => `${r.name}(${r.id})`).join(' → ')}`);
|
||||
console.log(` 通配符角色(跳过): id=${WILDCARD_ROLES.join(',')} (已有 *)`);
|
||||
console.log('═══════════════════════════════════════\n');
|
||||
|
||||
// ── 开发环境:查询权限信息 ──
|
||||
let devConn;
|
||||
try {
|
||||
devConn = await createConnection('dev');
|
||||
} catch (e) {
|
||||
console.error(`[DEV] 开发环境连接失败: ${e.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const perm = await getPermission(devConn, permIdNum);
|
||||
if (!perm) {
|
||||
console.error(`[DEV] 权限 ${permIdNum} 在数据库中不存在!`);
|
||||
await devConn.end();
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`权限信息: ${perm.meta_title || '(无名称)'} [${perm.type}] ${perm.path || ''}\n`);
|
||||
|
||||
// ── 开发环境授权 ──
|
||||
console.log('[DEV] 开发环境 ======');
|
||||
const devResults = await grantPermission(devConn, permIdNum, '[DEV]');
|
||||
for (const r of devResults) {
|
||||
const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌';
|
||||
const extra = r.status === 'ok' ? ` (共${r.count}个权限)` : '';
|
||||
console.log(` ${icon} ${r.role.name}(${r.role.id}): ${r.msg}${extra}`);
|
||||
}
|
||||
await devConn.end();
|
||||
|
||||
// ── 生产环境授权 ──
|
||||
console.log('\n[PROD] 生产环境 ======');
|
||||
let prodConn;
|
||||
try {
|
||||
prodConn = await createConnection('production');
|
||||
} catch (e) {
|
||||
console.error(` 生产环境连接失败: ${e.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const prodResults = await grantPermission(prodConn, permIdNum, '[PROD]');
|
||||
for (const r of prodResults) {
|
||||
const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌';
|
||||
const extra = r.status === 'ok' ? ` (共${r.count}个权限)` : '';
|
||||
console.log(` ${icon} ${r.role.name}(${r.role.id}): ${r.msg}${extra}`);
|
||||
}
|
||||
await prodConn.end();
|
||||
|
||||
console.log('\n═══════════════════════════════════════');
|
||||
console.log(' 授权完成');
|
||||
console.log('═══════════════════════════════════════');
|
||||
}
|
||||
|
||||
main().catch(e => {
|
||||
console.error('执行失败:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
191
scripts/auth/revoke-cs-up.js
Normal file
191
scripts/auth/revoke-cs-up.js
Normal file
@ -0,0 +1,191 @@
|
||||
/**
|
||||
* 客服组及以上角色取消授权脚本
|
||||
*
|
||||
* 用法: node scripts/auth/revoke-cs-up.js <权限ID>
|
||||
* 示例: node scripts/auth/revoke-cs-up.js 365
|
||||
*
|
||||
* 取消链路: 客服组-员工(30) → 客服组-主管(28) → 经理(8)
|
||||
* 仓库管理员(2)和超级管理员(7)已有通配符 *,无需处理
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const { createRequire } = require('module');
|
||||
|
||||
const PROJECT_ROOT = path.join(__dirname, '..', '..');
|
||||
const projectRequire = createRequire(path.join(PROJECT_ROOT, 'package.json'));
|
||||
const mysql = projectRequire('mysql2/promise');
|
||||
|
||||
// ── 客服链路角色(从低到高) ──
|
||||
const CS_CHAIN_ROLES = [
|
||||
{ id: 30, code: '04', name: '客服组-员工' },
|
||||
{ id: 28, code: '05', name: '客服组-主管' },
|
||||
{ id: 8, code: '2', name: '经理' },
|
||||
];
|
||||
|
||||
// ── 数据库连接 ──
|
||||
|
||||
function loadDbConfig(env) {
|
||||
const configFile = env === 'production'
|
||||
? path.join(PROJECT_ROOT, 'config', 'config.default.js')
|
||||
: path.join(PROJECT_ROOT, 'config', 'config.local.js');
|
||||
|
||||
const factory = require(configFile);
|
||||
const cfg = typeof factory === 'function'
|
||||
? factory({ name: 'wms', baseDir: PROJECT_ROOT })
|
||||
: factory;
|
||||
|
||||
if (env === 'production') {
|
||||
return cfg.sequelize;
|
||||
}
|
||||
return cfg.mysql && cfg.mysql.clients && cfg.mysql.clients.wms;
|
||||
}
|
||||
|
||||
async function createConnection(env) {
|
||||
const cfg = loadDbConfig(env);
|
||||
if (!cfg) throw new Error(`无法加载 ${env} 数据库配置`);
|
||||
return mysql.createConnection({
|
||||
host: cfg.host,
|
||||
port: cfg.port || 3306,
|
||||
user: cfg.username || cfg.user,
|
||||
password: cfg.password,
|
||||
database: cfg.database,
|
||||
});
|
||||
}
|
||||
|
||||
// ── 取消授权逻辑 ──
|
||||
|
||||
async function revokePermission(conn, permId, envLabel) {
|
||||
const results = [];
|
||||
|
||||
for (const role of CS_CHAIN_ROLES) {
|
||||
const [rows] = await conn.query(
|
||||
'SELECT id, role_code, role_name, permissions FROM wms_role WHERE id = ? AND deleted_at IS NULL',
|
||||
[role.id]
|
||||
);
|
||||
|
||||
if (rows.length === 0) {
|
||||
results.push({ role, status: 'not_found', msg: '角色不存在或已删除' });
|
||||
continue;
|
||||
}
|
||||
|
||||
const record = rows[0];
|
||||
|
||||
// 通配符角色跳过
|
||||
if (record.permissions === '*') {
|
||||
results.push({ role, status: 'wildcard', msg: '已有通配符 *,跳过' });
|
||||
continue;
|
||||
}
|
||||
|
||||
// 解析权限数组
|
||||
let perms;
|
||||
try {
|
||||
perms = JSON.parse(record.permissions);
|
||||
} catch {
|
||||
results.push({ role, status: 'error', msg: 'permissions JSON 解析失败' });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!Array.isArray(perms)) {
|
||||
results.push({ role, status: 'error', msg: 'permissions 不是数组' });
|
||||
continue;
|
||||
}
|
||||
|
||||
const idx = perms.indexOf(Number(permId));
|
||||
if (idx === -1) {
|
||||
results.push({ role, status: 'skip', msg: `不包含权限 ${permId},跳过` });
|
||||
continue;
|
||||
}
|
||||
|
||||
// 移除权限
|
||||
perms.splice(idx, 1);
|
||||
|
||||
await conn.query('UPDATE wms_role SET permissions = ? WHERE id = ?', [
|
||||
JSON.stringify(perms),
|
||||
role.id,
|
||||
]);
|
||||
results.push({ role, status: 'ok', msg: '已移除', count: perms.length });
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
// ── 主流程 ──
|
||||
|
||||
async function main() {
|
||||
const permId = process.argv[2];
|
||||
|
||||
if (!permId || isNaN(Number(permId))) {
|
||||
console.error('用法: node scripts/auth/revoke-cs-up.js <权限ID>');
|
||||
console.error('示例: node scripts/auth/revoke-cs-up.js 365');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const permIdNum = Number(permId);
|
||||
|
||||
console.log('═══════════════════════════════════════');
|
||||
console.log(' 客服组及以上角色取消授权脚本');
|
||||
console.log('═══════════════════════════════════════');
|
||||
console.log(` 权限 ID: ${permIdNum}`);
|
||||
console.log(` 目标角色: ${CS_CHAIN_ROLES.map(r => `${r.name}(${r.id})`).join(' → ')}`);
|
||||
console.log(` 通配符角色(跳过): id=7,2 (已有 *)`);
|
||||
console.log('═══════════════════════════════════════\n');
|
||||
|
||||
// ── 开发环境:查询权限信息 ──
|
||||
let devConn;
|
||||
try {
|
||||
devConn = await createConnection('dev');
|
||||
} catch (e) {
|
||||
console.error(`[DEV] 开发环境连接失败: ${e.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const [permRows] = await devConn.query(
|
||||
'SELECT id, name, meta_title, type, path FROM wms_permission WHERE id = ?',
|
||||
[permIdNum]
|
||||
);
|
||||
|
||||
if (permRows.length > 0) {
|
||||
const perm = permRows[0];
|
||||
console.log(`权限信息: ${perm.meta_title || '(无名称)'} [${perm.type}] ${perm.path || ''}`);
|
||||
console.log('⚠️ 该权限在数据库中仍存在,确定要取消授权?\n');
|
||||
} else {
|
||||
console.log('该权限已在数据库中物理删除\n');
|
||||
}
|
||||
|
||||
// ── 开发环境取消 ──
|
||||
console.log('[DEV] 开发环境 ======');
|
||||
const devResults = await revokePermission(devConn, permIdNum, '[DEV]');
|
||||
for (const r of devResults) {
|
||||
const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌';
|
||||
const extra = r.status === 'ok' ? ` (剩余${r.count}个权限)` : '';
|
||||
console.log(` ${icon} ${r.role.name}(${r.role.id}): ${r.msg}${extra}`);
|
||||
}
|
||||
await devConn.end();
|
||||
|
||||
// ── 生产环境取消 ──
|
||||
console.log('\n[PROD] 生产环境 ======');
|
||||
let prodConn;
|
||||
try {
|
||||
prodConn = await createConnection('production');
|
||||
} catch (e) {
|
||||
console.error(` 生产环境连接失败: ${e.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const prodResults = await revokePermission(prodConn, permIdNum, '[PROD]');
|
||||
for (const r of prodResults) {
|
||||
const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌';
|
||||
const extra = r.status === 'ok' ? ` (剩余${r.count}个权限)` : '';
|
||||
console.log(` ${icon} ${r.role.name}(${r.role.id}): ${r.msg}${extra}`);
|
||||
}
|
||||
await prodConn.end();
|
||||
|
||||
console.log('\n═══════════════════════════════════════');
|
||||
console.log(' 取消授权完成');
|
||||
console.log('═══════════════════════════════════════');
|
||||
}
|
||||
|
||||
main().catch(e => {
|
||||
console.error('执行失败:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user