Compare commits

...

4 Commits

Author SHA1 Message Date
liufumingren
591a69d35e fix(notice): 收货通知群路由细化与奇门取消拦截转快递群
- receiving_completed/rejected 只通知仓库收货群,不再通知货主(货主端链接不再生成)
- receiving_reviewed 货主侧三级回退:货主收货群→货主售后群→仓库异常群(sendToWarehouseChannel 支持 fallbackTargets 回退链)
- 新增 receiving_store_bound:收货单创建/首次绑定货主时提醒货主填写车牌号/快递单号,路由同三级回退
- qimen order.cancel 两个拦截分支仅限有运单时创建拦截工单并通知对应快递群,与正常货主发起拦截一致
- 新增 script/backfill-inbox-permissions.cjs:客服/仓库组主管员工回填 inbox 页面与 API 权限(已执行 dev 与线上)
2026-08-17 22:10:47 +08:00
liufumingren
0392902414 fix(order.recheckOrder): 车号扫描快照兜底过滤已解绑任务
- 兜底查询新增 NOT EXISTS 过滤:该车号下存在解绑记录(unbind_time 非空)的任务不再回退命中
- 绑定表保持权威数据源语义,解绑即失效;快照数据不清除,兼容无解绑记录的历史数据
- 生产库 car04 验证:新查询 0 命中(原查询命中已完成任务 3416)
2026-08-17 22:04:58 +08:00
liufumingren
e6f4d9f341 feat(inbox): 处理备注推送货主群、群类型清空接口与群按ID管理
- afterSale.handleWorkOrder: 处理备注发送到对应货主售后群(notifyGroup,内部流程不推),响应 notified_groups
- inbox.group.reset: 新增清空群类型接口(入参群主键ID),权限迁移 556
- 群登记以 group_id 为准: 移除同名群回填,群ID不存在直接新建,store_id/群信息均按 group_id 精确匹配
- changeAddr: 已有工单也把客户原文转发快递群并升级 pending_feedback(仅 pending 可升级)
- handleExpressFeedback: 工单描述售后类型显示中文(订单.物流异常)
- 同步 methods/system.json 与 changes 记录
2026-08-17 22:01:18 +08:00
liufumingren
a8200a3a35 feat(order): 订单拦截全链路阻断与作业排除
- 新增 app/lib/intercept_guard 共享守卫:除 none 外所有拦截状态一律视为已拦截
- 分配波次(singleFetchByIds)/抓取波次(createWavePickTask) 排除拦截订单并回传清单
- 分配储位(allocatePicking)/分配快递(createWaybillCodePipeline、batchAllocateExpress) 跳过拦截订单并回报
- 打印组装(getWavePlatformPrintData/getOrderPrintData/getPrintDataByWaybillCodes) 剔除拦截订单,打印回写/波次反查/标记均排除
- 拣货完成(wavePickTaskComplete) 拦截报错;复核(assertOrderCanRecheck/批量快捷复核) 补全拦截状态
- 打包/称重(workbench、order.updateExpressWeighingWeight) 拦截阻断,波次批量操作排除拦截单
- 绑定包材(order_express) 拦截阻断,波次批量绑定排除拦截单
2026-08-17 21:58:43 +08:00
31 changed files with 1442 additions and 127 deletions

View File

@ -0,0 +1,31 @@
'use strict';
/**
* 订单拦截状态共享定义。
*
* wms_order_delivery.intercept_status 枚举(order_delivery.js / order_delivery_factory.js)实际取值为:
* none / requesting / requested / intercepting / intercepted_in_transit / intercepted_at_warehouse /
* returning / returned / delivered_by_mistake / timeout / cancelled / failed / exception。
*
* 业务约定:拦截状态只要不是 'none'(即任意进入拦截流程/拦截结果的状态),一律视为"已拦截",
* 禁止继续执行仓储作业(分配波次/分配储位/分配快递/打印/抓取波次/拣货/复核/打包/称重/绑定包材等),
* 被拦截订单一律跳过。
*/
const INTERCEPT_STATUS_NONE = 'none';
/**
* 判断订单拦截状态是否属于"已拦截"。
* 空值/NULL 归一化为 none 处理;除此之外任何非 none 状态(含 requested/intercepting/intercepted_*、
* returning/returned/cancelled/failed/exception 等)均视为已拦截。
* @param {*} status 拦截状态值。
* @return {boolean} 是否已拦截。
*/
function isInterceptedOrderStatus(status) {
const normalizedStatus = String(status || '').trim() || INTERCEPT_STATUS_NONE;
return normalizedStatus !== INTERCEPT_STATUS_NONE;
}
module.exports = {
INTERCEPT_STATUS_NONE,
isInterceptedOrderStatus,
};

View File

@ -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: '定时兜底扫描任务在仓库维度触发失败时通知' }),

View File

