429 lines
17 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 DEBUG_LOG = path.join(__dirname, '..', '..', '..', '..', 'temp', 'quickSearch_debug.log');
function dbg(msg) {
const ts = new Date().toISOString();
const line = `[${ts}] ${msg}\n`;
try { fs.appendFileSync(DEBUG_LOG, line, 'utf8'); } catch (_) { /* ignore */ }
}
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,精确)、发货单号/外部订单号/平台交易单号(dispatch 表,模糊)。
* 返回匹配的订单列表(最多 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 表 OR 搜索 ======
dbg('--- Step1: express OR query ---');
const expressWhere = {
warehouse_id: warehouseId,
[Op.or]: [
{ waybill_code: keyword },
{ delivery_order_code: { [Op.like]: `%${keyword}%` } },
{ source_order_codes: { [Op.like]: `%${keyword}%` } },
],
};
dbg(`expressWhere: ${JSON.stringify(expressWhere)}`);
let expressRecords;
try {
expressRecords = await ctx.model.OrderExpress.findAll({
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',
],
where: expressWhere,
raw: true,
limit: MAX_RESULTS,
});
dbg(`expressRecords count: ${expressRecords.length}`);
} catch (e) {
dbg(`expressRecords ERROR: ${e.message}`);
expressRecords = [];
}
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;