diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js index a94a799..86f6c8d 100644 --- a/app/model/notification_webhook.js +++ b/app/model/notification_webhook.js @@ -41,6 +41,7 @@ module.exports = app => { Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }), Object.freeze({ code: 'receiving_rejected', name: '收货驳回', business: 'receiving', description: '收货单被驳回并恢复为收货中后的通知' }), Object.freeze({ code: 'receiving_reviewed', name: '收货审核完成', business: 'receiving', description: '收货单批量审核通过后的通知' }), + Object.freeze({ code: 'receiving_store_bound', name: '收货单创建/绑定货主', business: 'receiving', description: '收货单创建或首次绑定货主时提醒货主填写车牌号/快递号的通知' }), Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }), Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }), Object.freeze({ code: 'wave_strategy_quick_scan_failed', name: '波次策略兜底扫描失败', business: 'order', description: '定时兜底扫描任务在仓库维度触发失败时通知' }), diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index ab162cd..570c7ee 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -228,13 +228,16 @@ class orderServer extends MainService { ctx.logger.warn('[QimenOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr); } - // 创建售后工单 + 通知快递群(失败不影响主流程) + // 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程) try { - await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ - orderIds: [ existingOrder.id ], - warehouseId: info.warehouseId, - creatorLabel: ctx.user?.employees_name || '奇门系统', - }); + const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id); + if (Array.isArray(interceptExpress) && interceptExpress.length > 0) { + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ existingOrder.id ], + warehouseId: info.warehouseId, + creatorLabel: ctx.user?.employees_name || '奇门系统', + }); + } } catch (workOrderErr) { ctx.logger.warn( `[qimen order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}` @@ -272,6 +275,23 @@ class orderServer extends MainService { } await transaction.commit(); + + // 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程) + try { + const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id); + if (Array.isArray(interceptExpress) && interceptExpress.length > 0) { + await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ + orderIds: [ existingOrder.id ], + warehouseId: info.warehouseId, + creatorLabel: ctx.user?.employees_name || '奇门系统', + }); + } + } catch (workOrderErr) { + ctx.logger.warn( + `[qimen order cancel] 创建工单/通知失败(sync), orderId=${existingOrder.id}, error=${workOrderErr.message}` + ); + } + await this.sendCancelInterceptNotice({ orderCode, existingOrder, diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index b0f608f..269d58f 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -24,6 +24,9 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ 'all', '*', 'receiving_completed', + 'receiving_rejected', + 'receiving_reviewed', + 'receiving_store_bound', 'order_cancel_intercepted', 'wave_strategy_quick_scan_failed', 'store_warehouse_print_quantity_adjusted', @@ -37,15 +40,28 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ const FIXED_GROUP_SUBSCRIPTIONS = Object.freeze({ receiving_completed: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), - Object.freeze({ groupType: 'store', subType: 'receiving' }), ]), receiving_rejected: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), - Object.freeze({ groupType: 'store', subType: 'receiving' }), ]), receiving_reviewed: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), - Object.freeze({ groupType: 'store', subType: 'receiving' }), + Object.freeze({ + groupType: 'store', + subType: 'receiving', + fallbackTargets: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'after_sales' }), + ]), + }), + ]), + receiving_store_bound: Object.freeze([ + Object.freeze({ + groupType: 'store', + subType: 'receiving', + fallbackTargets: Object.freeze([ + Object.freeze({ groupType: 'store', subType: 'after_sales' }), + ]), + }), ]), order_cancel_intercepted: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'exception' }), @@ -1001,8 +1017,6 @@ class NoticeService extends Service { }; } - const groups = await this.findSubscribedGroups(payload); - // 货主目标群未配置时,降级发送到仓库异常群,内容前缀标记失败 const fixedTargets = this.getFixedGroupTargets(payload.event) || []; const hasStoreTarget = fixedTargets.some( @@ -1020,10 +1034,60 @@ class NoticeService extends Service { : Number(storeInfo.authStatus); const storeContractInactive = warehouseUseStatus === 0 || (authStatus !== null && authStatus !== 2); + // 主目标查询(store 目标的 fallbackTargets 不参与主查询,避免主目标命中时 fallback 群也被推送) + const primaryTargets = fixedTargets + .map(target => ({ + groupType: String(target && target.groupType || '').trim().toLowerCase(), + subType: String(target && target.subType || '').trim(), + })) + .filter(target => target.groupType); + const groups = await this.findSubscribedGroups(payload, primaryTargets); + const effectiveGroups = storeContractInactive ? groups.filter(group => group && group.group_type !== 'store') : groups; - const storeGroupMatched = effectiveGroups.some(group => group && group.group_type === 'store'); + + // store 目标回退链:主目标(如 store:receiving)未命中时,按 fallbackTargets 顺序逐级尝试(如 store:after_sales) + const storeChains = fixedTargets.filter( + target => String(target && target.groupType || '').trim().toLowerCase() === 'store' + ); + const extraStoreGroups = []; + let storeChainMatchedCount = 0; + + if (!storeContractInactive) { + for (const chain of storeChains) { + const chainSubType = String(chain.subType || '').trim(); + const primaryMatched = effectiveGroups.some( + group => group && group.group_type === 'store' && (!chainSubType || String(group.sub_type || '').trim() === chainSubType) + ); + if (primaryMatched) { + storeChainMatchedCount += 1; + continue; + } + + const fallbackTargets = Array.isArray(chain.fallbackTargets) ? chain.fallbackTargets : []; + let chainMatched = false; + for (const fallbackTarget of fallbackTargets) { + const fallbackGroups = await this.findSubscribedGroups(payload, [ fallbackTarget ]); + if (fallbackGroups.length > 0) { + for (const fallbackGroup of fallbackGroups) { + extraStoreGroups.push(fallbackGroup); + } + chainMatched = true; + break; + } + } + if (chainMatched) { + storeChainMatchedCount += 1; + } + } + } + + const mergedGroups = [ ...effectiveGroups, ...extraStoreGroups ]; + const effectiveGroupsFinal = mergedGroups.filter( + (group, index) => mergedGroups.findIndex(item => item.group_id === group.group_id) === index + ); + const storeGroupMatched = storeChains.length === 0 || storeChainMatchedCount >= storeChains.length; let fallbackGroups = []; let storeLabel = '货主'; @@ -1032,7 +1096,7 @@ class NoticeService extends Service { const exceptionGroups = await this.findSubscribedGroups(payload, [ { groupType: 'warehouse', subType: 'exception' }, ]); - const matchedGroupIds = new Set(effectiveGroups.map(group => group.group_id)); + const matchedGroupIds = new Set(effectiveGroupsFinal.map(group => group.group_id)); fallbackGroups = exceptionGroups.filter(group => !matchedGroupIds.has(group.group_id)); if (fallbackGroups.length > 0) { @@ -1047,7 +1111,7 @@ class NoticeService extends Service { } } - const pushGroups = [ ...effectiveGroups, ...fallbackGroups ]; + const pushGroups = [ ...effectiveGroupsFinal, ...fallbackGroups ]; if (pushGroups.length === 0) { ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 未匹配到订阅群', { traceId: payload.traceId, diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index e7c7398..74944b3 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1017,7 +1017,7 @@ class ReceivingService extends Service { `收货单ID:${item.id || ''}`, `收货单号:${item.receiving_number || '无'}`, `收货创建人:${item.creator && item.creator.name || '无'}`, - '请及时处理重新提交完成收货。', + '请及时处理重新提交完成收货', ].join('\n') + '。', businessId: item.id || ids[0], subject: { @@ -1493,6 +1493,72 @@ class ReceivingService extends Service { ]; } + /** + * 发送收货单创建/首次绑定货主通知(receiving_store_bound),提醒货主填写车牌号/快递单号。 + * 路由由 notice 固定订阅回退链处理:货主收货群 → 无则货主售后群 → 均无则仓库异常群。 + * @param {Object} options 发送参数 + * @param {Object} options.receiving 收货单快照 + * @param {string|null} [options.storeName=null] 货主名称(优先用合约备注) + * @return {Promise} 发送结果 + */ + async sendStoreBoundNotice({ receiving, storeName = null } = {}) { + const { ctx } = this; + const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function' + ? rawNoticeService + : (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function' + ? rawNoticeService.index + : null); + + if (!receiving || !noticeService) return null; + + const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0); + const storeId = Number(receiving.store_id || 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0 || !Number.isFinite(storeId) || storeId <= 0) { + return null; + } + + const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim(); + const storeLabel = String(storeName || receiving.store_name || '').trim() || '货主'; + const storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim(); + + const contentLines = [ + `收货单号:${receivingNumber} 正在收货`, + `货主:${storeLabel}`, + '请确认是否已填写车牌号或快递单号,未填写请及时补充', + ]; + const content = [ ...contentLines ].join('\n') + '。'; + const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。'; + + return await noticeService.send({ + warehouseId, + storeId, + messageType: 'text', + businessName: 'receiving', + event: 'receiving_store_bound', + channel: 'warehouse', + title: `收货单${receivingNumber}正在收货`, + content, + storeContent, + businessId: receiving.id, + subject: { + id: warehouseId, + type: 'warehouse', + name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''), + }, + sender: { + id: (ctx.user && (ctx.user.employees_id || ctx.user.id)) || null, + name: (ctx.user && ctx.user.employees_name) || '', + }, + metadata: { + receivingId: receiving.id, + receivingNumber, + warehouseId, + storeId, + }, + }); + } + /** * 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型。 * @param {Object} options 发送参数 @@ -1985,6 +2051,23 @@ class ReceivingService extends Service { ctx.logger.warn('[receiving.create] 写入操作日志失败,不影响业务', logErr); } + // 创建时已绑定货主 → 通知货主正在收货(失败不影响主流程) + if (Number(result.store_id || 0) > 0) { + try { + await this.sendStoreBoundNotice({ + receiving: { + id: result.id, + receiving_number: result.receiving_number, + warehouse_id: result.warehouse_id, + store_id: result.store_id, + store_name: result.store_name, + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[receiving.create] 通知货主失败,不影响业务', noticeErr); + } + } + return { code: 200, id: result.id, @@ -2330,6 +2413,21 @@ class ReceivingService extends Service { ctx.logger.warn('[receiving.bindStore] 写入操作日志失败,不影响业务', logErr); } + // 首次绑定货主 → 通知货主正在收货(失败不影响主流程) + try { + await this.sendStoreBoundNotice({ + receiving: { + id: receivingId, + receiving_number: receiving.receiving_number, + warehouse_id: warehouseId, + store_id: storeId, + store_name: storeName, + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[receiving.bindStore] 通知货主失败,不影响业务', noticeErr); + } + return { code: 200, message: '绑定货主成功', @@ -3155,6 +3253,7 @@ class ReceivingService extends Service { }; // 只在有值且收货单当前没有这些值时更新 store 信息 + const firstBoundStore = !!storeId && !receiving.store_id; if (storeId && !receiving.store_id) { updateData.store_id = storeId; updateData.store_name = storeName; @@ -3174,6 +3273,23 @@ class ReceivingService extends Service { // 6. 提交事务 await transaction.commit(); + // 首次自动绑定货主 → 通知货主正在收货(失败不影响主流程) + if (firstBoundStore) { + try { + await this.sendStoreBoundNotice({ + receiving: { + id: receivingId, + receiving_number: receiving.receiving_number, + warehouse_id: warehouseId, + store_id: storeId, + store_name: storeName, + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[receiving.updateReceivingStats] 通知货主失败,不影响业务', noticeErr); + } + } + ctx.logger.info(`成功更新收货单 ${receivingId} 的统计信息`); } catch (error) { @@ -4099,9 +4215,8 @@ class ReceivingService extends Service { const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0); const title = `收货单${receivingNumber}已完成`; const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`); - // 仓库侧与货主侧前端地址/路径不同,分别拼快速查看链接 + // 收货完成只通知仓库收货群,不再通知货主(货主端链接不再生成) const warehouseFrontendUrl = String(ctx.app.config.frontendUrl || '').trim(); - const storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim(); const contentLines = [ `收货单号:${receivingNumber} 已完成`, `货主:${receiving.store_name || '未知'}`, @@ -4121,7 +4236,6 @@ class ReceivingService extends Service { `备注:${receiving.remark || '无'}`, ].filter(Boolean); const content = [ ...contentLines, `快速查看:${warehouseFrontendUrl}/storage/receiving?id=${receivingNumber}` ].join('\n') + '。'; - const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。'; return await noticeService.send({ warehouseId, @@ -4132,7 +4246,6 @@ class ReceivingService extends Service { channel: 'warehouse', title, content, - storeContent, url: reportUrl || undefined, fileName: reportUrl ? reportFileName : '', mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '', diff --git a/methods/changes/qimen.json b/methods/changes/qimen.json index 11cfe45..aa94da4 100644 --- a/methods/changes/qimen.json +++ b/methods/changes/qimen.json @@ -69,5 +69,21 @@ ], "type": "changed", "module": "stockout" + }, + { + "version": "2026.08.17-qimen-order-cancel-01", + "date": "2026-08-17", + "summary": "order.cancel 触发拦截的两个分支统一转发快递群发起拦截(创建售后工单+通知快递群),仅限有运单的订单处理", + "methods": [ + "order.cancel" + ], + "notes": [ + "已拣货/已打印分支:保留原有 createInterceptWorkOrdersAndNotify 调用,新增前置判断——先查订单运单,无运单不再创建工单/通知快递群", + "已同步订单分支(sync_status=fin):新增与分支一相同的拦截处理——有运单时创建售后工单并通知对应快递群,与正常货主发起拦截一致", + "无运单订单仍按原逻辑更新拦截状态与异常群通知,不创建工单、不通知快递群", + "createInterceptWorkOrdersAndNotify 内部本就按运单驱动(无运单直接返回),外层判断进一步避免无谓调用" + ], + "type": "changed", + "module": "order" } ] diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index 9562c5b..5f5cdff 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -147,5 +147,82 @@ "事件码 storage_transfer_completed 仍保留注册:app/schedule/notice_stock_remaining.js 库存余量每日提醒复用该事件码,固定群映射 warehouse:production 不变" ], "module": "storage" + }, + { + "version": "2026-08-17-warehouse-03", + "date": "2026-08-17", + "type": "changed", + "summary": "拦截通知无对应快递群时降级转发仓库异常群:拦截工单创建后若运单快递无售后群(或无快递接口),统一转发异常群并在内容前缀标记失败,与货主群缺失降级行为一致", + "methods": [ + "notify.reply" + ], + "notes": [ + "app/service/systems/afterSale.js createInterceptWorkOrdersAndNotify:按快递分组通知售后群时,无群/无接口的运单收集后统一推送到仓库异常群(group_type=warehouse + sub_type=exception + is_blocked=0)", + "降级内容格式:通知快递【快递名】失败\\n{快递名 运单号...}\\n拦截(前缀与货主群缺失降级的「通知货主【X】失败」一致)", + "仅成功通知快递群的工单升级 pending_feedback;降级到异常群的工单保持 pending,等待人工跟进" + ], + "module": "after_sale" + }, + { + "version": "2026-08-17-warehouse-04", + "date": "2026-08-17", + "type": "changed", + "summary": "收货完成/驳回不再通知货主:receiving_completed 与 receiving_rejected 固定订阅由「仓库收货群+货主收货群」改为仅仓库收货群,货主端快速查看链接不再生成", + "methods": [ + "notify.reply" + ], + "notes": [ + "notice/index.js FIXED_GROUP_SUBSCRIPTIONS:receiving_completed 与 receiving_rejected 均移除 store:receiving 目标,仅保留 warehouse:receiving", + "storage/receiving.js 完成通知移除 storeContent(货主侧 /storage/receiving_owner 链接),只生成仓库侧快速查看链接", + "receiving_reviewed 仍保持双群通知不变", + "e2e 用例 receiving_completed / receiving_rejected expectGroups 调整为仅 g_wh_receiving_debug_001" + ], + "module": "receiving" + }, + { + "version": "2026-08-17-warehouse-05", + "date": "2026-08-17", + "type": "changed", + "summary": "收货审核通知货主群三级回退:审核明细文件优先推货主收货群,无收货群推货主售后群,均无则降级仓库异常群", + "methods": [ + "notify.reply" + ], + "notes": [ + "FIXED_GROUP_SUBSCRIPTIONS.receiving_reviewed 的 store 目标新增 fallbackTargets(store:after_sales),主目标查询时 fallback 不参与,命中主目标则不推 fallback 群", + "sendToWarehouseChannel 支持 store 目标回退链:主目标未匹配时按 fallbackTargets 顺序逐级查找,命中即停止并视为货主群推送(使用 storeContent/storeId 关联)", + "回退链全部未匹配时沿用原有异常群降级(前缀「通知货主【X】失败」)", + "e2e 新增 receiving_reviewed_fallback_after_sales(货主 1000241,无收货群→售后群)与 receiving_reviewed_fallback_exception(货主 1000282,无收货群无售后群→异常群)两个用例" + ], + "module": "receiving" + }, + { + "version": "2026-08-17-warehouse-06", + "date": "2026-08-17", + "type": "added", + "summary": "新增收货单创建/首次绑定货主通知(receiving_store_bound):提醒货主收货进行中并确认车牌号/快递单号,路由与审核一致(货主收货群→售后群→异常群)", + "methods": [ + "notify.reply" + ], + "notes": [ + "新事件码 receiving_store_bound 注册(notification_webhook.js AVAILABLE_EVENTS 与 notice/index.js DEFAULT_REGISTERED_EVENT_CODES)", + "FIXED_GROUP_SUBSCRIPTIONS.receiving_store_bound:仅货主侧目标 store:receiving + fallbackTargets store:after_sales(回退链复用 sendToWarehouseChannel 通用逻辑)", + "storage/receiving.js 新增 sendStoreBoundNotice:内容「收货单号:Rxx 正在收货 / 请确认是否已填写车牌号或快递单号」+ 货主端快速查看链接(storeContent)", + "触发点:create(创建时已绑定货主)、bindStore(首次绑定)、updateReceivingStats(商品匹配后自动绑定),失败均不影响主流程", + "e2e 新增 receiving_store_bound(货主 1000000 → 货主收货群)与 receiving_store_bound_fallback_after_sales(货主 1000241 → 售后群)" + ], + "module": "receiving" + }, + { + "version": "2026-08-17-warehouse-07", + "date": "2026-08-17", + "type": "changed", + "summary": "补回 inbox 权限到操作角色:客服组主管/员工、仓库组主管/员工补齐消息和自动回复/群列表/消息记录页面与 inbox.* API 权限;上线时需执行 script/backfill-inbox-permissions.cjs", + "methods": [], + "notes": [ + "新增 script/backfill-inbox-permissions.cjs:按角色合并 inbox 权限 ID(491~503、531 共 14 项,含页面 492/493/494),支持 --dry-run / --role-ids", + "permissions='*' 的全量角色(超级管理员/经理/仓库管理员/货主管理员)自动跳过,原本即拥有", + "dev 库已回填:26 仓库组-主管、27 仓库组-员工、28 客服组-主管、30 客服组-员工" + ], + "module": "permission" } ] diff --git a/script/backfill-inbox-permissions.cjs b/script/backfill-inbox-permissions.cjs new file mode 100644 index 0000000..76f320e --- /dev/null +++ b/script/backfill-inbox-permissions.cjs @@ -0,0 +1,217 @@ +'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); +});