liufumingren ce04778021 perf(order): quickSearch 改为逐级短路搜索
命中顺序:运单号(waybill_code) -> 发货单号(delivery_order_code) -> 平台订单号(source_order_codes),
每一级只要命中即停止后续查询,直接进入订单详情。

- 运单号:等值 + 剥离一单多件分段后缀主体等值 + 主体前缀 LIKE,走 waybill_code 索引
- 发货单号:等值走 idx_delivery_code_store;未命中再 %kw% 模糊兜底
- 平台订单号:%kw% 模糊仅作最后兜底

避免原单条 OR 查询混合等值与 %kw% 模糊导致优化器放弃索引、
退化为按 warehouse_id 全仓库扫描(生产单仓库 66w+ 行)。
dbg 调试日志改为持久写流异步写入,消除 appendFileSync 同步磁盘 IO。
2026-09-20 18:39:16 +08:00

523 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const OrderBaseService = require('./base');
const fs = require('fs');
const path = require('path');
const { stripWaybillSegmentSuffix, escapeLikeWildcards } = require('../../../lib/waybill_code');
const DEBUG_LOG = path.join(__dirname, '..', '..', '..', '..', 'temp', 'quickSearch_debug.log');
// 持久可写流:dbg 使用异步缓冲写,避免 appendFileSync 每次 open/write/close 的同步磁盘 IO
let debugStream = null;
function getDebugStream() {
if (!debugStream) {
try {
debugStream = fs.createWriteStream(DEBUG_LOG, { flags: 'a' });
debugStream.on('error', () => {
debugStream = null;
});
} catch (_) {
debugStream = null;
}
}
return debugStream;
}
function dbg(msg) {
const stream = getDebugStream();
if (!stream) return;
const line = `[${new Date().toISOString()}] ${msg}\n`;
try { stream.write(line); } catch (_) { /* ignore */ }
}
// express 表查询列(1a/1b/1c 三段共用)
const EXPRESS_ATTRIBUTES = [
'id', 'order_id', 'waybill_code', 'delivery_order_code', 'source_order_codes', 'store_id',
'logistics_code', 'logistics_name',
'logistics_interface_id', 'logistics_interface_name',
'platform_code', 'status', 'is_back', 'is_intercept', 'is_galaxy_receive',
'weighing_weight',
];
class DeliveryOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,deliveryOrder,quickSearch';
const _noNeedLog = 'list,quickSearch';
const _noNeedAuth = 'list,deliveryOrder,quickSearch';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 配送订单列表。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async list(data = {}) {
return await this.listByModule('deliveryOrder', data);
}
/**
* 查询配送订单详情。
*
* 默认使用 dispatch 表查询;
* 若调用方显式传入表位参数,则保持调用方指定值。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 订单头、商品明细、运单与日志信息。
*/
async detail(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const tableTypeFields = [ 'tableType', 'tablePosition', 'type', 'moduleName' ];
const hasTableTypeInput = tableTypeFields.some(field => {
if (!Object.prototype.hasOwnProperty.call(requestData, field)) {
return false;
}
return String(requestData[field] ?? '').trim() !== '';
});
const detailParams = hasTableTypeInput
? requestData
: {
...requestData,
tableType: 'dispatch',
};
return await super.detail(detailParams);
}
/**
* 订单快速搜索。
* 逐级短路搜索(wms_order_express 表),命中即停:
* 1. 运单号 waybill_code(等值 + 剥离一单多件分段后缀后的主体等值 + 主体前缀 LIKE);
* 2. 发货单号 delivery_order_code(等值优先,未命中再 %kw% 模糊);
* 3. 平台订单号 source_order_codes(%kw% 模糊兜底)。
* 返回匹配的订单列表(最多 20 条),包含订单关键信息及关联运单号。
*
* @param {Object} data 请求体。
* @param {string} data.keyword 搜索关键词(必填)。
* @return {Promise<Object>} { list, keyword }
*/
async quickSearch(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const requestData = this.isPlainObject(data) ? data : {};
const keyword = String(requestData.keyword || '').trim();
const warehouseId = this.getWarehouseId();
dbg('========== quickSearch START ==========');
dbg(`keyword="${keyword}" warehouseId=${warehouseId}`);
if (!keyword) {
dbg('keyword empty → return []');
return { list: [], keyword: '' };
}
if (!warehouseId) {
dbg('warehouseId empty → throw');
throw new Error('缺少仓库上下文');
}
const MAX_RESULTS = 20;
// 收集匹配的订单 ID(去重)
const matchedOrderIds = new Set();
// ====== 第一步:express 表逐级短路搜索 ======
// 命中顺序:运单号(waybill_code) → 发货单号(delivery_order_code) → 平台订单号(source_order_codes)。
// 每一级只要命中即停止后续查询,直接进入订单详情查询。
// 性能背景:单仓库 wms_order_express 行数达 60w+,逐级短路保证绝大多数场景
// (运单号/完整发货单号)只走索引点查,模糊全扫仅作为最后兜底。
dbg('--- Step1: express level search ---');
// 业务规则:运单号先剥离一单多件包裹序号后缀(如 -1-1-),主体必须等值匹配,
// 不得落入模糊 like
const waybillBase = stripWaybillSegmentSuffix(keyword);
const escapedWaybillBase = escapeLikeWildcards(waybillBase);
const waybillConditions = [
{ waybill_code: keyword },
...(waybillBase !== keyword ? [{ waybill_code: waybillBase }] : []),
...(escapedWaybillBase ? [{ waybill_code: { [Op.like]: `${escapedWaybillBase}-%` } }] : []),
];
dbg(`waybillBase="${waybillBase}" escapedWaybillBase="${escapedWaybillBase}"`);
let expressRecords = [];
let hitLevel = null;
// Level 1:运单号(等值/主体等值/主体前缀,走 waybill_code 索引)
try {
expressRecords = await ctx.model.OrderExpress.findAll({
attributes: EXPRESS_ATTRIBUTES,
where: {
warehouse_id: warehouseId,
[Op.or]: waybillConditions,
},
raw: true,
limit: MAX_RESULTS,
});
if (expressRecords.length > 0) hitLevel = 'waybill_code';
dbg(`L1 waybill_code records: ${expressRecords.length}`);
} catch (e) {
dbg(`L1 ERROR: ${e.message}`);
}
// Level 2a:发货单号等值(走 idx_delivery_code_store 索引)
if (!hitLevel) {
try {
expressRecords = await ctx.model.OrderExpress.findAll({
attributes: EXPRESS_ATTRIBUTES,
where: {
warehouse_id: warehouseId,
delivery_order_code: keyword,
},
raw: true,
limit: MAX_RESULTS,
});
if (expressRecords.length > 0) hitLevel = 'delivery_order_code';
dbg(`L2a delivery_order_code exact records: ${expressRecords.length}`);
} catch (e) {
dbg(`L2a ERROR: ${e.message}`);
}
}
// Level 2b:发货单号模糊兜底(中缀 LIKE 无法走索引,仅在等值未命中时执行)
if (!hitLevel) {
try {
expressRecords = await ctx.model.OrderExpress.findAll({
attributes: EXPRESS_ATTRIBUTES,
where: {
warehouse_id: warehouseId,
delivery_order_code: { [Op.like]: `%${keyword}%` },
},
raw: true,
limit: MAX_RESULTS,
});
if (expressRecords.length > 0) hitLevel = 'delivery_order_code_like';
dbg(`L2b delivery_order_code like records: ${expressRecords.length}`);
} catch (e) {
dbg(`L2b ERROR: ${e.message}`);
}
}
// Level 3:平台订单号(无索引全扫兜底,最后一级,仅前两级均未命中时执行)
if (!hitLevel) {
try {
expressRecords = await ctx.model.OrderExpress.findAll({
attributes: EXPRESS_ATTRIBUTES,
where: {
warehouse_id: warehouseId,
source_order_codes: { [Op.like]: `%${keyword}%` },
},
raw: true,
limit: MAX_RESULTS,
});
if (expressRecords.length > 0) hitLevel = 'source_order_codes';
dbg(`L3 source_order_codes records: ${expressRecords.length}`);
} catch (e) {
dbg(`L3 ERROR: ${e.message}`);
}
}
dbg(`hitLevel=${hitLevel}`);
const waybillMap = new Map();
for (const er of expressRecords) {
dbg(` er: id=${er.id} order_id=${er.order_id} waybill_code=${er.waybill_code} delivery_order_code=${er.delivery_order_code}`);
if (er.order_id) {
matchedOrderIds.add(er.order_id);
if (!waybillMap.has(er.order_id)) {
waybillMap.set(er.order_id, []);
}
waybillMap.get(er.order_id).push(this.buildWaybillItem(er));
}
}
dbg(`matchedOrderIds: [${[ ...matchedOrderIds ].join(',')}]`);
dbg(`waybillMap keys: [${[ ...waybillMap.keys() ].join(',')}]`);
if (matchedOrderIds.size === 0) {
dbg('matchedOrderIds empty → return []');
return { list: [], keyword };
}
// ====== 第二步:订单表 IN 查详情 ======
const orderIds = [ ...matchedOrderIds ].slice(0, MAX_RESULTS);
const orderMap = new Map();
dbg(`--- Step2: order detail IN query, orderIds=[${orderIds.join(',')}] ---`);
if (orderIds.length > 0) {
const factory = ctx.model && ctx.model.OrderDeliveryFactory;
dbg(`factory exists: ${!!factory}`);
dbg(`factory keys: ${factory ? Object.keys(factory).join(',') : 'N/A'}`);
dbg(`factory.getDispatchModel type: ${factory && typeof factory.getDispatchModel}`);
// 直接尝试调用,不判断 typeof,看具体报什么错
if (factory) {
const tableDefs = [
{ label: 'dispatch', getModel: () => factory.getDispatchModel(warehouseId) },
{ label: 'current', getModel: () => factory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => factory.getHistoryModel(warehouseId) },
];
// 序列表批量定位:命中则只查对应分表,未命中(存量订单)回退三表遍历
const normalizedOrderIds = orderIds.map(Number).filter(n => Number.isFinite(n) && n > 0);
let locationMap = new Map();
try {
if (typeof factory.getOrderLocations === 'function') {
locationMap = await factory.getOrderLocations(normalizedOrderIds, warehouseId);
}
} catch (e) {
dbg(` locationMap ERROR: ${e.message}`);
}
dbg(` locationMap size: ${locationMap.size}`);
const idsByLabel = { dispatch: [], current: [], history: [] };
const unresolvedIds = [];
for (const id of normalizedOrderIds) {
const location = locationMap.get(id);
if (location && idsByLabel[location]) {
idsByLabel[location].push(id);
} else {
unresolvedIds.push(id);
}
}
for (const entry of tableDefs) {
const targetIds = [ ...new Set([ ...(idsByLabel[entry.label] || []), ...unresolvedIds ]) ];
if (targetIds.length === 0) continue;
dbg(` trying table: ${entry.label}, targetIds=[${targetIds.join(',')}]`);
try {
const model = await entry.getModel();
dbg(` ${entry.label} model: ${!!model}, typeof findAll=${model && typeof model.findAll}`);
if (!model || typeof model.findAll !== 'function') {
dbg(` ${entry.label} model invalid, skip`);
continue;
}
const whereClause = { id: targetIds };
dbg(` ${entry.label} where: ${JSON.stringify(whereClause)}`);
const rows = await model.findAll({
attributes: [
'id', 'delivery_order_code', 'source_order_codes', 'pay_no',
'store_id', 'status',
'name', 'mobile', 'province', 'city', 'area', 'detail_address',
'buyer_nick', 'seller_nick', 'shop_nick',
'total_amount', 'item_amount', 'freight',
'items_count', 'items_weight',
'wave_no', 'delivery_time', 'create_at',
],
where: whereClause,
raw: true,
});
dbg(` ${entry.label} rows count: ${rows.length}`);
for (const r of (rows || [])) {
dbg(` row: id=${r.id} delivery_order_code=${r.delivery_order_code} status=${r.status}`);
const rid = String(r.id);
if (!orderMap.has(rid)) { orderMap.set(rid, r); }
}
} catch (e) {
dbg(` ${entry.label} ERROR: ${e.message} | stack: ${(e.stack || '').split('\n').slice(0, 3).join(' | ')}`);
continue;
}
}
}
}
dbg(`orderMap.size: ${orderMap.size}, keys: [${[ ...orderMap.keys() ].join(',')}]`);
// ====== 第三步:货主备注 ======
dbg('--- Step3: store remark ---');
const storeRemarkMap = new Map();
const allStoreIds = new Set();
for (const oid of orderIds) {
const wb = (waybillMap.get(oid) || [])[0];
const sid = (wb && wb.store_id) || (orderMap.get(String(oid)) || {}).store_id || 0;
if (sid) allStoreIds.add(sid);
}
dbg(`allStoreIds: [${[ ...allStoreIds ].join(',')}]`);
if (allStoreIds.size > 0 && ctx.model.StoreWarehouse) {
try {
const swRows = await ctx.model.StoreWarehouse.findAll({
where: { store_id: { [Op.in]: [ ...allStoreIds ] }, warehouse_id: warehouseId },
attributes: [ 'store_id', 'store_remask' ], raw: true,
});
dbg(`store_warehouse rows: ${swRows.length}`);
for (const sw of swRows) {
dbg(` sw: store_id=${sw.store_id} store_remask="${sw.store_remask}"`);
storeRemarkMap.set(sw.store_id, sw.store_remask || '');
}
} catch (e) { dbg(`store_warehouse ERROR: ${e.message}`); }
}
// ====== 合并输出 ======
dbg('--- Merge output ---');
const list = [];
for (const oid of orderIds) {
const order = orderMap.get(String(oid)) || {};
const waybills = waybillMap.get(oid) || [];
dbg(` oid=${oid} orderKeys=[${Object.keys(order).join(',')}] waybills=${waybills.length}`);
if (waybills.length === 0) {
list.push({
order_id: oid, waybill_id: 0, waybill_code: '',
logistics_code: '', logistics_name: '', logistics_interface_id: 0, logistics_interface_name: '',
platform_code: '', waybill_status: null, waybill_status_text: '',
is_back: 'N', is_intercept: 'N', is_galaxy_receive: 'N',
weighing_weight: 0, weighing_weight_display: '0 kg',
delivery_order_code: order.delivery_order_code || '',
source_order_codes: order.source_order_codes || '',
pay_no: order.pay_no || '',
store_id: order.store_id || 0, store_name: order.store_name || '',
store_remask: storeRemarkMap.get(order.store_id) || '',
status: order.status || '', name: order.name || '', mobile: order.mobile || '',
province: order.province || '', city: order.city || '', area: order.area || '',
detail_address: order.detail_address || '',
buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '',
total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0,
items_count: order.items_count || 0, items_weight: order.items_weight || 0,
wave_no: order.wave_no || '',
delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null,
create_at: order.create_at ? app.formatDate(order.create_at) : null,
});
} else {
for (const wb of waybills) {
list.push({
order_id: oid, waybill_id: wb.id, waybill_code: wb.waybill_code,
logistics_code: wb.logistics_code, logistics_name: wb.logistics_name,
logistics_interface_id: wb.logistics_interface_id, logistics_interface_name: wb.logistics_interface_name,
platform_code: wb.platform_code,
waybill_status: wb.status, waybill_status_text: wb.status_text,
is_back: wb.is_back, is_intercept: wb.is_intercept, is_galaxy_receive: wb.is_galaxy_receive,
weighing_weight: wb.weighing_weight, weighing_weight_display: wb.weighing_weight_display,
delivery_order_code: wb.delivery_order_code || order.delivery_order_code || '',
source_order_codes: wb.source_order_codes || order.source_order_codes || '',
pay_no: order.pay_no || '',
store_id: wb.store_id || order.store_id || 0, store_name: order.store_name || '',
store_remask: storeRemarkMap.get(wb.store_id || order.store_id) || '',
status: order.status || '', name: order.name || '', mobile: order.mobile || '',
province: order.province || '', city: order.city || '', area: order.area || '',
detail_address: order.detail_address || '',
buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '',
total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0,
items_count: order.items_count || 0, items_weight: order.items_weight || 0,
wave_no: order.wave_no || '',
delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null,
create_at: order.create_at ? app.formatDate(order.create_at) : null,
});
}
}
}
dbg(`list.length: ${list.length}`);
dbg('========== quickSearch END ==========');
return { list, keyword };
}
buildWaybillItem(er) {
return {
id: er.id,
waybill_code: er.waybill_code,
delivery_order_code: er.delivery_order_code || '',
source_order_codes: er.source_order_codes || '',
store_id: er.store_id || 0,
logistics_code: er.logistics_code || '',
logistics_name: er.logistics_name || '',
logistics_interface_id: er.logistics_interface_id || 0,
logistics_interface_name: er.logistics_interface_name || '',
platform_code: er.platform_code || '',
status: er.status,
status_text: er.status === 1 ? '已分配' : '未分配',
is_back: er.is_back || 'N',
is_intercept: er.is_intercept || 'N',
is_galaxy_receive: er.is_galaxy_receive || 'N',
weighing_weight: er.weighing_weight || 0,
weighing_weight_display: er.weighing_weight > 0
? `${(er.weighing_weight / 1000).toFixed(2)} kg` : '0 kg',
};
}
/**
* 按订单 ID 列表批量查询订单关键字段(遍历 dispatch → current → history)。
* @param {number[]} orderIds 订单ID列表
* @param {number} warehouseId 仓库ID
* @return {Promise<Map<number, Object>>} orderId → 订单行
*/
async fetchOrderMapByIds(orderIds, warehouseId) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getDispatchModel !== 'function') {
return [];
}
const attributes = [
'id', 'delivery_order_code', 'source_order_codes', 'pay_no',
'store_id', 'status',
'name', 'mobile', 'province', 'city', 'area', 'detail_address',
'buyer_nick', 'seller_nick', 'shop_nick',
'total_amount', 'item_amount', 'freight',
'items_count', 'items_weight',
'wave_no', 'delivery_time', 'create_at',
];
const tableOrders = [
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) },
];
// 序列表批量定位:命中则只查对应分表,未命中(存量订单)回退三表遍历
const normalizedIds = [ ...new Set((orderIds || []).map(Number).filter(id => Number.isFinite(id) && id > 0)) ];
let locationMap = new Map();
try {
if (typeof orderDeliveryFactory.getOrderLocations === 'function') {
locationMap = await orderDeliveryFactory.getOrderLocations(normalizedIds, warehouseId);
}
} catch (_err) {
locationMap = new Map();
}
const idsByLabel = { dispatch: [], current: [], history: [] };
const unresolvedIds = [];
for (const id of normalizedIds) {
const location = locationMap.get(id);
if (location && idsByLabel[location]) {
idsByLabel[location].push(id);
} else {
unresolvedIds.push(id);
}
}
const resultMap = new Map();
for (const entry of tableOrders) {
const targetIds = [ ...new Set([ ...(idsByLabel[entry.label] || []), ...unresolvedIds ]) ];
if (targetIds.length === 0) continue;
try {
const model = await entry.getModel();
if (!model || typeof model.findAll !== 'function') continue;
const rows = await model.findAll({
attributes,
where: {
id: { [Op.in]: targetIds },
},
raw: true,
});
for (const r of rows) {
const rid = String(r.id);
if (!resultMap.has(rid)) {
resultMap.set(rid, r);
}
}
} catch (_err) {
continue;
}
}
return resultMap;
}
}
module.exports = DeliveryOrderService;