Compare commits

...

4 Commits

9 changed files with 501 additions and 85 deletions

View File

@ -41,7 +41,8 @@ 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: 'receiving_store_bound', name: '收货单创建/绑定货主', business: 'receiving', description: '收货单创建或首次绑定货主时的通知(展示车牌号/快递单号登记状态,未登记显示无)' }),
Object.freeze({ code: 'receiving_store_unmatched', 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

@ -1545,7 +1545,7 @@ class WaveService extends OrderBaseService {
* 构建波次列表 where 条件(白名单字段)。
*
* @param {Object} whereData 查询 where 入参。
* @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string }} SQL 条件片段、参数与分配状态筛选值。
* @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string, reviewAssignmentStatus: string, storeIds: number[] }} SQL 条件片段、参数与分配状态筛选值。
*/
buildBatchListWhereClause(whereData = {}) {
const normalizedWhere = this.isPlainObject(whereData) ? whereData : {};
@ -1576,6 +1576,7 @@ class WaveService extends OrderBaseService {
'express_assignment_status',
'print_assignment_status',
'review_assignment_status',
'store_id',
];
const invalidFields = whereKeys.filter(key => !allowedFields.includes(key));
@ -1700,6 +1701,37 @@ class WaveService extends OrderBaseService {
appendMinCondition('processed_orders_min', 'processed_orders', 'whereProcessedOrdersMin');
appendMaxCondition('processed_orders_max', 'processed_orders', 'whereProcessedOrdersMax');
// store_id 货主筛选:支持单值/数组/{operator,value} 结构,归一化为正整数数组(去重)。
// 过滤语义:返回包含任一筛选货主订单的波次(含混合货主波次)。
const normalizeStoreIdList = value => {
if (value === undefined || value === null || value === '') {
return [];
}
const rawValue = this.isPlainObject(value) && Object.prototype.hasOwnProperty.call(value, 'value')
? value.value
: value;
const sourceList = Array.isArray(rawValue) ? rawValue : [ rawValue ];
const normalizedIds = [];
for (const item of sourceList) {
if (item === undefined || item === null || item === '') {
continue;
}
const numberValue = Number(String(item).trim());
if (!Number.isInteger(numberValue) || numberValue <= 0) {
throw new Error('store_id 参数不合法');
}
normalizedIds.push(numberValue);
}
return [ ...new Set(normalizedIds) ];
};
const storeIds = normalizeStoreIdList(normalizedWhere.store_id);
const storageAssignmentStatus = this.normalizeBatchListStorageAssignmentStatusFilter(
normalizedWhere.storage_assignment_status
);
@ -1720,6 +1752,7 @@ class WaveService extends OrderBaseService {
expressAssignmentStatus,
printAssignmentStatus,
reviewAssignmentStatus,
storeIds,
};
}
@ -4265,6 +4298,83 @@ class WaveService extends OrderBaseService {
});
}
/**
* 解析波次列表的货主名称映射(store_id → 名称)。
*
* 货主名称口径与售后/库存列表一致:合约表 wms_store_warehouse.store_remask
* (货主备注名称,store_id+warehouse_id 维度)优先,无合约或备注为空时回退
* wms_store.company_name(公司全称)。
*
* @param {Object[]} batchRows 波次行数据(含 order_total/owner_distinct_count/owner_named_count/owner_store_id)。
* @param {number|string} [warehouseId=0] 当前仓库ID。
* @return {Promise<Map<number, string>>} store_id → 货主名称。
*/
async resolveWaveBatchOwnerStoreNameMap(batchRows = [], warehouseId = 0) {
const nameMap = new Map();
const ownerStoreIds = [];
for (const batch of batchRows) {
const orderCount = Number(batch && batch.order_total || 0);
const ownerDistinctCount = Number(batch && batch.owner_distinct_count || 0);
const ownerNamedCount = Number(batch && batch.owner_named_count || 0);
const ownerStoreId = Number(batch && batch.owner_store_id || 0);
if (orderCount > 0 && ownerDistinctCount === 1 && ownerNamedCount === orderCount && ownerStoreId > 0) {
ownerStoreIds.push(ownerStoreId);
}
}
const uniqueStoreIds = [ ...new Set(ownerStoreIds) ];
if (uniqueStoreIds.length === 0) {
return nameMap;
}
const normalizedWarehouseId = Number(warehouseId || 0);
try {
// 1. 合约表货主备注名称(store_id + warehouse_id 维度)
const contractMap = new Map();
if (normalizedWarehouseId > 0) {
const contractRows = await this.ctx.model.StoreWarehouse.findAll({
where: {
store_id: { [Op.in]: uniqueStoreIds },
warehouse_id: normalizedWarehouseId,
},
attributes: [ 'store_id', 'store_remask' ],
raw: true,
});
for (const row of contractRows) {
const remask = String(row.store_remask || '').trim();
if (remask) {
contractMap.set(Number(row.store_id), remask);
}
}
}
// 2. 货主公司全称兜底
const storeRows = await this.ctx.model.Store.findAll({
where: { id: { [Op.in]: uniqueStoreIds } },
attributes: [ 'id', 'company_name' ],
raw: true,
});
for (const row of storeRows) {
const companyName = String(row.company_name || '').trim();
if (companyName) {
nameMap.set(Number(row.id), companyName);
}
}
// 3. 备注名称覆盖公司全称
for (const storeId of uniqueStoreIds) {
if (contractMap.has(storeId)) {
nameMap.set(storeId, contractMap.get(storeId));
}
}
} catch (error) {
this.ctx.logger?.warn?.('resolveWaveBatchOwnerStoreNameMap 解析货主名称失败:', error?.message || error);
}
return nameMap;
}
/**
* 波次列表查询。
*
@ -4300,6 +4410,20 @@ class WaveService extends OrderBaseService {
AND wave_status IN (:waveStatusList)
${whereClause.sql}
`;
const storeIdFilter = Array.isArray(whereClause.storeIds) ? whereClause.storeIds : [];
const ownerFilterJoinSql = storeIdFilter.length > 0 ? `
INNER JOIN (
SELECT candidate_wave.wave_id
FROM (
SELECT wave_id
FROM wms_wave_batch
WHERE ${baseBatchWhereSql}
) candidate_wave
INNER JOIN ${orderTableName} od ON od.wave_id = candidate_wave.wave_id
AND od.store_id IN (:whereStoreIds)
GROUP BY candidate_wave.wave_id
) wave_owner_filter ON wave_owner_filter.wave_id = wb.wave_id
` : '';
const batchListFromSql = `
FROM (
SELECT
@ -4337,7 +4461,10 @@ class WaveService extends OrderBaseService {
SUM(CASE WHEN od.inspection_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS review_none_count,
SUM(CASE WHEN od.pick_status = 'none' THEN 1 ELSE 0 END) AS pick_none_count,
SUM(CASE WHEN od.pick_status = 'fin' THEN 1 ELSE 0 END) AS pick_fin_count,
SUM(CASE WHEN od.pick_status = 'error' THEN 1 ELSE 0 END) AS pick_error_count
SUM(CASE WHEN od.pick_status = 'error' THEN 1 ELSE 0 END) AS pick_error_count,
COUNT(DISTINCT NULLIF(od.store_id, 0)) AS owner_distinct_count,
MAX(NULLIF(od.store_id, 0)) AS owner_store_id,
SUM(CASE WHEN NULLIF(od.store_id, 0) IS NOT NULL THEN 1 ELSE 0 END) AS owner_named_count
FROM (
SELECT wave_id
FROM wms_wave_batch
@ -4346,6 +4473,7 @@ class WaveService extends OrderBaseService {
LEFT JOIN ${orderTableName} od ON od.wave_id = candidate_wave.wave_id
GROUP BY candidate_wave.wave_id
) wave_order_stats ON wave_order_stats.wave_id = wb.wave_id
${ownerFilterJoinSql}
LEFT JOIN wms_express e ON e.code = wb.logistics_name
WHERE 1 = 1
${storageAssignmentFilterClause.sql}
@ -4386,7 +4514,10 @@ class WaveService extends OrderBaseService {
COALESCE(wave_order_stats.review_none_count, 0) AS review_none_count,
COALESCE(wave_order_stats.pick_none_count, 0) AS pick_none_count,
COALESCE(wave_order_stats.pick_fin_count, 0) AS pick_fin_count,
COALESCE(wave_order_stats.pick_error_count, 0) AS pick_error_count
COALESCE(wave_order_stats.pick_error_count, 0) AS pick_error_count,
COALESCE(wave_order_stats.owner_distinct_count, 0) AS owner_distinct_count,
wave_order_stats.owner_store_id,
COALESCE(wave_order_stats.owner_named_count, 0) AS owner_named_count
${batchListFromSql}
ORDER BY wb.total_orders DESC, wb.wave_id DESC
LIMIT :limit OFFSET :offset
@ -4407,6 +4538,7 @@ class WaveService extends OrderBaseService {
...expressAssignmentFilterClause.replacements,
...printAssignmentFilterClause.replacements,
...reviewAssignmentFilterClause.replacements,
...(storeIdFilter.length > 0 ? { whereStoreIds: storeIdFilter } : {}),
limit: pageSize,
offset,
},
@ -4420,6 +4552,7 @@ class WaveService extends OrderBaseService {
...expressAssignmentFilterClause.replacements,
...printAssignmentFilterClause.replacements,
...reviewAssignmentFilterClause.replacements,
...(storeIdFilter.length > 0 ? { whereStoreIds: storeIdFilter } : {}),
},
}),
]);
@ -4443,6 +4576,8 @@ class WaveService extends OrderBaseService {
});
}
const ownerStoreNameMap = await this.resolveWaveBatchOwnerStoreNameMap(rawList, warehouseId);
const list = rawList.map(batch => {
const waveId = Number(batch && batch.wave_id || 0);
const orderCount = Number(batch && batch.order_total || 0);
@ -4460,6 +4595,17 @@ class WaveService extends OrderBaseService {
const reviewFinCount = Number(batch && batch.review_fin_count || 0);
const reviewErrorCount = Number(batch && batch.review_error_count || 0);
const unreviewedOrderCount = orderCount - reviewFinCount;
const ownerDistinctCount = Number(batch && batch.owner_distinct_count || 0);
const ownerNamedCount = Number(batch && batch.owner_named_count || 0);
const ownerStoreId = Number(batch && batch.owner_store_id || 0);
// 货主展示:仅当所有订单均存在货主(store_id)且货主唯一时返回货主名称,否则返回“混合”。
const ownerName = orderCount > 0
&& ownerDistinctCount === 1
&& ownerNamedCount === orderCount
&& ownerStoreId > 0
? (ownerStoreNameMap.get(ownerStoreId) || '')
: '混合';
// 复核状态判定:error 统一归入未复核
let reviewAssignmentStatus;
@ -4506,6 +4652,7 @@ class WaveService extends OrderBaseService {
}),
review_assignment_status: reviewAssignmentStatus,
unreviewed_order_count: unreviewedOrderCount,
store_name: ownerName,
};
});

View File

@ -797,22 +797,18 @@ class DeliveryOrderService extends Service {
};
// ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) =====
// enable_external_express_code 开启时以外部快递匹配结果为准(匹配不到已在 resolveExpressSnapshot 兜底默认快递),跳过策略漏斗覆盖
// enable_external_express_code 开启时仅"纯货主维度"策略参与漏斗,命中后覆盖外部快递匹配结果;
// 关闭时全维度策略参与,沿用原有逻辑
try {
const funnelPolicyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId);
const enableExternalExpressCode = this.resolveEnableExternalExpressCode(funnelPolicyConfig, funnelPolicyConfig);
if (enableExternalExpressCode) {
ctx.logger.info('[ExpressPolicyMatch] enable_external_express_code 开启,跳过快递策略漏斗,保留外部快递匹配或兜底结果', {
orderId,
orderCode: deliveryOrder.deliveryOrderCode,
logisticsCode: orderData.logistics_code,
sysLogisticsCode: orderData.sys_logistics_code,
});
}
const receiverInfo = deliveryOrder.receiverInfo;
const shopNick = deliveryOrder.shopNick;
const hasEnoughData = !enableExternalExpressCode
&& (shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city)));
// 外部编码开启:仅需货主ID即可参与漏斗(只匹配纯货主维度策略);
// 外部编码关闭:需 shopNick 或收货省/市信息
const hasEnoughData = enableExternalExpressCode
? Boolean(info.storeId)
: Boolean(shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city)));
if (hasEnoughData) {
const address = [
@ -834,6 +830,10 @@ class DeliveryOrderService extends Service {
prohibitedTypeIds: itemsInfo && Array.isArray(itemsInfo.prohibited_type_ids)
? itemsInfo.prohibited_type_ids
: null,
},
{
// 启用外部编码时仅匹配纯货主维度策略,命中后覆盖外部快递映射结果
onlyStoreDimension: enableExternalExpressCode,
}
);
@ -904,7 +904,9 @@ class DeliveryOrderService extends Service {
this.appendOrderOperationLog(
operationLogs,
ORDER_OPERATION_CODES.EXPRESS_FALLBACK,
`未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}`
enableExternalExpressCode
? `未命中货主快递策略,保留外部快递: ${fallbackName || fallbackCode}`
: `未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}`
);
}
}

View File

@ -177,6 +177,27 @@ class ExpressPolicyService extends Service {
return policyArray.some(v => Number(v) === Number(value));
}
/**
* 判断策略是否为"纯货主维度"策略:
* store_ids 非空,且 shop_name / prohibited_type_id / regions / exclude_regions / 重量区间全部未限定。
*
* @param {Object} policy 策略行
* @return {boolean} 是否为纯货主策略
*/
_isStoreOnlyPolicy(policy = {}) {
const asArray = v => (Array.isArray(v) ? v : []);
if (asArray(policy.store_ids).length === 0) {
return false;
}
const hasOtherDimension = asArray(policy.shop_name).length > 0
|| asArray(policy.prohibited_type_id).length > 0
|| asArray(policy.regions).length > 0
|| asArray(policy.exclude_regions).length > 0
|| (policy.min_weight_g !== null && policy.min_weight_g !== undefined)
|| (policy.max_weight_g !== null && policy.max_weight_g !== undefined);
return !hasOtherDimension;
}
/**
* 按策略优先级漏斗筛选,返回命中策略的快递编码与重量段类型。
*
@ -195,9 +216,11 @@ class ExpressPolicyService extends Service {
* @param {Array<number>} [params.prohibitedTypeIds] 商品违禁品类型 ID 数组
* @param {string} [params.address] 省市区详细地址(单个字符串)
* @param {number} [params.weight] 重量(克)
* @return {Promise<{expressCode: string|null, weightType: number|null}>}
* @param {Object} [options] 匹配选项
* @param {boolean} [options.onlyStoreDimension=false] 仅匹配"纯货主维度"策略(store_ids 非空且其它维度全空)
* @return {Promise<{expressCode: string|null, weightType: number|null}>} 命中策略的快递编码与重量段类型,未命中时 expressCode 为 null
*/
async matchPolicy(warehouseId, params = {}) {
async matchPolicy(warehouseId, params = {}, options = {}) {
const {
storeId,
customShopName,
@ -205,6 +228,7 @@ class ExpressPolicyService extends Service {
address,
weight,
} = params;
const { onlyStoreDimension = false } = options;
const policies = await this.getWarehousePolicies(warehouseId);
if (!Array.isArray(policies) || policies.length === 0) {
@ -212,6 +236,11 @@ class ExpressPolicyService extends Service {
}
for (const policy of policies) {
// 0) 维度白名单:onlyStoreDimension 开启时跳过非纯货主策略
if (onlyStoreDimension && !this._isStoreOnlyPolicy(policy)) {
continue;
}
// 1) store_ids — 未限定(NULL)视为不限;否则传入 storeId 必须在范围内
if (!this._matchValueInArray(policy.store_ids, storeId)) {
continue;

View File

@ -27,6 +27,7 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([
'receiving_rejected',
'receiving_reviewed',
'receiving_store_bound',
'receiving_store_unmatched',
'order_cancel_intercepted',
'wave_strategy_quick_scan_failed',
'store_warehouse_print_quantity_adjusted',
@ -63,6 +64,15 @@ const FIXED_GROUP_SUBSCRIPTIONS = Object.freeze({
]),
}),
]),
receiving_store_unmatched: 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' }),
]),

View File

@ -1190,33 +1190,33 @@ class ReceivingService extends Service {
reviewer: reviewerName,
});
// 1. 发送文字通知
// 0. 加载明细并反查货主商品编码(通知文案与报表共用,失败不影响主流程)
let details = [];
let itemCodeMap = new Map();
try {
const textResult = await this.sendReviewNotice({ receiving: receivingSnapshot, reviewer });
ctx.logger.info('[receiving.reviewReceiving] 文字通知结果', {
details = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: r.id },
});
itemCodeMap = await this.resolveReviewDetailItemCodeMap(details);
} catch (detailErr) {
ctx.logger.error('[receiving.reviewReceiving] 加载明细失败', {
receiving_id: r.id,
receiving_number: r.receiving_number,
success: !!(textResult && textResult.success),
message: textResult && textResult.message,
matchedHookCount: Number(textResult && textResult.data && textResult.data.matchedHookCount || 0),
sentCount: Number(textResult && textResult.data && textResult.data.sentCount || 0),
failedCount: Number(textResult && textResult.data && textResult.data.failedCount || 0),
});
} catch (textErr) {
ctx.logger.error('[receiving.reviewReceiving] 文字通知发送失败', {
receiving_id: r.id,
error: textErr.message,
error: detailErr.message,
});
}
// 2. 加载明细与图片,生成 Excel 报表
// 1. 加载明细与图片,生成 Excel 报表(复用步骤 0 已加载的明细,为空时回退重新查询)
let reviewReport = null;
try {
const details = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: r.id },
});
let reportDetails = details;
if (reportDetails.length === 0) {
reportDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: r.id },
});
}
const detailIds = details.map(d => String(d.id));
const detailIds = reportDetails.map(d => String(d.id));
const detailImageMap = new Map();
if (detailIds.length > 0) {
const detailImageRefs = await ctx.model.FileReference.findAll({
@ -1239,10 +1239,10 @@ class ReceivingService extends Service {
});
const stats = {
total_details: details.length,
matched_details: details.filter(d => d.system_product_id).length,
unmatched_details: details.filter(d => !d.system_product_id).length,
total_quantity: details.reduce((sum, d) => sum + (d.actual_quantity || 0), 0),
total_details: reportDetails.length,
matched_details: reportDetails.filter(d => d.system_product_id).length,
unmatched_details: reportDetails.filter(d => !d.system_product_id).length,
total_quantity: reportDetails.reduce((sum, d) => sum + (d.actual_quantity || 0), 0),
};
const excelService = ctx.service && ctx.service.systems && ctx.service.systems.excel;
@ -1257,7 +1257,7 @@ class ReceivingService extends Service {
businessId: r.id,
expireDays: 90,
sheets: this.buildReviewReportSheets({
receiving: { ...receivingSnapshot, details },
receiving: { ...receivingSnapshot, details: reportDetails },
reviewer,
stats,
detailImageMap,
@ -1273,32 +1273,37 @@ class ReceivingService extends Service {
url: reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || ''),
});
} catch (reportErr) {
ctx.logger.error('[receiving.reviewReceiving] Excel报表生成失败,跳过文件通知', {
ctx.logger.error('[receiving.reviewReceiving] Excel报表生成失败,回退正文展示明细列表', {
receiving_id: r.id,
error: reportErr.message,
});
}
// 3. 发送文件通知(仅当 Excel 上传成功时)
if (reviewReport) {
try {
const fileResult = await this.sendReviewNotice({ receiving: receivingSnapshot, reviewer, reviewReport });
ctx.logger.info('[receiving.reviewReceiving] 文件通知结果', {
receiving_id: r.id,
receiving_number: r.receiving_number,
success: !!(fileResult && fileResult.success),
message: fileResult && fileResult.message,
matchedHookCount: Number(fileResult && fileResult.data && fileResult.data.matchedHookCount || 0),
sentCount: Number(fileResult && fileResult.data && fileResult.data.sentCount || 0),
failedCount: Number(fileResult && fileResult.data && fileResult.data.failedCount || 0),
reportUrl: reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || '',
});
} catch (fileErr) {
ctx.logger.error('[receiving.reviewReceiving] 文件通知发送失败', {
receiving_id: r.id,
error: fileErr.message,
});
}
// 2. 发送审核完成通知:Excel 生成成功直接带下载链接,失败则回退正文展示全部明细
try {
const noticeResult = await this.sendReviewNotice({
receiving: receivingSnapshot,
reviewer,
reviewReport,
details,
itemCodeMap,
});
ctx.logger.info('[receiving.reviewReceiving] 审核完成通知结果', {
receiving_id: r.id,
receiving_number: r.receiving_number,
hasReport: !!reviewReport,
success: !!(noticeResult && noticeResult.success),
message: noticeResult && noticeResult.message,
matchedHookCount: Number(noticeResult && noticeResult.data && noticeResult.data.matchedHookCount || 0),
sentCount: Number(noticeResult && noticeResult.data && noticeResult.data.sentCount || 0),
failedCount: Number(noticeResult && noticeResult.data && noticeResult.data.failedCount || 0),
reportUrl: reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || ''),
});
} catch (noticeErr) {
ctx.logger.error('[receiving.reviewReceiving] 审核完成通知发送失败', {
receiving_id: r.id,
error: noticeErr.message,
});
}
ctx.logger.info('[receiving.reviewReceiving] 单据通知处理完成', {
@ -1494,8 +1499,8 @@ class ReceivingService extends Service {
}
/**
* 发送收货单创建/首次绑定货主通知(receiving_store_bound),提醒货主确认/补填车牌号或快递单号。
* 已填写车牌号或快递单号时,文案展示已登记信息;均未填写时才提示及时补充。
* 发送收货单创建/首次绑定货主通知(receiving_store_bound)。
* 车牌号/快递单号始终展示登记状态:已登记显示「车牌号:X 已登记」「快递单号:X 已登记」,未登记显示「车牌号:无」「快递单号:无」。
* 路由由 notice 固定订阅回退链处理:货主收货群 → 无则货主售后群 → 均无则仓库异常群。
* @param {Object} options 发送参数
* @param {Object} options.receiving 收货单快照
@ -1525,16 +1530,10 @@ class ReceivingService extends Service {
const licensePlate = String(receiving.license_plate || '').trim();
const trackingNumber = String(receiving.tracking_number || '').trim();
const vehicleInfoLines = [];
if (licensePlate) {
vehicleInfoLines.push(`车牌号:${licensePlate} 已登记`);
}
if (trackingNumber) {
vehicleInfoLines.push(`快递单号:${trackingNumber} 已登记`);
}
if (vehicleInfoLines.length === 0) {
vehicleInfoLines.push('请确认是否已填写车牌号或快递单号,未填写请及时补充');
}
const vehicleInfoLines = [
licensePlate ? `车牌号:${licensePlate} 已登记` : '车牌号:无',
trackingNumber ? `快递单号:${trackingNumber} 已登记` : '快递单号:无',
];
const contentLines = [
`收货单号:${receivingNumber} 正在收货`,
@ -1579,12 +1578,16 @@ class ReceivingService extends Service {
* @param {Object} options.receiving 收货单快照
* @param {Object} [options.reviewer={}] 审核人信息
* @param {Object|null} [options.reviewReport=null] 审核报表(有值则发文件通知)
* @param {Array<Object>|null} [options.details=null] 收货明细列表(用于通知文案展示全部明细)
* @param {Map<number, string>|null} [options.itemCodeMap=null] system_product_id → item_code 映射
* @return {Promise<Object|null>} 发送结果
*/
async sendReviewNotice({
receiving,
reviewer = {},
reviewReport = null,
details = null,
itemCodeMap = null,
} = {}) {
const { ctx } = this;
const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice;
@ -1609,13 +1612,23 @@ class ReceivingService extends Service {
(reviewReport && (reviewReport.filename || reviewReport.fileKey || reviewReport.key)) || `审核明细_${receivingNumber}.xlsx`
).trim();
const content = [
`收货单号:${receivingNumber}`,
`货主:${receiving.store_name || '未知'}`,
`审核人:${reviewerName || '未知'}`,
`审核时间:${this.formatReportDate(receiving.updated_at || new Date())}`,
`备注:${receiving.remark || '无'}`,
].join('\n') + '。';
const detailList = Array.isArray(details) ? details : [];
const codeMap = itemCodeMap instanceof Map ? itemCodeMap : new Map();
const productLines = detailList.map((detail, index) => {
const stockId = Number(detail.system_product_id || 0);
const itemCode = (stockId > 0 && codeMap.get(stockId)) || String(detail.barcode || '').trim() || '未知编码';
const productName = String(detail.product_name || '').trim() || '未知商品';
const quantity = Number(detail.actual_quantity || 0);
return `${index + 1}.${itemCode} ${productName} ${quantity}`;
});
const contentLines = [ `收货单号:${receivingNumber} 完成收货审核` ];
if (reportUrl) {
contentLines.push('', `审核明细下载:${reportUrl}`);
} else if (productLines.length > 0) {
contentLines.push('', '商品:', ...productLines);
}
contentLines.push('', '请及时提交入库单入库');
const content = contentLines.join('\n') + '。';
return await noticeService.send({
warehouseId,
@ -1624,7 +1637,7 @@ class ReceivingService extends Service {
businessName: 'receiving',
event: 'receiving_reviewed',
channel: 'warehouse',
title: `收货单${receivingNumber}审核完成`,
title: `收货单${receivingNumber}完成收货审核`,
content,
url: reportUrl || undefined,
fileName: reportUrl ? reportFileName : '',
@ -1648,6 +1661,42 @@ class ReceivingService extends Service {
});
}
/**
* 反查货主商品编码:收货明细 system_product_id 对应 wms_stock_store.stock_id,取 item_code 作为商品编码。
* @param {Array<Object>} details 收货明细列表(含 system_product_id)
* @return {Promise<Map<number, string>>} system_product_id → item_code
*/
async resolveReviewDetailItemCodeMap(details = []) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const codeMap = new Map();
if (!Array.isArray(details) || details.length === 0) return codeMap;
const stockIds = [ ...new Set(
details.map(detail => Number(detail.system_product_id || 0)).filter(id => Number.isFinite(id) && id > 0)
) ];
if (stockIds.length === 0) return codeMap;
const rows = await ctx.model.StockStore.findAll({
where: {
stock_id: { [Op.in]: stockIds },
delete_at: null,
},
attributes: [ 'stock_id', 'item_code' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
rows.forEach(row => {
const stockId = Number(row.stock_id);
if (!stockId || codeMap.has(stockId)) return;
const itemCode = String(row.item_code || '').trim();
if (itemCode) codeMap.set(stockId, itemCode);
});
return codeMap;
}
isEmptyValue(value) {
if (value === undefined || value === null) {
return true;
@ -4309,6 +4358,76 @@ class ReceivingService extends Service {
});
}
/**
* 发送收货完成未匹配商品货主通知(receiving_store_unmatched),提醒货主核实未匹配商品资料。
* 路由由 notice 固定订阅回退链处理:货主收货群 → 无则货主售后群 → 均无则仓库异常群。
* @param {Object} options 发送参数
* @param {Object} options.receiving 收货单快照
* @param {Array<Object>} [options.unmatchedDetails=[]] 未匹配明细列表(含 barcode/product_name)
* @return {Promise<Object|null>} 发送结果
*/
async sendStoreUnmatchedNotice({ receiving, unmatchedDetails = [] } = {}) {
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 || !Array.isArray(unmatchedDetails) || unmatchedDetails.length === 0) {
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 storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim();
const barcodeLines = unmatchedDetails.map((detail, index) => `${index + 1}.${String(detail.barcode || '').trim() || '无条码'},`);
const contentLines = [
`收货单号:${receivingNumber} 提交完成收货,有未匹配商品资料`,
'条码:',
...barcodeLines,
'核实是否是新商品未推送资料',
`详情以及收货图片查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}`,
'如果没有账户请联系人工客服开通',
];
const content = contentLines.join('\n') + '。';
return await noticeService.send({
warehouseId,
storeId,
messageType: 'text',
businessName: 'receiving',
event: 'receiving_store_unmatched',
channel: 'warehouse',
title: `收货单${receivingNumber}有未匹配商品资料`,
content,
storeContent: content,
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,
unmatchedBarcodes: unmatchedDetails.map(detail => detail.barcode || ''),
},
});
}
/**
* 完成收货单:校验明细、更新状态并写入库存。
* @param {Object} data 请求体
@ -4619,6 +4738,33 @@ class ReceivingService extends Service {
});
}
// 11.1 存在未匹配商品明细且已绑定货主时,通知货主核实商品资料(失败不影响主流程)
if (unmatchedDetails.length > 0 && Number(receiving.store_id || 0) > 0) {
try {
const unmatchedNoticeResult = await this.sendStoreUnmatchedNotice({
receiving: receivingSnapshot,
unmatchedDetails: unmatchedDetails.map(detail => ({
barcode: detail.barcode,
product_name: detail.product_name,
})),
});
ctx.logger.info('收货完成未匹配商品货主通知结果', {
receiving_id: id,
receiving_number: receiving.receiving_number,
warehouseId,
unmatchedCount: unmatchedDetails.length,
success: !!(unmatchedNoticeResult && unmatchedNoticeResult.success),
message: unmatchedNoticeResult && unmatchedNoticeResult.message,
});
} catch (notifyError) {
ctx.logger.error(`收货完成未匹配商品货主通知发送失败: ${notifyError.message}`, {
receiving_id: id,
warehouseId,
error: notifyError.stack,
});
}
}
ctx.logger.info('收货单已完成', {
receiving_id: id,
receiving_number: receiving.receiving_number,

View File

@ -1,4 +1,38 @@
[
{
"version": "2026.08.26-wave-batchList-store-id-filter",
"date": "2026-08-26",
"type": "enhanced",
"summary": "order.wave.batchList 新增 where.store_id(货主ID)过滤:支持单值/数组/{operator,value} 结构(正整数),返回包含任一筛选货主订单的波次(含混合货主波次);未在 wms_wave_batch 加冗余 store_id 字段,通过订单分表 INNER JOIN 聚合匹配,零迁移零回填零口径漂移风险。",
"methods": [
"order.wave.batchList"
],
"notes": [
"app/service/systemMethods/order/wave.js buildBatchListWhereClause:allowedFields 新增 store_id,normalizeStoreIdList 归一化(单值/数组/{operator,value}→正整数数组去重,非法值抛错),返回值新增 storeIds",
"batchList:storeIds 非空时在 wave_order_stats 之后追加 INNER JOIN wave_owner_filter(订单表 od.wave_id 匹配且 od.store_id IN (:whereStoreIds) 按 wave_id 分组),listSql/countSql replacements 新增 whereStoreIds",
"设计决策:不在 wms_wave_batch 增加 store_id 冗余字段(混合填0),理由——batchList 原本就必须 LEFT JOIN 订单表做状态聚合,货主过滤挂同一次 JOIN 零额外成本;订单表已有 store_id 单列索引;冗余需覆盖抓取入波/策略任务建波/batchRemoveOrders/batchRemoveExceptionOrders 等 10+ 处写入点维护,遗漏即口径漂移;owner_name 展示已实时聚合订单 store_id,避免双口径",
"实测:{operator:'',value:[1000281,1000000]} 过滤 wave_type=1&source=0 返回 196 条(库中该货主订单波次);单值/数组形式均返回 5 条;不存在货主 0 条;非法值报错;无过滤 baseline 278 条不受影响;原请求含 wave_status=0 返回 0 因库中活动波次均为 status=1",
"同步更新 methods/system.json 的 batchList where 白名单说明"
],
"module": "order.wave"
},
{
"version": "2026.08.26-wave-batchList-store-name",
"date": "2026-08-26",
"type": "enhanced",
"summary": "order.wave.batchList 响应每条记录新增 store_name(货主信息):按波次内订单 store_id(货主ID)聚合,所有订单均为同一货主时返回货主名称,否则(多个货主、存在无货主订单或空波次)返回“混合”;货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),无合约或备注为空时回退 wms_store.company_name(公司全称)。",
"methods": [
"order.wave.batchList"
],
"notes": [
"app/service/systemMethods/order/wave.js batchList:wave_order_stats 子查询新增 owner_distinct_count(COUNT(DISTINCT NULLIF(store_id,0)))、owner_named_count(SUM 非空判定)、owner_store_id(MAX(NULLIF(store_id,0)))三个聚合字段,listSql SELECT 透出",
"新增 resolveWaveBatchOwnerStoreNameMap:仅对满足单货主的波次批量查 StoreWarehouse(store_id+warehouse_id)取 store_remask,再查 wms_store.company_name 兑底,remask 覆盖 company_name;查询失败仅告警不影响列表",
"判定口径:orderCount>0 且 ownerDistinctCount===1 且 ownerNamedCount===orderCount 且 ownerStoreId>0 才返回货主名称,否则返回“混合”(0 单波次同样返回“混合”)",
"货主名称口径与 afterSale._enrichListStoreNames、inventory.store_name 一致(store_remask 优先、company_name 兑底);早期草稿曾按 shop_nick 店铺名称实现,已按项目货主口径修正",
"同步更新 methods/system.json 的 batchList 描述与 response.list 字段说明"
],
"module": "order.wave"
},
{
"version": "2026.08.26-workbench-queryOrder-pack-status",
"date": "2026-08-26",

View File

@ -239,5 +239,52 @@
"背景:R20682003 创建时已写入车牌粤EH22E2,但通知为固定提醒文案导致货主误以为车牌未生效"
],
"module": "receiving"
},
{
"version": "2026-08-26-warehouse-01",
"date": "2026-08-26",
"type": "changed",
"summary": "调整 receiving_store_bound 通知模板:不再向货主发送「请确认是否已填写车牌号或快递单号,未填写请及时补充」提示,车牌号/快递单号未登记时展示「车牌号:无 / 快递单号:无」",
"methods": [
"notify.reply"
],
"notes": [
"storage/receiving.js sendStoreBoundNotice:车牌号/快递单号两行始终输出,已登记显示「车牌号:X 已登记」「快递单号:X 已登记」,未登记显示「车牌号:无」「快递单号:无」",
"notification_webhook.js AVAILABLE_EVENTS.receiving_store_bound 描述同步更新:展示车牌号/快递单号登记状态",
"背景:车牌号/快递单号由仓库侧登记,货主端无法填写,「请确认/及时补充」提示对货主无意义,改为直接展示登记状态"
],
"module": "receiving"
},
{
"version": "2026-08-26-warehouse-02",
"date": "2026-08-26",
"type": "added",
"summary": "新增收货完成未匹配商品货主通知(receiving_store_unmatched):收货单提交完成时存在未匹配商品明细,通知货主核实是否为新商品未推送资料",
"methods": [
"notify.reply"
],
"notes": [
"新事件码 receiving_store_unmatched 注册(notification_webhook.js AVAILABLE_EVENTS 与 notice/index.js DEFAULT_REGISTERED_EVENT_CODES)",
"FIXED_GROUP_SUBSCRIPTIONS.receiving_store_unmatched:仅货主侧目标 store:receiving + fallbackTargets store:after_sales(与 receiving_store_bound 一致)",
"storage/receiving.js 新增 sendStoreUnmatchedNotice:内容「收货单号:xxx 提交完成收货,有未匹配商品资料 / 条码:1.xxx,2.xxx / 核实是否是新商品未推送资料 / 详情以及收货图片查看:货主端 receiving_owner 链接 / 如果没有账户请联系人工客服开通」",
"触发点:completeReceiving 事务提交后,unmatchedDetails 非空且已绑定货主时发送,失败不影响主流程"
],
"module": "receiving"
},
{
"version": "2026-08-26-warehouse-03",
"date": "2026-08-26",
"type": "changed",
"summary": "审核通过通知(receiving_reviewed)改为返回 Excel 审核明细下载链接,Excel 生成失败时回退正文展示全部明细(item_code 反查 stock_store)",
"methods": [
"notify.reply"
],
"notes": [
"storage/receiving.js 新增 resolveReviewDetailItemCodeMap:批量反查 wms_stock_store(stock_id=明细 system_product_id,delete_at 为空),返回 system_product_id → item_code 映射",
"sendReviewNotice 内容改为「收货单号:Rxx 完成收货审核 / 审核明细下载:Excel链接 / 请及时提交入库单入库」,标题改为完成收货审核;Excel 生成失败时回退正文展示全部明细(1.商品编码 名称 数量)",
"reviewReceiving 调整为先生成 Excel 再发一次通知(成功带下载链接,失败回退文字),替代原「先文字后文件」两次发送",
"item_code 反查不到时回退明细条码,仍无则显示未知编码"
],
"module": "receiving"
}
]

View File

@ -28507,7 +28507,7 @@
"list": [
{
"method": "order.wave.batchList",
"description": "波次列表查询。仅使用当前登录操作者仓库上下文(禁止传入 warehouse_id/warehouseId)。支持 where 白名单过滤,固定查询 wave_status=0/1;返回波次基础信息及分配状态汇总(storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status)。支持 only_todo=1 仅返回仍有未复核订单的波次,并返回复核状态汇总(review_assignment_status)与未复核数量(unreviewed_order_count)。",
"description": "波次列表查询。仅使用当前登录操作者仓库上下文(禁止传入 warehouse_id/warehouseId)。支持 where 白名单过滤,固定查询 wave_status=0/1;返回波次基础信息及分配状态汇总(storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status)。支持 only_todo=1 仅返回仍有未复核订单的波次,并返回复核状态汇总(review_assignment_status)与未复核数量(unreviewed_order_count)。列表每条记录返回货主信息 store_name:当波次内所有订单均为同一货主(store_id)时返回货主名称,否则返回“混合”。货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),无合约或备注为空时回退 wms_store.company_name(公司全称)。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -28538,7 +28538,7 @@
"type": "object",
"required": false,
"source": "body",
"description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- express_assignment_status(等值,string,可选,英文枚举,取值:unassigned、partially_assigned、assigned;语义:按快递分配聚合判断,assigned 表示聚合后全部 fin,partially_assigned 表示部分已分配且不含 error,unassigned 表示全 none 或包含 error(异常并入未分配集合))。\n- print_assignment_status(等值,string,可选,英文枚举,取值:unprinted、partially_printed、printed;语义:按打印分配聚合判断,printed 表示聚合后全部已打印)。\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。\n说明:express_assignment_status 与 print_assignment_status 要求使用英文枚举值;storage_assignment_status 仍向后兼容中文展示值。若传入的枚举值不在允许集合内,接口会返回 400(参数校验失败),并在 message 中说明错误字段与允许取值。\n- review_assignment_status(等值,string,可选,英文枚举:unreviewed、partially_reviewed、reviewed;分别表示未复核、部分复核、已复核)。"
"description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- express_assignment_status(等值,string,可选,英文枚举,取值:unassigned、partially_assigned、assigned;语义:按快递分配聚合判断,assigned 表示聚合后全部 fin,partially_assigned 表示部分已分配且不含 error,unassigned 表示全 none 或包含 error(异常并入未分配集合))。\n- print_assignment_status(等值,string,可选,英文枚举,取值:unprinted、partially_printed、printed;语义:按打印分配聚合判断,printed 表示聚合后全部已打印)。\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。\n说明:express_assignment_status 与 print_assignment_status 要求使用英文枚举值;storage_assignment_status 仍向后兼容中文展示值。若传入的枚举值不在允许集合内,接口会返回 400(参数校验失败),并在 message 中说明错误字段与允许取值。\n- review_assignment_status(等值,string,可选,英文枚举:unreviewed、partially_reviewed、reviewed;分别表示未复核、部分复核、已复核)。\n- store_id(货主ID,可选,正整数,支持单值/数组/{operator,value} 结构,如 {\"operator\":\"\",\"value\":[1000281,1000000]};语义:返回包含任一筛选货主订单的波次,含混合货主波次;单值与数组均按 in 匹配)。"
}
],
"response": [
@ -28546,7 +28546,7 @@
"name": "list",
"type": "array",
"required": true,
"description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status / unreviewed_order_count)。其中 pick_assignment_status 按订单 pick_status 聚合判定,取值:未拣货/部分拣货/已拣货/拣货异常。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。"
"description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status / unreviewed_order_count)。其中 pick_assignment_status 按订单 pick_status 聚合判定,取值:未拣货/部分拣货/已拣货/拣货异常。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。每条记录新增字段 store_name(string):货主信息,当波次内所有订单均为同一货主(store_id)时返回货主名称,否则返回“混合”;货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),无合约或备注为空时回退 wms_store.company_name(公司全称)。"
},
{
"name": "pagination",