@ -2173,7 +2173,10 @@ class InboxFunctionsService extends Service {
// 第三步:创建工单(含原文)并映射 waybill_id → 工单号
const createdNos = [];
const waybillToAsNo = {}; // waybill_id → after_sale_no 映射
const waybillToAsNo = {}; // waybill_id → after_sale_no 映射(新建 + 已存在)
for (const r of existingASList) {
waybillToAsNo[r.waybill_id] = r.after_sale_no;
}
if (toCreate.length > 0) {
const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统';
for (const e of toCreate) {
@ -2209,8 +2212,9 @@ class InboxFunctionsService extends Service {
}
// 第四步:原文转发到对应快递的售后群(按快递分组)
// 新建与已存在的工单都转发:客户再次发来的原文是快递需要的最新诉求
const expressByCode = {};
for (const e of toCreate) {
for (const e of expressList) {
const code = e.logistics_code || '__unknown__';
if (!expressByCode[code]) {
expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] };
@ -2245,7 +2249,7 @@ class InboxFunctionsService extends Service {
});
notifiedTotal += 1;
}
toCreate
expressList
.filter(e => (e.logistics_code || '__unknown__') === code)
.forEach(e => notifiedWaybillIds.add(e.id));
} catch (e) {
@ -2253,8 +2257,11 @@ class InboxFunctionsService extends Service {
}
}
// 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限
const notifiedAsNos = createdNos.filter((asNo, idx) => notifiedWaybillIds.has(toCreate[idx].id));
// 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限(新建与已有工单,仅 pending 状态升级)
const notifiedAsNos = expressList
.filter(e => notifiedWaybillIds.has(e.id))
.map(e => waybillToAsNo[e.id])
.filter(Boolean);
if (notifiedAsNos.length > 0) {
try {
const hours = await ctx.service.systems.afterSale._resolveFollowupHours(
@ -2266,7 +2273,12 @@ class InboxFunctionsService extends Service {
followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`),
role_group: 'customer_service',
},
{ where: { after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos } } }
{
where: {
after_sale_no: { [ctx.app.Sequelize.Op.in]: notifiedAsNos },
status: 'pending',
},
}
);
} catch (e) {
ctx.logger.warn(`[inbox functions] 改地址/催退回更新工单状态失败: ${e.message}`);
@ -3331,6 +3343,15 @@ class InboxFunctionsService extends Service {
const asType = String(params.as_type || 'order').trim() || 'order';
const asSubType = String(params.as_sub_type || 'logistics_issue').trim() || 'logistics_issue';
// 工单详细描述中的售后类型/子类型显示中文名称(存储仍用英文编码)
const asTypesMeta = (ctx.model.AfterSale && ctx.model.AfterSale.AFTER_SALE_TYPES) || [];
const asTypeMeta = asTypesMeta.find(t => t.type === asType);
const asTypeName = (asTypeMeta && asTypeMeta.name) || asType;
const asSubTypeMeta = asTypeMeta && Array.isArray(asTypeMeta.subType)
? asTypeMeta.subType.find(s => s.value === asSubType)
: null;
const asSubTypeName = (asSubTypeMeta && asSubTypeMeta.name) || asSubType;
if (!raw) return { success: false, error: '请提供运单号' };
if (!warehouseId) return { success: false, error: '无法获取仓库信息' };
@ -3419,7 +3440,7 @@ class InboxFunctionsService extends Service {
const description = [
`运单号: ${e.waybill_code}`,
`快递公司: ${e.logistics_name || '未知'}`,
`售后类型: ${asType}.${asSubType}`,
`售后类型: ${asTypeName}.${asSubTypeName}`,
'来源: 快递群反馈',
feedbackMsgContent ? `原文: ${feedbackMsgContent}` : '',
].filter(Boolean).join('\n');
@ -3553,6 +3574,7 @@ class InboxFunctionsService extends Service {
where: {
group_id: { [ctx.app.Sequelize.Op.in]: candidateGroupIds },
warehouse_id: warehouseId,
is_blocked: 0,
},
raw: true,
});

View File

@ -28,7 +28,7 @@ class InboxProcessorService extends Service {
* @param {string} groupId 外部群ID
* @param {number} warehouseId 仓库ID
* @param {Object|null} msgExtData 入站消息的 ext_data
* @return {Promise<{group_type: string, sub_type: string, ai_enabled: number, ext_data: Object|null}>}
* @return {Promise<{group_type: string, sub_type: string, ai_enabled: number, ext_data: Object|null}>} 群类型/子类型/AI开关/扩展数据
*/
async _loadGroupInfo(groupId, warehouseId, msgExtData) {
const { ctx } = this;

View File

@ -165,27 +165,19 @@ class InboxReceiverService extends Service {
);
}
} else {
// 群ID不存在:优先兼容同名群回填群ID;都没有才新建。
// 注意表上已无 (group_name, warehouse_id) 唯一索引,名称维度不再保证唯一。
const byName = await ctx.model.InboxGroup.findOne({
where: { group_name: groupName, warehouse_id: warehouseId },
// 群ID不存在:按群ID直接新建(群以ID为准,不按名称匹配既有群)
await ctx.model.InboxGroup.create({
group_name: groupName,
group_id: extGroupId,
warehouse_id: warehouseId,
store_id: storeId || null,
source_type: sourceType,
source_extra: data.source_extra || null,
ai_enabled: 0,
});
if (byName) {
await byName.update({ group_id: extGroupId });
ctx.logger.info(
`[inbox] 同名群回填群ID group_id=${extGroupId} name=${groupName}`
);
} else {
await ctx.model.InboxGroup.create({
group_name: groupName,
group_id: extGroupId,
warehouse_id: warehouseId,
store_id: storeId || null,
source_type: sourceType,
source_extra: data.source_extra || null,
ai_enabled: 0,
});
}
ctx.logger.info(
`[inbox] 新建群记录 group_id=${extGroupId} name=${groupName}`
);
}
} else {
// 无群ID:按 (group_name, warehouse_id) 幂等登记(向后兼容)

View File

@ -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,

View File

@ -516,6 +516,7 @@ class AfterSaleMethodService extends MainService {
operatorId,
operatorSnapshot,
warehouseId,
notifyGroup: true,
});
return this.success('处理成功', result);

View File

@ -9,13 +9,14 @@ const MainService = require('../main');
class InboxSystemService extends MainService {
/**
* 群管理子入口,供 /system dispatcher 按 inbox.group.* 路径访问。
* @return {{list: Function, disable: Function, update: Function, messages: Function, checkAuth: Function}}
* @return {{list: Function, disable: Function, update: Function, reset: Function, messages: Function, checkAuth: Function}}
*/
get group() {
return {
list: data => this.groupList(data),
disable: data => this.groupDisable(data),
update: data => this.groupUpdate(data),
reset: data => this.groupReset(data),
messages: data => this.groupMessages(data),
checkAuth: (...args) => this.checkAuth(...args),
};
@ -158,6 +159,25 @@ class InboxSystemService extends MainService {
return { message: '群信息修改成功' };
}
/**
* 清空群类型配置(入参主键ID或外部群ID)。
* 清空 group_type / sub_type / store_id / 快递专属字段,AI 开关重置关闭,
* 仅保留群创建时信息。warehouseId 从 ctx.user.store_id 自动注入。
*
* @param {Object} data 请求数据。
* @param {number} data.id 群记录主键ID(必填)。
* @return {Promise<Object>} { message: 操作结果 }。
*/
async groupReset(data = {}) {
const { ctx } = this;
const { id } = data;
const warehouseId = Number(ctx.user?.store_id || 0);
await ctx.service.systems.inbox.group.reset({ id, warehouseId });
return { message: '群类型配置已清空' };
}
/**
* 拉取指定群的消息列表。
* warehouseId 从 ctx.user.store_id 自动注入。

View File

@ -2,6 +2,7 @@
const MainService = require('../../main');
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
const { isInterceptedOrderStatus } = require('../../../lib/intercept_guard');
const DEFAULT_PAGE_SIZE = 20;
const MAX_PAGE_SIZE = 500;
@ -194,6 +195,36 @@ class OrderBaseService extends MainService {
return `${chars[0]}***${chars[chars.length - 1]}`;
}
/**
* 判断订单拦截状态是否属于"已进入拦截流程"的状态。
*
* requested/requesting/intercepting 为拦截发起中,intercepted_in_transit 为途中拦截成功,
* intercepted_at_warehouse 为仓库拦截成功;intercepted 为历史遗留值,一并兼容。
*
* @param {*} status 拦截状态值。
* @return {boolean} 是否已进入拦截流程。
*/
isInterceptedOrderStatus(status = '') {
return isInterceptedOrderStatus(status);
}
/**
* 断言订单未进入拦截流程,否则抛出阻断异常。
*
* @param {Object} orderRow 订单行(需含 intercept_status 字段)。
* @param {string} [actionText='继续作业'] 被阻断的作业文案。
* @return {void} 无返回值。
*/
assertOrderNotIntercepted(orderRow = {}, actionText = '继续作业') {
if (!this.isPlainObject(orderRow)) {
return;
}
if (this.isInterceptedOrderStatus(orderRow.intercept_status)) {
throw new Error(`订单已被拦截,无法${actionText}`);
}
}
/**
* 获取当前请求对应的仓库ID。
* @return {number|string|null} 仓库ID。

View File

@ -1205,8 +1205,14 @@ class PendingOrderService extends OrderBaseService {
const resultData = result && result.data ? result.data : (result || {});
const allocatedIds = Array.isArray(resultData.allocated_order_ids) ? resultData.allocated_order_ids : [];
const shortageIds = Array.isArray(resultData.shortage_order_ids) ? resultData.shortage_order_ids : [];
const skippedList = Array.isArray(resultData.skipped_orders) ? resultData.skipped_orders : [];
const allocatedSet = new Set(allocatedIds.map(Number));
const shortageSet = new Set(shortageIds.map(Number));
const skippedMap = new Map(
skippedList
.filter(item => Number(item && item.order_id) > 0)
.map(item => [ Number(item.order_id), item ])
);
if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
const operatorInfo = operator || {};
@ -1218,16 +1224,23 @@ class PendingOrderService extends OrderBaseService {
const oid = Number(orderId);
const allocated = allocatedSet.has(oid);
const shortage = shortageSet.has(oid);
const skippedItem = skippedMap.get(oid) || null;
const skippedReason = skippedItem ? String(skippedItem.skipped_reason || '').trim() : '';
const skippedMessage = skippedReason === 'intercepted'
? '储位分配跳过:订单已拦截'
: (skippedReason ? `储位分配跳过:${skippedReason}` : '');
const operationCode = allocated
? 'ORDER_STORAGE_ALLOCATE_SUCCESS'
: shortage
? 'ORDER_STORAGE_ALLOCATE_FAILED'
: 'ORDER_STORAGE_ALLOCATE_SUCCESS';
: skippedItem
? 'ORDER_STORAGE_ALLOCATE_FAILED'
: 'ORDER_STORAGE_ALLOCATE_SUCCESS';
const msg = allocated
? '储位分配成功'
: shortage
? '储位分配失败:库存不足'
: '储位分配完成';
: skippedMessage || '储位分配完成';
return {
business_type: 'order',
business_id: String(oid),

View File

@ -671,28 +671,6 @@ class RecheckOrderService extends OrderBaseService {
};
}
/**
* 判断订单拦截状态是否属于"已进入拦截流程"的状态。
* 拦截状态枚举(wms_order_delivery.intercept_status)实际取值为:
* none / requesting / requested / intercepting / intercepted_in_transit / intercepted_at_warehouse /
* returning / returned / delivered_by_mistake / timeout / cancelled / failed / exception。
* 其中 requested/requesting/intercepting 为拦截发起中,intercepted_in_transit 为途中拦截成功,
* intercepted_at_warehouse 为仓库拦截成功;intercepted 为历史遗留值,一并兼容。
* @param {string} status 拦截状态。
* @return {boolean} 是否为拦截流程状态。
*/
isInterceptedOrderStatus(status = '') {
const normalizedStatus = String(status || '').trim();
return [
'intercepted',
'requested',
'requesting',
'intercepting',
'intercepted_in_transit',
'intercepted_at_warehouse',
].includes(normalizedStatus);
}
/**
* 构建团购波次列表视图(团单模式)。
* 根据拣货任务ID查找关联的所有波次,每个波次展开为一项。
@ -2734,7 +2712,8 @@ class RecheckOrderService extends OrderBaseService {
* 通过车号查找匹配的拣货任务行。
* 匹配优先级:
* 1. wms_pick_task_cart_binding(车任务绑定表,unbind_time IS NULL,权威数据源)
* 2. wms_wave_pick_task.current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot(快照回退兜底)
* 2. wms_wave_pick_task.current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot(快照回退兜底,
* 仅兜底该车号下不存在解绑记录的任务:绑定表为权威数据源,已解绑的任务不再回退命中,避免解绑后快照残留误匹配)
* @param {string} cartCode 车号。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object|null>} 任务行,未找到返回 null。
@ -2769,7 +2748,9 @@ class RecheckOrderService extends OrderBaseService {
return bindingRows[0];
}
// 第二优先级(回退兜底):任务主表 + 任务订单行快照
// 第二优先级(回退兜底):任务主表 + 任务订单行快照。
// 绑定表是权威数据源:该车号下存在解绑记录(unbind_time 非空)的任务不再回退命中,
// 避免解绑后任务主表/订单行快照残留导致误匹配已完成任务。
const snapshotRows = await ctx.model.query(
`
SELECT
@ -2790,6 +2771,14 @@ class RecheckOrderService extends OrderBaseService {
AND pto.cart_code_snapshot = :cartCode
)
)
AND NOT EXISTS (
SELECT 1
FROM wms_pick_task_cart_binding b
WHERE b.task_id = t.id
AND b.warehouse_id = :warehouseId
AND b.cart_code_snapshot = :cartCode
AND b.unbind_time IS NOT NULL
)
ORDER BY t.create_time DESC, t.id DESC
LIMIT 1
`,
@ -3201,8 +3190,7 @@ class RecheckOrderService extends OrderBaseService {
if (String(order.pick_status || '') === 'none') {
throw new Error('订单未拣货,不允许复核。');
}
const interceptStatus = String(order.intercept_status || '').trim();
if (interceptStatus === 'intercepted' || interceptStatus === 'intercepted_at_warehouse') {
if (this.isInterceptedOrderStatus(order.intercept_status)) {
throw new Error('订单已被拦截,无法提交复核');
}
}
@ -3926,7 +3914,7 @@ class RecheckOrderService extends OrderBaseService {
* 1. 未分配储位:storage_status 不等于 'fin'
* 2. 未分配快递:post_status 不等于 'fin'
* 3. 未同步:status 不等于 'created'
* 4. 已拦截:intercept_status 为 'intercepted' 或 'intercepted_at_warehouse'
* 4. 已拦截:intercept_status 处于拦截流程状态(requested/requesting/intercepting/intercepted_in_transit/intercepted_at_warehouse,历史值 intercepted 兼容)
*
* 核心流程(每个满足条件的订单在独立事务中执行):
* 1. 若 pick_status 不等于 'fin',先完成拣货:
@ -3983,8 +3971,7 @@ class RecheckOrderService extends OrderBaseService {
continue;
}
const interceptStatus = String(order.intercept_status || '').trim();
if (interceptStatus === 'intercepted' || interceptStatus === 'intercepted_at_warehouse') {
if (this.isInterceptedOrderStatus(order.intercept_status)) {
failedOrders.push({
order_id: orderId,
delivery_order_code: String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(),
@ -4172,8 +4159,7 @@ class RecheckOrderService extends OrderBaseService {
for (const order of waveOrders) {
const orderId = Number(order.id);
const interceptStatus = String(order.intercept_status || '').trim();
if (interceptStatus === 'intercepted' || interceptStatus === 'intercepted_at_warehouse') {
if (this.isInterceptedOrderStatus(order.intercept_status)) {
allFailedOrders.push({
order_id: orderId,
wave_id: waveId,

View File

@ -6800,7 +6800,7 @@ class WaveService extends OrderBaseService {
try {
const orderRows = await orderModel.findAll({
attributes: [ 'id', 'wave_id', 'wave_no', 'step', 'status', 'outbound_status', 'items_hash', 'items', 'logistics_name' ],
attributes: [ 'id', 'wave_id', 'wave_no', 'step', 'status', 'outbound_status', 'items_hash', 'items', 'logistics_name', 'intercept_status' ],
where: {
id: { [Op.in]: normalizedIds },
},
@ -6819,6 +6819,11 @@ class WaveService extends OrderBaseService {
.map(row => Number(row && row.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ]
.sort((a, b) => a - b);
const excludedInterceptedOrderIds = [ ...new Set(normalizedOrderRows
.filter(row => this.isInterceptedOrderStatus(row && row.intercept_status))
.map(row => Number(row && row.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ]
.sort((a, b) => a - b);
const fetchableRows = normalizedOrderRows.filter(row => {
const orderId = Number(row && row.id || 0);
@ -6832,6 +6837,11 @@ class WaveService extends OrderBaseService {
return false;
}
// 拦截流程中的订单不允许分配波次
if (this.isInterceptedOrderStatus(row && row.intercept_status)) {
return false;
}
return true;
});
@ -6851,6 +6861,7 @@ class WaveService extends OrderBaseService {
fetched_order_ids: [],
fetched_order_count: 0,
excluded_existing_wave_order_ids: excludedExistingWaveOrderIds,
excluded_intercepted_order_ids: excludedInterceptedOrderIds,
skipped_order_ids: skippedOrderIds,
not_found_order_ids: notFoundOrderIds,
});
@ -6964,6 +6975,7 @@ class WaveService extends OrderBaseService {
fetched_order_ids: grabbedOrderIds,
fetched_order_count: grabbedOrderIds.length,
excluded_existing_wave_order_ids: excludedExistingWaveOrderIds,
excluded_intercepted_order_ids: excludedInterceptedOrderIds,
skipped_order_ids: skippedOrderIds,
not_found_order_ids: notFoundOrderIds,
});
@ -8792,7 +8804,7 @@ class WaveService extends OrderBaseService {
try {
orderRows = await orderModel.findAll({
attributes: [ 'id', 'business_key' ],
attributes: [ 'id', 'business_key', 'intercept_status' ],
where: baseOrderWhere,
raw: true,
});
@ -8808,7 +8820,7 @@ class WaveService extends OrderBaseService {
warehouseId,
});
orderRows = await orderModel.findAll({
attributes: [ 'id' ],
attributes: [ 'id', 'intercept_status' ],
where: baseOrderWhere,
raw: true,
});
@ -8823,10 +8835,25 @@ class WaveService extends OrderBaseService {
matchedOrderCount: Array.isArray(orderRows) ? orderRows.length : 0,
});
const skippedInterceptedOrderIds = [ ...new Set((Array.isArray(orderRows) ? orderRows : [])
.filter(row => this.isInterceptedOrderStatus(row && row.intercept_status))
.map(row => Number(row && row.id || 0))
.filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]
.sort((a, b) => a - b);
const skippedInterceptedOrderIdSet = new Set(skippedInterceptedOrderIds);
if (skippedInterceptedOrderIds.length > 0) {
this.ctx.logger.info('[wave.batchAllocateExpress] 跳过拦截订单', {
traceId,
taskId: normalizedTaskId,
warehouseId,
skippedInterceptedOrderIds,
});
}
const normalizedOrders = (Array.isArray(orderRows) ? orderRows : [])
.map(row => {
const orderId = Number(row && row.id || 0);
if (!Number.isInteger(orderId) || orderId <= 0) {
if (!Number.isInteger(orderId) || orderId <= 0 || skippedInterceptedOrderIdSet.has(orderId)) {
return null;
}
@ -8844,6 +8871,7 @@ class WaveService extends OrderBaseService {
taskId: normalizedTaskId,
warehouseId,
waveIds,
skippedInterceptedOrderIds,
});
const durationMs = Date.now() - startTime;
await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'success', {
@ -8853,14 +8881,18 @@ class WaveService extends OrderBaseService {
processed_order_count: 0,
success_order_count: 0,
failed_order_count: 0,
skipped_intercepted_order_ids: skippedInterceptedOrderIds,
progress_percent: 100,
end_time: Date.now(),
duration_ms: durationMs,
result: {
wave_ids: waveIds,
allocated_order_count: 0,
skipped_intercepted_order_ids: skippedInterceptedOrderIds,
duration_ms: durationMs,
message: '未找到可分配快递号的订单',
message: skippedInterceptedOrderIds.length > 0
? `拦截订单已跳过,未找到可分配快递号的订单(跳过 ${skippedInterceptedOrderIds.length} 单)`
: '未找到可分配快递号的订单',
},
trace_id: traceId,
});
@ -8902,12 +8934,14 @@ class WaveService extends OrderBaseService {
processed_order_count: normalizedOrders.length,
success_order_count: normalizedOrders.length,
failed_order_count: 0,
skipped_intercepted_order_ids: skippedInterceptedOrderIds,
progress_percent: 100,
end_time: Date.now(),
duration_ms: durationMs,
result: {
wave_ids: waveIds,
allocated_order_count: normalizedOrders.length,
skipped_intercepted_order_ids: skippedInterceptedOrderIds,
duration_ms: durationMs,
message: String(pipelineResult && pipelineResult.message || '分配快递任务已提交').trim(),
},

View File

@ -1,6 +1,7 @@
'use strict';
const MainService = require('../main');
const { isInterceptedOrderStatus } = require('../../lib/intercept_guard');
class PickService extends MainService {
/**
@ -132,9 +133,26 @@ class PickService extends MainService {
[this.app.Sequelize.Op.in]: normalizedOrderIds,
},
},
attributes: [ 'id' ],
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
// 拦截流程中的订单不允许抓取波次,直接剔除
const interceptedOrderIds = new Set((Array.isArray(orderRows) ? orderRows : [])
.filter(row => isInterceptedOrderStatus(row && row.intercept_status))
.map(row => Number(row && row.id || 0))
.filter(id => Number.isInteger(id) && id > 0));
if (interceptedOrderIds.size > 0) {
const excludedIds = normalizedOrderIds.filter(id => interceptedOrderIds.has(id));
if (excludedIds.length > 0) {
ctx.logger.info('[pick.createWavePickTask] 剔除拦截订单: %s', excludedIds.join(','));
}
}
const activeOrderIds = normalizedOrderIds.filter(id => !interceptedOrderIds.has(id));
if (activeOrderIds.length <= 0) {
throw Object.assign(new Error('波次下订单均已被拦截,无法创建任务'), { code: 400 });
}
const orderNoMap = new Map((Array.isArray(orderRows) ? orderRows : [])
.map(row => [ Number(row && row.id || 0), '' ]));
@ -182,7 +200,7 @@ class PickService extends MainService {
waveId,
pickMode,
source,
orderCount: normalizedOrderIds.length,
orderCount: activeOrderIds.length,
operatorId,
operatorName,
remark,
@ -257,10 +275,10 @@ class PickService extends MainService {
}
);
if (normalizedOrderIds.length > 0) {
if (activeOrderIds.length > 0) {
// 按库位排序并按 stock_id 分组,同 stock_id 的订单共享同一篮号
const stockGroups = await this.resolveLocationSortedOrderIds(
normalizedOrderIds,
activeOrderIds,
warehouseId,
transaction
);
@ -418,7 +436,7 @@ class PickService extends MainService {
&& this.ctx.service.systems
&& this.ctx.service.systems.operationLog;
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
const logPayloads = normalizedOrderIds.map(orderId => ({
const logPayloads = activeOrderIds.map(orderId => ({
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'ORDER_WAVE_GRAB',
@ -437,7 +455,7 @@ class PickService extends MainService {
} catch (e) {
ctx.logger.warn('[pick.createWavePickTask] 写入 order_operation_log 失败,不影响主流程', {
error: e && e.message,
normalizedOrderIds,
activeOrderIds,
});
}

View File

@ -348,6 +348,7 @@ class PrintService extends MainService {
: { print_status: 'error' };
const where = {
id: orderIds,
intercept_status: 'none',
};
if (callbackResult === 'failed') {
where.print_status = 'none';
@ -1614,6 +1615,7 @@ class PrintService extends MainService {
wave_id: waveId,
warehouse_id: warehouseId,
status: { [this.app.Sequelize.Op.ne]: 'cancel' },
intercept_status: 'none',
},
raw: true,
});
@ -1764,6 +1766,7 @@ class PrintService extends MainService {
}, {
where: {
id: orderIds,
intercept_status: 'none',
},
});

View File

@ -1074,14 +1074,15 @@ class AfterSaleService extends Service {
* @param {number} params.operatorId 操作人ID
* @param {string} params.operatorSnapshot 操作人快照 JSON
* @param {number} params.warehouseId 仓库ID
* @return {Promise<Object>} 处理结果,包含更新后的售后单和步骤记录
* @param {boolean} [params.notifyGroup] 是否将处理备注发送到对应货主售后群(内部自动处理不传)
* @return {Promise<Object>} 处理结果,包含更新后的售后单、步骤记录和通知群数量
* @throws {Error} 售后单不存在或权限不足时抛出
*/
async handleWorkOrder(params = {}) {
const {
id, remark, targetStatus, resolution,
attachmentIds, operatorId, operatorSnapshot,
warehouseId,
warehouseId, notifyGroup,
} = params;
const { ctx } = this;
@ -1163,11 +1164,73 @@ class AfterSaleService extends Service {
await transaction.commit();
// 9. 处理备注发送到对应的货主售后群(仅交互处理传入 notifyGroup 时触发,不转发快递群)
let notifiedGroupCount = 0;
if (notifyGroup && remark && String(remark).trim()) {
try {
const remarkText = String(remark).trim();
const asRow = afterSale.toJSON ? afterSale.toJSON() : afterSale;
// 定位货主:优先工单 store_id,缺失时从来源消息所在群反查
let notifyStoreId = Number(asRow.store_id || 0);
if (!notifyStoreId && asRow.inbox_message_id) {
try {
const inbound = await ctx.model.InboxMessage.findByPk(asRow.inbox_message_id, {
attributes: [ 'group_id' ],
raw: true,
});
if (inbound && inbound.group_id) {
const originGroup = await ctx.model.InboxGroup.findOne({
attributes: [ 'store_id' ],
where: {
group_id: inbound.group_id,
warehouse_id: warehouseId,
is_blocked: 0,
},
raw: true,
});
if (originGroup && originGroup.store_id) {
notifyStoreId = Number(originGroup.store_id);
}
}
} catch (originErr) {
ctx.logger.warn(`[handleWorkOrder] 反查来源群货主失败 id=${id}: ${originErr.message}`);
}
}
if (notifyStoreId) {
const storeGroups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({
storeIds: [ notifyStoreId ],
warehouseId,
});
const content = `【工单 ${asRow.after_sale_no}】处理备注:\n${remarkText}`;
for (const g of storeGroups) {
if (!g.group_id) continue;
ctx.service.inbox.processor.pushSystemNotification({
warehouse_id: warehouseId,
group_id: g.group_id,
group_name: g.group_name || '',
content,
ext_data: g.ext_data || null,
});
notifiedGroupCount += 1;
}
}
ctx.logger.info(
`[handleWorkOrder] 处理备注发送到货主售后群 id=${id} store=${notifyStoreId} notified=${notifiedGroupCount}`
);
} catch (notifyErr) {
ctx.logger.warn(`[handleWorkOrder] 处理备注发送群失败 id=${id}: ${notifyErr.message}`);
}
}
const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale;
return {
after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app),
step,
notified_groups: notifiedGroupCount,
};
} catch (error) {
await transaction.rollback();
@ -1260,7 +1323,7 @@ class AfterSaleService extends Service {
priority: 10,
creator_id: 0,
inbox_message_id: null,
role_group: 'warehouse',
role_group: 'customer_service',
status: 'pending',
waybill_id: e.id,
waybill_no: e.waybill_code,
@ -1281,16 +1344,26 @@ class AfterSaleService extends Service {
for (const e of toCreate) {
const code = e.logistics_code || '__unknown__';
if (!expressByCode[code]) {
expressByCode[code] = { interfaceId: e.logistics_interface_id, waybills: [] };
expressByCode[code] = {
code,
interfaceId: e.logistics_interface_id,
logisticsName: String(e.logistics_name || '').trim(),
waybills: [],
};
}
expressByCode[code].waybills.push(e.waybill_code);
}
let notifiedCount = 0;
const notifiedWaybillIds = new Set();
// 无对应快递群(或快递无接口)的运单收集后统一降级通知仓库异常群(与货主群缺失降级行为一致)
const fallbackEntries = [];
for (const [ code, info ] of Object.entries(expressByCode)) {
if (code === '__unknown__' || !info.interfaceId) continue;
if (code === '__unknown__' || !info.interfaceId) {
fallbackEntries.push(info);
continue;
}
try {
const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({
expressInterfaceId: info.interfaceId,
@ -1298,7 +1371,10 @@ class AfterSaleService extends Service {
warehouseId,
});
if (afterSalesGroups.length === 0) continue;
if (afterSalesGroups.length === 0) {
fallbackEntries.push(info);
continue;
}
const notifyMsg = info.waybills.join('\n') + '\n拦截';
for (const g of afterSalesGroups) {
@ -1315,10 +1391,56 @@ class AfterSaleService extends Service {
const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code);
codeWaybills.forEach(e => notifiedWaybillIds.add(e.id));
} catch (e) {
fallbackEntries.push(info);
ctx.logger.warn(`[afterSale] 查售后群失败 code=${code}: ${e.message}`);
}
}
// 4b. 无对应快递群降级:转发仓库异常群,内容前缀标记失败(与货主群缺失降级一致)
if (fallbackEntries.length > 0) {
try {
const exceptionGroups = await ctx.model.InboxGroup.findAll({
attributes: [ 'group_id', 'group_name', 'ext_data' ],
where: {
warehouse_id: warehouseId,
group_type: 'warehouse',
sub_type: 'exception',
is_blocked: 0,
},
raw: true,
});
if (exceptionGroups.length > 0) {
const labelSet = new Set();
const fallbackLines = [];
for (const entry of fallbackEntries) {
const label = entry.logisticsName || entry.code || '未知快递';
labelSet.add(label);
for (const waybill of entry.waybills) {
fallbackLines.push(`${label} ${waybill}`);
}
}
const fallbackContent = `通知快递【${Array.from(labelSet).join('、')}】失败\n${fallbackLines.join('\n')}\n拦截`;
for (const g of exceptionGroups) {
ctx.service.inbox.processor.pushSystemNotification({
warehouse_id: warehouseId,
group_id: g.group_id,
group_name: g.group_name,
content: fallbackContent,
ext_data: g.ext_data || null,
});
}
ctx.logger.warn('[afterSale.createInterceptWorkOrdersAndNotify] 无对应快递群,已降级通知仓库异常群', {
warehouseId,
fallbackCount: fallbackEntries.length,
exceptionGroupCount: exceptionGroups.length,
});
}
} catch (fallbackErr) {
ctx.logger.warn(`[afterSale] 降级通知异常群失败: ${fallbackErr.message}`);
}
}
// 5. 有通知的工单升级为 pending_feedback
if (notifiedWaybillIds.size > 0) {
const notifiedWaybillIdArr = [ ...notifiedWaybillIds ];

View File

@ -2,6 +2,8 @@
const { Service } = require('egg');
const { isInterceptedOrderStatus } = require('../../lib/intercept_guard');
const DEFAULT_CACHE_TTL_SECONDS = 600;
const DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS = 60 * 60;
const DEFAULT_WAYBILL_BATCH_SIZE = 10;
@ -2514,7 +2516,7 @@ class ExpressService extends Service {
[Op.ne]: 'cancel',
},
},
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key' ],
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status' ],
raw: true,
});
@ -2538,13 +2540,27 @@ class ExpressService extends Service {
[Op.ne]: 'cancel',
},
},
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key' ],
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key', 'intercept_status' ],
raw: true,
});
}
}
const orders_arr = [ ...(Array.isArray(currentOrders) ? currentOrders : []), ...dispatchOrders ];
// 拦截订单跳过(除 none 外一律视为已拦截)
const mergedOrders = [ ...(Array.isArray(currentOrders) ? currentOrders : []), ...dispatchOrders ];
const interceptedOrderIdSet = new Set(mergedOrders
.filter(order => isInterceptedOrderStatus(order && order.intercept_status))
.map(order => Number(order && order.id || 0))
.filter(orderId => Number.isInteger(orderId) && orderId > 0));
const skippedInterceptedOrderIds = Array.from(interceptedOrderIdSet);
const orders_arr = mergedOrders.filter(order => !interceptedOrderIdSet.has(Number(order && order.id || 0)));
if (skippedInterceptedOrderIds.length > 0) {
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 跳过拦截订单', {
traceId,
warehouseId,
skippedInterceptedOrderIds,
});
}
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 订单筛选结果', {
traceId,
warehouseId,
@ -2552,6 +2568,7 @@ class ExpressService extends Service {
currentCount: (Array.isArray(currentOrders) ? currentOrders : []).length,
dispatchCount: dispatchOrders.length,
matchedOrderCount: orders_arr.length,
skippedInterceptedOrderIds,
});
// 【step1.5】过滤已分配运单号(status=1)且传入 business_key=1 的订单,避免重复分配。
@ -2600,7 +2617,10 @@ class ExpressService extends Service {
if (filteredOrdersArr.length === 0) {
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 所有订单均已分配运单号,无需处理', { traceId });
return { message: '所有订单均已分配运单号,无需处理' };
return {
message: '所有订单均已分配运单号,无需处理',
skipped_intercepted_order_ids: skippedInterceptedOrderIds,
};
}
// orders_arr和orderList合并:同一 order_id 在 orderList 中可能有多条(不同 business_key),
@ -2702,7 +2722,10 @@ class ExpressService extends Service {
traceId,
groupedCount: groupedOrders.length,
});
return { message: '分配快递任务已提交' };
return {
message: '分配快递任务已提交',
skipped_intercepted_order_ids: skippedInterceptedOrderIds,
};
}
/**
* 异步执行订单快递分配任务。错误订单转异常,并记录失败订单列表。

View File

@ -362,6 +362,55 @@ class InboxGroupService extends Service {
);
}
/**
* 清空群类型配置。
* 将群恢复为"仅保留创建信息"状态:清空 group_type / sub_type / store_id /
* express_interfaces / system_express_code,AI 开关重置为关闭。
* 保留群名称、群ID、仓库、来源信息、屏蔽状态与扩展数据。
*
* @param {Object} data 请求数据。
* @param {number} data.id 群记录主键ID(必填)。
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
* @return {Promise<{id: number, group_name: string, group_id: string|null}>} 被重置的群信息。
*/
async reset(data = {}) {
const { ctx } = this;
const { InboxGroup } = ctx.model;
const id = Number(data.id);
const warehouseId = Number(data.warehouseId);
if (!warehouseId) throw new Error('warehouseId 无效');
if (!id) throw new Error('群ID无效');
const where = { id, warehouse_id: warehouseId };
const group = await InboxGroup.findOne({
attributes: [ 'id', 'group_name', 'group_id' ],
where,
raw: true,
});
if (!group) throw new Error('群不存在或无权限操作');
await InboxGroup.update(
{
group_type: null,
sub_type: null,
store_id: null,
express_interfaces: null,
system_express_code: null,
ai_enabled: 0,
},
{ where }
);
ctx.logger.info(
`[inbox group] 清空群类型配置 id=${group.id} group_id=${group.group_id} warehouse_id=${warehouseId}`
);
return { id: group.id, group_name: group.group_name, group_id: group.group_id };
}
/**
* 校验快递接口ID数组的有效性。
* 所有ID必须在 wms_express_interface 表中存在。
@ -436,6 +485,7 @@ class InboxGroupService extends Service {
const where = {
group_type: 'express',
system_express_code: code,
is_blocked: 0,
[Op.or]: [
{ express_interfaces: { [Op.or]: [ null, '' ] } },
{ express_interfaces: { [Op.like]: `%${eid}%` } },
@ -495,6 +545,7 @@ class InboxGroupService extends Service {
group_type: 'store',
sub_type: 'after_sales',
store_id: { [Op.in]: ids },
is_blocked: 0,
},
raw: true,
});

View File

@ -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,

View File

@ -2,6 +2,8 @@
const Service = require('egg').Service;
const { isInterceptedOrderStatus } = require('../../lib/intercept_guard');
/**
* 订单快递业务服务。
*
@ -196,6 +198,55 @@ class OrderExpressService extends Service {
return orderExpressRow;
}
/**
* 查询订单拦截状态(依次查询 current → dispatch 分表)。
* @param {number} orderId 订单 ID。
* @param {number} warehouseId 仓库 ID。
* @return {Promise<string>} 拦截状态,查询失败时返回 'none'。
*/
async findOrderInterceptStatus(orderId, warehouseId) {
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
return 'none';
}
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') continue;
const row = await model.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
if (row) {
return String(row.intercept_status || '').trim() || 'none';
}
} catch (_err) { continue; }
}
return 'none';
}
/**
* 断言订单未进入拦截流程,否则抛出业务异常。
* @param {number} orderId 订单 ID。
* @param {number} warehouseId 仓库 ID。
* @param {string} [actionText='继续作业'] 被阻断的作业文案。
* @return {Promise<void>} 无返回值。
*/
async assertOrderNotIntercepted(orderId, warehouseId, actionText = '继续作业') {
const interceptStatus = await this.findOrderInterceptStatus(orderId, warehouseId);
if (isInterceptedOrderStatus(interceptStatus)) {
throw this.createBusinessError(`订单已被拦截,无法${actionText}`, 400);
}
}
/**
* 规范化并校验称重重量。
*
@ -306,6 +357,9 @@ class OrderExpressService extends Service {
throw this.createBusinessError('运单号不存在', 404);
}
// 拦截流程中的订单不允许称重
await this.assertOrderNotIntercepted(normalizedOrderId, warehouseId, '称重');
// 依次查询多个订单表获取波次信息:current → history → dispatch
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
@ -438,6 +492,9 @@ class OrderExpressService extends Service {
const orderId = Number(expressRow.order_id || 0);
// 拦截流程中的订单不允许称重
await this.assertOrderNotIntercepted(orderId, warehouseId, '称重');
// 依次查询多个订单表获取波次信息:current → history → dispatch
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
@ -546,7 +603,7 @@ class OrderExpressService extends Service {
// 查询波次下所有订单
const waveOrders = await orderDeliveryModel.findAll({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'id' ],
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
@ -554,7 +611,18 @@ class OrderExpressService extends Service {
throw this.createBusinessError('波次下未找到订单', 404);
}
const orderIds = waveOrders.map(o => Number(o.id));
// 波次内拦截订单不参与批量称重
const interceptedWaveOrderIds = (Array.isArray(waveOrders) ? waveOrders : [])
.filter(o => isInterceptedOrderStatus(o && o.intercept_status))
.map(o => Number(o.id));
const orderIds = (Array.isArray(waveOrders) ? waveOrders : [])
.filter(o => !isInterceptedOrderStatus(o && o.intercept_status))
.map(o => Number(o.id));
if (interceptedWaveOrderIds.length > 0) {
this.ctx.logger.info(
`[order_express._updateWaveAllOrdersWeight] 波次内拦截订单不参与称重: ${interceptedWaveOrderIds.join(',')}`
);
}
// 批量更新波次下全部运单的称重重量
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
@ -880,7 +948,7 @@ class OrderExpressService extends Service {
// 查询波次下所有订单
const waveOrders = await orderDeliveryModel.findAll({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'id' ],
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
@ -888,7 +956,18 @@ class OrderExpressService extends Service {
throw this.createBusinessError('波次下未找到订单', 404);
}
const orderIds = waveOrders.map(o => Number(o.id));
// 波次内拦截订单不参与批量称重
const interceptedWaveOrderIds = (Array.isArray(waveOrders) ? waveOrders : [])
.filter(o => isInterceptedOrderStatus(o && o.intercept_status))
.map(o => Number(o.id));
const orderIds = (Array.isArray(waveOrders) ? waveOrders : [])
.filter(o => !isInterceptedOrderStatus(o && o.intercept_status))
.map(o => Number(o.id));
if (interceptedWaveOrderIds.length > 0) {
this.ctx.logger.info(
`[order_express._updateWaveOrderWeight] 波次内拦截订单不参与称重: ${interceptedWaveOrderIds.join(',')}`
);
}
const totalCount = orderIds.length;
// 批量更新所有订单的运单称重重量
@ -1295,6 +1374,9 @@ class OrderExpressService extends Service {
const materialRow = await this.findActivePackageMaterialByCode(normalizedPackageMaterialCode, warehouseId);
const orderExpressRow = await this.findValidOrderExpressByOrderAndWaybill(normalizedOrderId, normalizedWaybillCode, warehouseId);
// 拦截流程中的订单不允许绑定包材
await this.assertOrderNotIntercepted(Number(orderExpressRow.order_id), warehouseId, '绑定包材');
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
const updateResult = await orderExpressModel.update({
package_material_id: Number(materialRow.id),
@ -1383,6 +1465,9 @@ class OrderExpressService extends Service {
throw this.createBusinessError('运单号不存在', 404);
}
// 拦截流程中的订单不允许绑定包材
await this.assertOrderNotIntercepted(Number(orderExpressRow.order_id), warehouseId, '绑定包材');
// 查询启用中的包材
const materialRow = await this.findActivePackageMaterialById(normalizedPackageMaterialId, warehouseId);
@ -1581,21 +1666,35 @@ class OrderExpressService extends Service {
];
const orderIdSet = new Set();
const excludedInterceptedOrderIds = [];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findAll !== 'function') continue;
const rows = await model.findAll({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'id' ],
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
if (Array.isArray(rows)) {
rows.forEach(r => orderIdSet.add(Number(r.id)));
rows.forEach(r => {
const orderId = Number(r.id);
if (isInterceptedOrderStatus(r && r.intercept_status)) {
excludedInterceptedOrderIds.push(orderId);
return;
}
orderIdSet.add(orderId);
});
}
} catch (_err) { continue; }
}
if (excludedInterceptedOrderIds.length > 0) {
this.ctx.logger.info(
`[bindExpressPackageMaterialByWaybill] 波次内拦截订单不参与批量绑定: ${excludedInterceptedOrderIds.join(',')}`
);
}
if (orderIdSet.size === 0) {
throw this.createBusinessError('波次下未找到订单', 404);
}

View File

@ -489,12 +489,15 @@ class OrderPrintSystemService extends OrderBaseService {
total_platforms: 0,
locked_count: 0,
total_locked_orders: 0,
intercepted_count: 0,
},
waveGroups: [],
locked_wave_groups: [],
wave_ids: [],
locked_count: 0,
locked_orders: [],
intercepted_count: 0,
intercepted_orders: [],
ext: {
missing_wave_ids: normalizedWaveIds,
filtered_wave_ids: [],
@ -512,8 +515,24 @@ class OrderPrintSystemService extends OrderBaseService {
} = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows);
const validWaveIdSet = new Set(validWaveIds);
const validOrderRows = orderRows.filter(order => validWaveIdSet.has(Number(order && order.wave_id || 0)));
const interceptedOrderRows = validOrderRows.filter(
orderRow => this.isInterceptedOrderStatus(orderRow && orderRow.intercept_status)
);
const lockedOrderRows = validOrderRows.filter(orderRow => this.isOrderLocked(orderRow));
const unlockedOrderRows = validOrderRows.filter(orderRow => !this.isOrderLocked(orderRow));
const unlockedOrderRows = validOrderRows.filter(
orderRow => !this.isOrderLocked(orderRow)
&& !this.isInterceptedOrderStatus(orderRow && orderRow.intercept_status)
);
const interceptedOrders = interceptedOrderRows
.map(orderRow => ({
order_id: Number(orderRow && orderRow.id || 0),
order_no: String(orderRow && (orderRow.delivery_order_code || orderRow.source_order_codes) || '').trim(),
wave_id: Number(orderRow && orderRow.wave_id || 0),
wave_no: String(orderRow && orderRow.wave_no || '').trim(),
intercept_status: String(orderRow && orderRow.intercept_status || '').trim() || 'none',
status: 'intercepted',
status_text: '已拦截',
}));
const lockedOrders = lockedOrderRows
.map(orderRow => ({
order_id: Number(orderRow && orderRow.id || 0),
@ -553,12 +572,15 @@ class OrderPrintSystemService extends OrderBaseService {
total_platforms: 0,
locked_count: lockedOrders.length,
total_locked_orders: lockedOrders.length,
intercepted_count: interceptedOrders.length,
},
waveGroups: [],
locked_wave_groups: lockedWaveGroups,
wave_ids: validWaveIds,
locked_count: lockedOrders.length,
locked_orders: lockedOrders,
intercepted_count: interceptedOrders.length,
intercepted_orders: interceptedOrders,
ext: {
missing_wave_ids: missingWaveIds,
filtered_wave_ids: filteredWaveIds,
@ -653,12 +675,15 @@ class OrderPrintSystemService extends OrderBaseService {
total_platforms: totalPlatforms,
locked_count: lockedOrders.length,
total_locked_orders: lockedOrders.length,
intercepted_count: interceptedOrders.length,
},
waveGroups,
locked_wave_groups: lockedWaveGroups,
wave_ids: validWaveIds,
locked_count: lockedOrders.length,
locked_orders: lockedOrders,
intercepted_count: interceptedOrders.length,
intercepted_orders: interceptedOrders,
ext: {
missing_wave_ids: missingWaveIds,
filtered_wave_ids: filteredWaveIds,
@ -697,9 +722,12 @@ class OrderPrintSystemService extends OrderBaseService {
total_waves: 0,
total_orders: 0,
total_platforms: 0,
intercepted_count: 0,
},
waveGroups: [],
wave_ids: [],
intercepted_count: 0,
intercepted_orders: [],
ext: {
missing_order_ids: normalizedOrderIds,
filtered_order_ids: [],
@ -711,13 +739,33 @@ class OrderPrintSystemService extends OrderBaseService {
const missingOrderIds = normalizedOrderIds.filter(orderId => !hitOrderIdSet.has(orderId));
// 订单级过滤:仅保留 post_status === 'fin' 的订单(等价于波次级的快递完全分配检查)
const validOrderRows = orderRows.filter(row => String(row && row.post_status || '').trim() === 'fin');
const postFinOrderRows = orderRows.filter(row => String(row && row.post_status || '').trim() === 'fin');
// 拦截订单从打印清单中剔除
const interceptedOrderRows = postFinOrderRows.filter(
row => this.isInterceptedOrderStatus(row && row.intercept_status)
);
const interceptedOrders = interceptedOrderRows.map(row => ({
order_id: Number(row && row.id || 0),
order_no: String(row && (row.delivery_order_code || row.source_order_codes) || '').trim(),
wave_id: Number(row && row.wave_id || 0),
wave_no: String(row && row.wave_no || '').trim(),
intercept_status: String(row && row.intercept_status || '').trim() || 'none',
status: 'intercepted',
status_text: '已拦截',
}));
const validOrderRows = postFinOrderRows.filter(
row => !this.isInterceptedOrderStatus(row && row.intercept_status)
);
const filteredOrderIds = orderRows
.filter(row => String(row && row.post_status || '').trim() !== 'fin')
.map(row => ({
order_id: Number(row && row.id || 0),
reason: '快递未完全分配',
}));
}))
.concat(interceptedOrderRows.map(row => ({
order_id: Number(row && row.id || 0),
reason: '已拦截',
})));
if (validOrderRows.length === 0) {
return {
@ -725,9 +773,12 @@ class OrderPrintSystemService extends OrderBaseService {
total_waves: 0,
total_orders: 0,
total_platforms: 0,
intercepted_count: interceptedOrders.length,
},
waveGroups: [],
wave_ids: [],
intercepted_count: interceptedOrders.length,
intercepted_orders: interceptedOrders,
ext: {
missing_order_ids: missingOrderIds,
filtered_order_ids: filteredOrderIds,
@ -826,9 +877,12 @@ class OrderPrintSystemService extends OrderBaseService {
total_waves: waveGroups.length,
total_orders: orderPrintList.length,
total_platforms: totalPlatforms,
intercepted_count: interceptedOrders.length,
},
waveGroups,
wave_ids: validOrderWaveIds,
intercepted_count: interceptedOrders.length,
intercepted_orders: interceptedOrders,
ext: {
missing_order_ids: missingOrderIds,
filtered_order_ids: filteredOrderIds,
@ -881,9 +935,16 @@ class OrderPrintSystemService extends OrderBaseService {
const waybillRows = await this.queryWaybillsByCodes(normalizedWaybillCodes, normalizedWarehouseId);
if (waybillRows.length === 0) {
return {
summary: { total_waves: 0, total_orders: 0, total_platforms: 0 },
summary: {
total_waves: 0,
total_orders: 0,
total_platforms: 0,
intercepted_count: 0,
},
waveGroups: [],
wave_ids: [],
intercepted_count: 0,
intercepted_orders: [],
ext: {
missing_waybill_codes: normalizedWaybillCodes,
filtered_waybill_codes: [],
@ -911,9 +972,16 @@ class OrderPrintSystemService extends OrderBaseService {
if (validWaybillRows.length === 0) {
return {
summary: { total_waves: 0, total_orders: 0, total_platforms: 0 },
summary: {
total_waves: 0,
total_orders: 0,
total_platforms: 0,
intercepted_count: 0,
},
waveGroups: [],
wave_ids: [],
intercepted_count: 0,
intercepted_orders: [],
ext: {
missing_waybill_codes: missingWaybillCodes,
filtered_waybill_codes: invalidWaybillCodes,
@ -921,10 +989,24 @@ class OrderPrintSystemService extends OrderBaseService {
};
}
// 3. 过滤 post_status !== 'fin' 的订单
// 3. 过滤 post_status !== 'fin' 或进入拦截流程的订单
const interceptedOrderRows = orderRows.filter(
row => this.isInterceptedOrderStatus(row && row.intercept_status)
);
const interceptedOrderIdSet = new Set(interceptedOrderRows.map(row => Number(row.id)));
const interceptedOrders = interceptedOrderRows.map(row => ({
order_id: Number(row && row.id || 0),
order_no: String(row && (row.delivery_order_code || row.source_order_codes) || '').trim(),
wave_id: Number(row && row.wave_id || 0),
wave_no: String(row && row.wave_no || '').trim(),
intercept_status: String(row && row.intercept_status || '').trim() || 'none',
status: 'intercepted',
status_text: '已拦截',
}));
const validOrderIdSet = new Set(
orderRows
.filter(row => String(row.post_status || '').trim() === 'fin')
.filter(row => String(row.post_status || '').trim() === 'fin'
&& !this.isInterceptedOrderStatus(row && row.intercept_status))
.map(row => Number(row.id))
);
const finalWaybillRows = validWaybillRows.filter(row => validOrderIdSet.has(Number(row.order_id)));
@ -932,14 +1014,23 @@ class OrderPrintSystemService extends OrderBaseService {
.filter(row => !validOrderIdSet.has(Number(row.order_id)))
.map(row => ({
waybill_code: String(row.waybill_code || '').trim(),
reason: '关联订单快递未完全分配',
reason: interceptedOrderIdSet.has(Number(row.order_id))
? '关联订单已被拦截'
: '关联订单快递未完全分配',
}));
if (finalWaybillRows.length === 0) {
return {
summary: { total_waves: 0, total_orders: 0, total_platforms: 0 },
summary: {
total_waves: 0,
total_orders: 0,
total_platforms: 0,
intercepted_count: interceptedOrders.length,
},
waveGroups: [],
wave_ids: [],
intercepted_count: interceptedOrders.length,
intercepted_orders: interceptedOrders,
ext: {
missing_waybill_codes: missingWaybillCodes,
filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ],
@ -1079,9 +1170,12 @@ class OrderPrintSystemService extends OrderBaseService {
total_waves: waveGroups.length,
total_orders: orderPrintList.length,
total_platforms: totalPlatforms,
intercepted_count: interceptedOrders.length,
},
waveGroups,
wave_ids: validOrderWaveIds,
intercepted_count: interceptedOrders.length,
intercepted_orders: interceptedOrders,
ext: {
missing_waybill_codes: missingWaybillCodes,
filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ],
@ -1681,6 +1775,7 @@ class OrderPrintSystemService extends OrderBaseService {
'print_status',
'lock_status',
'print_lock_status',
'intercept_status',
'items_count',
'items_total',
'items_weight',
@ -1746,6 +1841,7 @@ class OrderPrintSystemService extends OrderBaseService {
'print_status',
'lock_status',
'print_lock_status',
'intercept_status',
'items_count',
'items_total',
'items_weight',

View File

@ -44,12 +44,12 @@ class OrderReviewService extends OrderBaseService {
}
/**
* 判断是否为拦截状态。
* 判断是否为拦截状态(除 none 外一律视为已拦截)。
* @param {string} interceptStatus 拦截状态。
* @return {boolean} 是否拦截。
*/
isInterceptStatus(interceptStatus) {
return String(interceptStatus || '').trim() !== 'none';
return this.isInterceptedOrderStatus(interceptStatus);
}
/**

View File

@ -2,6 +2,8 @@
const MainService = require('../main');
const { isInterceptedOrderStatus } = require('../../lib/intercept_guard');
const STORAGE_STATUS_FIN = 'fin';
const STORAGE_STATUS_ERROR = 'error';
const ORDER_STATUS_CANCEL = 'cancel';
@ -628,6 +630,21 @@ class OrderStorageAllocationService extends MainService {
continue;
}
if (isInterceptedOrderStatus(orderRow && orderRow.intercept_status)) {
skippedOrders.push({
order_id: orderId,
status: 'skipped',
intercept_status: orderRow.intercept_status,
skipped_reason: 'intercepted',
});
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', {
orderId,
interceptStatus: orderRow.intercept_status,
skippedReason: 'intercepted',
});
continue;
}
if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_FIN) {
skippedOrders.push({
order_id: orderId,

View File

@ -2,6 +2,8 @@
const Service = require('egg').Service;
const { INTERCEPT_STATUS_NONE } = require('../../lib/intercept_guard');
const REVIEWED_INSPECTION_STATUS = 'fin';
const PICK_MODE_VIEW_META_MAP = {
1: {
@ -1945,6 +1947,35 @@ class PickSystemService extends Service {
}
}
// 检查目标订单是否进入拦截流程,拦截订单不允许完成拣货
if (targetOrderIds.length > 0) {
const interceptCheckModel = await this.getOrderModel(warehouseId);
const interceptedOrderRows = await interceptCheckModel.findAll({
where: {
warehouse_id: warehouseId,
id: {
[this.app.Sequelize.Op.in]: targetOrderIds,
},
intercept_status: {
[this.app.Sequelize.Op.ne]: INTERCEPT_STATUS_NONE,
},
},
attributes: [ 'id', 'intercept_status' ],
raw: true,
transaction,
});
if (interceptedOrderRows && interceptedOrderRows.length > 0) {
const detailList = interceptedOrderRows.map(
orderRow => `订单${orderRow.id}(intercept_status=${orderRow.intercept_status})`
).join(';');
throw this.createBusinessError(
`以下订单已被拦截,无法完成拣货:${detailList}`,
400
);
}
}
// 检查目标订单是否已分配储位(storage_status='fin'),防止订单在波次中被取消储位分配后仍然完成拣货
if (targetOrderIds.length > 0) {
const orderModel = await this.getOrderModel(warehouseId);

View File

@ -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<Object|null>} 发送结果
*/
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' : '',

View File

@ -2,6 +2,8 @@
const Service = require('egg').Service;
const { isInterceptedOrderStatus } = require('../../lib/intercept_guard');
class WorkbenchService extends Service {
/**
* 查询工作台列表(仓库隔离 + 软删除过滤)
@ -474,6 +476,11 @@ class WorkbenchService extends Service {
if (!orderRow) throw new Error(`未找到发货单 [${deliveryOrderCode}]`);
// 拦截流程中的订单不允许打包
if (isInterceptedOrderStatus(orderRow.intercept_status)) {
throw new Error(`订单已被拦截,无法打包 [${deliveryOrderCode}]`);
}
const orderId = orderRow.id;
const waveId = orderRow.wave_id || 0;
const actualWaveNo = waveNo || orderRow.wave_no || '';
@ -617,13 +624,13 @@ class WorkbenchService extends Service {
} catch (_err) { continue; }
}
} else if (waveId > 0) {
// 团购:批量更新波次下所有订单
// 团购:批量更新波次下所有订单(拦截订单不更新)
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model) continue;
const affected = await model.update(orderUpdateData, {
where: { wave_id: waveId, warehouse_id: warehouseId },
where: { wave_id: waveId, warehouse_id: warehouseId, intercept_status: 'none' },
});
if (affected[0] > 0) {
ctx.logger.info('[Workbench._packOrder] 团购批量更新订单打包状态 waveId=%d pack_status=%s table=%s affected=%d',
@ -925,7 +932,7 @@ class WorkbenchService extends Service {
if (!model || typeof model.findOne !== 'function') continue;
const row = await model.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [ 'id', 'wave_id', 'wave_no', 'items_weight' ],
attributes: [ 'id', 'wave_id', 'wave_no', 'items_weight', 'intercept_status' ],
raw: true,
});
if (row) {
@ -943,6 +950,11 @@ class WorkbenchService extends Service {
throw new Error(`未找到运单对应的订单 [id=${orderId}, warehouse=${warehouseId}]`);
}
// 拦截流程中的订单不允许称重
if (isInterceptedOrderStatus(orderRow.intercept_status)) {
throw new Error(`订单已被拦截,无法称重 [${normalizedBarcode}]`);
}
const waveId = Number(orderRow.wave_id || 0);
// 步骤3:散单(wave_id=0)→ 仅更新该运单的称重重量
@ -1014,7 +1026,7 @@ class WorkbenchService extends Service {
const { Op } = ctx.app.Sequelize;
const waveOrders = await orderDeliveryModel.findAll({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'id' ],
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
@ -1022,7 +1034,17 @@ class WorkbenchService extends Service {
throw new Error('波次下未找到订单');
}
const orderIds = waveOrders.map(o => Number(o.id));
// 波次内拦截订单不参与批量称重
const interceptedWaveOrderIds = (Array.isArray(waveOrders) ? waveOrders : [])
.filter(o => isInterceptedOrderStatus(o && o.intercept_status))
.map(o => Number(o.id));
const orderIds = (Array.isArray(waveOrders) ? waveOrders : [])
.filter(o => !isInterceptedOrderStatus(o && o.intercept_status))
.map(o => Number(o.id));
if (interceptedWaveOrderIds.length > 0) {
ctx.logger.info('[Workbench._sendWeight] 波次内拦截订单不参与称重 waveId=%d orderIds=%s',
waveId, interceptedWaveOrderIds.join(','));
}
const totalCount = orderIds.length;
await ctx.model.OrderExpress.update(

View File

@ -0,0 +1,117 @@
'use strict';
/**
* inbox.group.reset 群类型清空接口权限记录 + 角色授权迁移。
*
* 权限明细(固定 ID 558,556 已被「运单退回」web 页面占用):
* 558 — inbox.group.reset API:清空群类型配置(重置群)
*
* 角色授权(客服员工及以上链路):
* 30(客服组-员工) → 28(客服组-主管) → 8(经理,通配符 * 自动拥有)
*
* 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。
*/
const TABLE = 'wms_permission';
const ROLE_TABLE = 'wms_role';
const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at';
/** 权限ID → 授权角色ID列表(不含通配符角色) */
const PERMISSION_ROLES = {
558: [ 30, 28, 8 ],
};
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
// ── 1. 创建 API 权限记录(固定 ID)──
const apis = [
[ 558, 'inbox.group.reset', 'API:清空群类型配置' ],
];
for (const [ id, path, metaTitle ] of apis) {
await queryInterface.sequelize.query(
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
{ replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] }
);
}
// ── 2. 角色授权注入 ──
for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) {
for (const roleId of PERMISSION_ROLES[permId]) {
const rows = await queryInterface.sequelize.query(
`SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`,
{ replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT }
);
const record = Array.isArray(rows) ? rows[0] : null;
if (!record) {
continue;
}
// 通配符角色跳过
if (record.permissions === '*') {
continue;
}
let perms;
try {
perms = typeof record.permissions === 'string'
? JSON.parse(record.permissions)
: record.permissions;
} catch (e) {
perms = null;
}
if (!Array.isArray(perms)) {
continue;
}
if (!perms.includes(permId)) {
perms.push(permId);
perms.sort((a, b) => Number(a) - Number(b));
await queryInterface.sequelize.query(
`UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`,
{ replacements: [ JSON.stringify(perms), roleId ] }
);
}
}
}
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.sequelize.query(
'DELETE FROM `wms_permission` WHERE id = 558'
);
const roleIds = [ 30, 28, 8 ];
for (const roleId of roleIds) {
const rows = await queryInterface.sequelize.query(
`SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`,
{ replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT }
);
const record = Array.isArray(rows) ? rows[0] : null;
if (!record || record.permissions === '*') {
continue;
}
let perms;
try {
perms = typeof record.permissions === 'string'
? JSON.parse(record.permissions)
: record.permissions;
} catch (e) {
perms = null;
}
if (!Array.isArray(perms) || !perms.includes(558)) {
continue;
}
perms = perms.filter(p => p !== 558);
await queryInterface.sequelize.query(
`UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`,
{ replacements: [ JSON.stringify(perms), roleId ] }
);
}
},
};

View File

@ -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"
}
]

View File

@ -1,4 +1,35 @@
[
{
"version": "2026.08.17-inbox-group-reset",
"date": "2026-08-17",
"type": "enhanced",
"summary": "新增 inbox.group.reset 群操作接口:入参群记录主键ID,清空群类型配置(group_type/sub_type/store_id/express_interfaces/system_express_code 置空、ai_enabled 重置为0),仅保留群创建时信息(群名称/群ID/仓库/来源/屏蔽状态/扩展数据)",
"methods": [
"inbox.group.reset"
],
"notes": [
"app/service/systems/inbox/group.js reset:仓库隔离按主键 id 定位群,清空类型相关字段并写操作日志,返回重置后群信息",
"app/service/systemMethods/inbox.js 新增 groupReset,注册到 inbox.group 子入口",
"数据库迁移 20260817120000-add-inbox-group-reset-permission.js:权限ID 556 授权角色 8/26/28/29",
"同步更新 methods/system.json 中 inbox.group.reset 接口文档"
],
"module": "inbox.group"
},
{
"version": "2026.08.17-afterSale-handleWorkOrder-remark-notify-group",
"date": "2026-08-17",
"type": "enhanced",
"summary": "afterSale.handleWorkOrder 处理备注同步发送到对应货主售后群:填写 remark 时推送到货主售后群(工单 store_id 定位,缺失时从来源消息所在群反查货主,不转发快递群);消息内容格式为「【工单 售后单号】处理备注:备注内容」;响应新增 notified_groups 返回发送群数量",
"methods": [
"afterSale.handleWorkOrder"
],
"notes": [
"app/service/systems/afterSale.js handleWorkOrder:新增 notifyGroup 参数(方法层交互处理传 true,内部自动处理如库内拦截/退回已收到不传),事务提交后按 remark 非空发送:store_id 定位货主 → findStoreAfterSalesGroups 发货主售后群;无 store_id 时按 inbox_message_id 查来源消息 group_id → InboxGroup 反查 store_id 再发送;发送失败仅告警不影响处理结果",
"app/service/systemMethods/afterSale.js handleWorkOrder:调用 systems 层时传 notifyGroup: true",
"同步更新 methods/system.json 中 afterSale.handleWorkOrder 的 description、remark 参数说明与 notified_groups 响应说明"
],
"module": "afterSale"
},
{
"version": "2026.08.16-waybill-createAt-between",
"date": "2026-08-16",

View File

@ -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"
}
]

View File

@ -33703,6 +33703,47 @@
}
]
},
{
"method": "inbox.group.reset",
"description": "清空群类型配置:清空群类型/子类型/货主/快递接口/系统快递编码,AI开关重置关闭,仅保留群创建时信息(群名称/群ID/仓库/来源/屏蔽状态/扩展数据)。入参群记录主键ID",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
}
],
"params": [
{
"name": "id",
"type": "number",
"required": true,
"source": "body",
"description": "群记录主键ID"
}
],
"response": [
{
"name": "message",
"type": "string",
"required": true,
"description": "操作结果提示:群类型配置已清空"
}
],
"errors": [
{
"code": "400",
"message": "群ID无效"
},
{
"code": "500",
"message": "群不存在或无权限操作"
}
]
},
{
"method": "inbox.group.messages",
"description": "按群拉取消息列表,支持方向/关键词筛选,分页返回。warehouseId服务端自动注入,查询命中idx_warehouse_group_created索引",
@ -34582,7 +34623,7 @@
},
{
"method": "afterSale.handleWorkOrder",
"description": "处理售后工单:写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动将 role_group 回退到 customer_service;status=completed 时自动写入 resolution + resolved_at。步骤 action 由服务端固定为\"处理工单\",step_status 与主表 status 完全一致。status 不填或填错时默认 processing。新增 pending_feedback 状态用于内部处理完成等待外部反馈(如已将拦截信息发给运方,等待运方反馈后再决定是否继续处理)。",
"description": "处理售后工单:写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动将 role_group 回退到 customer_service;status=completed 时自动写入 resolution + resolved_at。步骤 action 由服务端固定为\"处理工单\",step_status 与主表 status 完全一致。status 不填或填错时默认 processing。新增 pending_feedback 状态用于内部处理完成等待外部反馈(如已将拦截信息发给运方,等待运方反馈后再决定是否继续处理)。填写处理备注(remark)时会同步发送到对应的货主售后群(工单无 store_id 时从来源消息所在群反查货主,不转发快递群),响应 notified_groups 返回发送的群数量。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
@ -34606,7 +34647,7 @@
"type": "string",
"required": false,
"source": "body",
"description": "处理备注"
"description": "处理备注。填写后同步发送到对应的货主售后群,内容格式:\"【工单 售后单号】处理备注:备注内容\""
},
{
"name": "attachment_ids",
@ -34628,6 +34669,12 @@
"type": "integer",
"required": true,
"description": "售后工单ID"
},
{
"name": "notified_groups",
"type": "integer",
"required": false,
"description": "处理备注发送到的货主售后群数量(未填写备注或未找到货主售后群时为0)"
}
],
"errors": []

View File

@ -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);
});