liufumingren c2b5ffc319 1
2026-06-07 20:42:24 +08:00

1550 lines
49 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 MainService = require('../../main');
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
const DEFAULT_PAGE_SIZE = 20;
const MAX_PAGE_SIZE = 500;
const FORBIDDEN_WAREHOUSE_FIELDS = new Set([ 'warehouse_id', 'warehouseId' ]);
const WAREHOUSE_FIELD_ERROR_MESSAGE = '订单工作台查询条件禁止传入 warehouse_id / warehouseId,请使用当前用户上下文的 store_id。';
const REVIEW_STATUS_STEP_MAP = Object.freeze({
none: 0,
padding: 2,
running: 2,
fin: 1,
error: 3,
});
const REVIEW_ORDER_ALLOWED_FIELDS = Object.freeze([ 'ids' ]);
const BADGE_COUNT_OVER_LIMIT_VALUE = '99+';
const ORDER_LIST_BASE_ATTRIBUTES = [
'id', 'delivery_order_code', 'pre_delivery_order_code', 'pre_delivery_order_id',
'order_type', 'order_flag', 'source_order_codes',
'sys_platform_code', 'sys_platform_name',
'create_at',
'place_order_time', 'pay_time', 'pay_no', 'service_code',
'operator_name', 'operate_time', 'delivery_time',
'shop_nick', 'seller_nick', 'buyer_nick',
'buyer_message', 'seller_message', 'remark',
'total_amount', 'item_amount', 'discount_amount', 'freight',
'ar_amount', 'got_amount', 'service_fee',
'logistics_name',
'delivery_type', 'weight_type',
'is_urgency', 'invoice_flag', 'status',
'name', 'zip_code', 'tel', 'mobile', 'email',
'province', 'city', 'area', 'town', 'detail_address',
'id_type', 'id_number',
'sync_status',
'items', 'items_count', 'items_total', 'items_weight',
'wave_id',
'wave_no',
'wave_strategy_version',
'wave_scan_result',
'post_status', 'storage_status', 'pick_status', 'pack_status',
'inspection_status', 'print_status', 'claim_status',
'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status',
];
const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({
0: '常规',
1: '轻货',
2: '重货',
3: '冷链',
});
const ORDER_TABLE_TYPE_ALIASES = Object.freeze({
current: 'current',
history: 'history',
dispatch: 'dispatch',
outsourced: 'outsourced',
order: 'current',
revieworder: 'current',
pendingorder: 'current',
outboundorder: 'current',
expectionorder: 'current',
archiveorder: 'history',
entrustorder: 'outsourced',
deliveryorder: 'dispatch',
deliveryexpectionorder: 'dispatch',
});
const MODULE_CONFIGS = Object.freeze({
order: {
modelType: 'current',
defaultWhere: {},
},
reviewOrder: {
modelType: 'current',
defaultWhere: {
step: {
operator: 'eq',
value: 0,
},
},
},
pendingOrder: {
modelType: 'current',
defaultWhere: {
outbound_status: {
operator: 'ne',
value: 'padding',
},
step: {
operator: 'in',
value: [ 1, 2, 3 ],
},
},
},
waveStrategyFallbackOrder: {
modelType: 'current',
defaultWhere: {
step: {
operator: 'ne',
value: 0,
},
wave_id: {
operator: 'eq',
value: 0,
},
wave_scan_result: {
operator: 'eq',
value: 2,
},
},
},
outboundOrder: {
modelType: 'current',
defaultWhere: {
outbound_status: {
operator: 'in',
value: [ 'fin', 'padding' ],
},
step: {
operator: 'in',
value: [ 4, 9 ],
},
},
},
expectionOrder: {
modelType: 'current',
defaultWhere: {
step: {
operator: 'eq',
value: 3,
},
},
},
entrustOrder: {
modelType: 'outsourced',
defaultWhere: {},
},
deliveryOrder: {
modelType: 'dispatch',
defaultWhere: {
dispatch_lane: {
operator: 'eq',
value: 'm4',
},
},
},
deliveryExpectionOrder: {
modelType: 'dispatch',
defaultWhere: {
dispatch_lane: {
operator: 'eq',
value: 'm5',
},
},
},
archiveOrder: {
modelType: 'history',
defaultWhere: {},
},
});
/**
* 订单工作台系统方法基础能力。
* 负责仓库上下文、分页规范、where 解析、模型选择与审核状态更新。
*/
class OrderBaseService extends MainService {
/**
* 脱敏展示值:保留首尾字符,中间统一替换为 ***。
* @param {string|number|null|undefined} value 原始值。
* @return {string|null} 脱敏后的值。
*/
maskListSensitiveValue(value) {
if (value === null || value === undefined) {
return value;
}
const normalizedValue = String(value);
if (!normalizedValue) {
return normalizedValue;
}
const chars = Array.from(normalizedValue);
if (chars.length <= 1) {
return normalizedValue;
}
return `${chars[0]}***${chars[chars.length - 1]}`;
}
/**
* 获取当前请求对应的仓库ID。
* @return {number|string|null} 仓库ID。
*/
getWarehouseId() {
const { ctx } = this;
const warehouseId = ctx?.user?.store_id ?? null;
return warehouseId === '' ? null : warehouseId;
}
/**
* 获取订单日志使用的操作人信息。
*
* 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。
*
* @return {{ id: string|null, name: string }} 操作人信息。
*/
getOrderLogOperator() {
const { ctx } = this;
const stateUser = this.isPlainObject(ctx?.state?.user) ? ctx.state.user : null;
const ctxUser = this.isPlainObject(ctx?.user) ? ctx.user : null;
const paramsObject = this.isPlainObject(this.params) ? this.params : {};
const paramsOperator = this.isPlainObject(paramsObject.__operator)
? paramsObject.__operator
: (this.isPlainObject(paramsObject.operator) ? paramsObject.operator : null);
const operatorSource = stateUser || ctxUser || paramsOperator || {};
const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id;
const rawOperatorName = operatorSource.employees_name
?? operatorSource.operator_name
?? operatorSource.real_name
?? operatorSource.name;
const operatorId = rawOperatorId === undefined || rawOperatorId === null
? null
: String(rawOperatorId).trim() || null;
const operatorName = rawOperatorName === undefined || rawOperatorName === null
? 'system'
: String(rawOperatorName).trim() || 'system';
return {
id: operatorId,
name: operatorName,
};
}
/**
* 获取订单日志使用的仓库ID。
*
* 取值优先级:显式传入参数 -> 当前上下文仓库 -> ctx.user.warehouse_id -> ctx.user.store_id。
*
* @param {number|string|null} [preferredWarehouseId=null] 优先使用的仓库ID。
* @return {number|string|null} 归一化后的仓库ID。
*/
getOrderLogWarehouseId(preferredWarehouseId = null) {
const { ctx } = this;
const candidates = [
preferredWarehouseId,
this.getWarehouseId(),
ctx?.user?.warehouse_id,
ctx?.user?.store_id,
];
for (const candidate of candidates) {
if (candidate === undefined || candidate === null || candidate === '') {
continue;
}
return candidate;
}
return null;
}
/**
* 规范分页参数并限制 pageSize 上限。
* @param {Object} pageParams 分页参数。
* @return {{ page: number, pageSize: number }} 规范化结果。
*/
normalizePagination(pageParams = {}) {
const requestParams = this.isPlainObject(pageParams) ? pageParams : {};
const pageValue = requestParams.page ?? requestParams.currentPage ?? 1;
const pageSizeValue = requestParams.pageSize ?? requestParams.page_size ?? requestParams.size ?? DEFAULT_PAGE_SIZE;
const page = Math.max(Number.parseInt(pageValue, 10) || 1, 1);
const pageSize = Math.min(
Math.max(Number.parseInt(pageSizeValue, 10) || DEFAULT_PAGE_SIZE, 1),
MAX_PAGE_SIZE
);
return {
page,
pageSize,
};
}
/**
* 规范化 where 入参,兼容简写值与标准 { operator, value } 结构。
* @param {Object} whereInput where 条件对象。
* @return {Object} 规范化后的 where 条件。
*/
normalizeWhereInput(whereInput = {}) {
const sourceWhere = this.isPlainObject(whereInput && whereInput.where)
? whereInput.where
: whereInput;
if (!this.isPlainObject(sourceWhere)) {
return {};
}
const normalized = {};
for (const [ fieldKey, condition ] of Object.entries(sourceWhere)) {
if (FORBIDDEN_WAREHOUSE_FIELDS.has(fieldKey)) {
throw new Error(WAREHOUSE_FIELD_ERROR_MESSAGE);
}
if (this.isPlainObject(condition)) {
const hasStandardKeys = [ 'value', 'operator', 'type', 'field', 'values' ]
.some(key => Object.prototype.hasOwnProperty.call(condition, key));
if (hasStandardKeys) {
const normalizedCondition = {
...condition,
};
if (!Object.prototype.hasOwnProperty.call(normalizedCondition, 'value')
&& Object.prototype.hasOwnProperty.call(normalizedCondition, 'values')) {
normalizedCondition.value = normalizedCondition.values;
delete normalizedCondition.values;
}
if (!Object.prototype.hasOwnProperty.call(normalizedCondition, 'operator') || !normalizedCondition.operator) {
normalizedCondition.operator = Array.isArray(normalizedCondition.value) ? 'in' : 'eq';
}
normalized[fieldKey] = normalizedCondition;
continue;
}
}
normalized[fieldKey] = {
operator: Array.isArray(condition) ? 'in' : 'eq',
value: condition,
};
}
return normalized;
}
/**
* 规范订单 ID 入参,兼容 ids、id、order_id、orderId 四种写法。
* @param {Object} data 请求体。
* @return {number[]} 订单 ID 列表。
*/
normalizeOrderIds(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const rawIds = requestData.ids;
const fallbackId = requestData.id !== undefined && requestData.id !== null && requestData.id !== ''
? requestData.id
: requestData.order_id !== undefined && requestData.order_id !== null && requestData.order_id !== ''
? requestData.order_id
: requestData.orderId;
const sourceIds = [];
if (Array.isArray(rawIds)) {
sourceIds.push(...rawIds);
} else if (typeof rawIds === 'string') {
sourceIds.push(...rawIds.split(','));
} else if (rawIds !== undefined && rawIds !== null && rawIds !== '') {
sourceIds.push(rawIds);
} else if (requestData.id !== undefined && requestData.id !== null && requestData.id !== '') {
sourceIds.push(requestData.id);
} else if (requestData.order_id !== undefined && requestData.order_id !== null && requestData.order_id !== '') {
sourceIds.push(requestData.order_id);
} else if (requestData.orderId !== undefined && requestData.orderId !== null && requestData.orderId !== '') {
sourceIds.push(requestData.orderId);
}
const normalizedIds = [];
for (const value of sourceIds) {
const normalizedId = Number(String(value).trim());
if (Number.isFinite(normalizedId) && normalizedId > 0) {
normalizedIds.push(normalizedId);
}
}
if (normalizedIds.length === 0 && fallbackId !== undefined && fallbackId !== null && fallbackId !== '') {
const normalizedFallbackId = Number(String(fallbackId).trim());
if (Number.isFinite(normalizedFallbackId) && normalizedFallbackId > 0) {
normalizedIds.push(normalizedFallbackId);
}
}
return Array.from(new Set(normalizedIds));
}
/**
* 判断 where 条件是否可以安全合并到扁平对象。
* @param {Object} condition Sequelize 条件对象。
* @return {boolean} 是否可合并。
*/
isMergeableWhereCondition(condition) {
if (!this.isPlainObject(condition)) {
return false;
}
if (Object.getOwnPropertySymbols(condition).length > 0) {
return false;
}
return Object.keys(condition).length === 1;
}
/**
* 合并两个 where 对象,后者优先覆盖前者。
* @param {Object} baseWhere 基础条件。
* @param {Object} extraWhere 追加条件。
* @return {Object} 合并后的条件。
*/
mergeWhereObjects(baseWhere = {}, extraWhere = {}) {
return {
...(this.isPlainObject(baseWhere) ? baseWhere : {}),
...(this.isPlainObject(extraWhere) ? extraWhere : {}),
};
}
/**
* 获取模块配置。
* @param {string} moduleName 模块名称。
* @return {{ modelType: string, defaultWhere: Object }} 模块配置。
*/
getModuleConfig(moduleName = 'order') {
return MODULE_CONFIGS[moduleName] || MODULE_CONFIGS.order;
}
/**
* 获取模块默认筛选条件。
* @param {string} moduleName 模块名称。
* @return {Object} 默认筛选条件。
*/
getDefaultWhere(moduleName = 'order') {
const config = this.getModuleConfig(moduleName);
return this.mergeWhereObjects({}, config.defaultWhere);
}
/**
* 构造订单工作台角标缓存键。
* @param {number|string} warehouseId 仓库ID。
* @return {string} 缓存键。
*/
getBadgeCountCacheKey(warehouseId) {
return `systemMethods:order:badgeCount:${warehouseId}`;
}
/**
* 将角标计数转换为前端展示值。
* @param {number|string} count 订单数。
* @return {number|string} 展示值。
*/
formatBadgeCountValue(count) {
const normalizedCount = Number(count);
if (!Number.isFinite(normalizedCount) || normalizedCount < 0) {
return 0;
}
return normalizedCount > 99 ? BADGE_COUNT_OVER_LIMIT_VALUE : normalizedCount;
}
/**
* 将订单重量类型转换为中文展示值。
* @param {number|string} weightType 重量类型值。
* @return {string} 中文重量类型。
*/
formatWeightTypeLabel(weightType) {
if (typeof weightType === 'string') {
const trimmedWeightType = weightType.trim();
if (!trimmedWeightType) {
return ORDER_WEIGHT_TYPE_LABELS[0];
}
if (Object.values(ORDER_WEIGHT_TYPE_LABELS).includes(trimmedWeightType)) {
return trimmedWeightType;
}
}
const normalizedWeightType = Number(weightType);
if (Number.isInteger(normalizedWeightType)
&& Object.prototype.hasOwnProperty.call(ORDER_WEIGHT_TYPE_LABELS, normalizedWeightType)) {
return ORDER_WEIGHT_TYPE_LABELS[normalizedWeightType];
}
return ORDER_WEIGHT_TYPE_LABELS[0];
}
/**
* 规范波次扫描结果,空值时默认返回 0(未扫描)。
* @param {*} scanResult 扫描结果原始值。
* @return {number|string} 规范化后的扫描结果。
*/
normalizeWaveScanResult(scanResult) {
if (scanResult === null || scanResult === undefined || scanResult === '') {
return 0;
}
const numericResult = Number(scanResult);
return Number.isNaN(numericResult) ? scanResult : numericResult;
}
/**
* 规范波次策略版本,空值时默认返回 0。
* @param {*} strategyVersion 波次策略版本原始值。
* @return {number|string} 规范化后的波次策略版本。
*/
normalizeWaveStrategyVersion(strategyVersion) {
if (strategyVersion === null || strategyVersion === undefined || strategyVersion === '') {
return 0;
}
const numericVersion = Number(strategyVersion);
return Number.isNaN(numericVersion) ? strategyVersion : numericVersion;
}
/**
* 规范订单列表单行输出,保证重量类型直接返回中文。
* @param {Object} order 订单列表行数据。
* @return {Object} 规范后的订单列表行数据。
*/
normalizeOrderListItem(order = {}) {
if (!this.isPlainObject(order)) {
return order;
}
return {
...order,
name: this.maskListSensitiveValue(order.name),
tel: this.maskListSensitiveValue(order.tel),
weight_type: this.formatWeightTypeLabel(order.weight_type),
wave_strategy_version: this.normalizeWaveStrategyVersion(order.wave_strategy_version),
wave_scan_result: this.normalizeWaveScanResult(order.wave_scan_result),
};
}
/**
* 获取指定模块的角标展示值。
* @param {string} moduleName 模块名称。
* @param {number|string} [warehouseId] 仓库ID。
* @return {Promise<number|string>} 角标展示值。
*/
async getBadgeCountByModule(moduleName = 'order', warehouseId = this.getWarehouseId()) {
const actualWarehouseId = warehouseId ?? this.getWarehouseId();
const model = await this.getOrderModel(moduleName, actualWarehouseId);
const queryWhere = this.buildWhere(this.getDefaultWhere(moduleName), actualWarehouseId);
const count = await model.count({ where: queryWhere });
return this.formatBadgeCountValue(count);
}
/**
* 获取订单工作台对应的物理模型。
* @param {string} moduleName 模块名称。
* @param {number|string} [warehouseId] 仓库ID(保留兼容参数,实际以上下文 store_id 为准)。
* @return {Promise<Object>} Sequelize 动态模型。
*/
async getOrderModel(moduleName = 'order', warehouseId = null) {
const { ctx } = this;
const config = this.getModuleConfig(moduleName);
const contextWarehouseId = this.getWarehouseId();
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
&& String(warehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}
const actualWarehouseId = contextWarehouseId;
switch (config.modelType) {
case 'history':
return await ctx.model.OrderDeliveryFactory.getHistoryModel(actualWarehouseId);
case 'dispatch':
return await ctx.model.OrderDeliveryFactory.getDispatchModel(actualWarehouseId);
case 'outsourced':
return await ctx.model.OrderDeliveryFactory.getOutsourcedModel(actualWarehouseId);
case 'current':
default:
return await ctx.model.OrderDeliveryFactory.getCurrentModel(actualWarehouseId);
}
}
/**
* 解析订单详情使用的表位类型。
* @param {Object} data 请求体。
* @return {string} 表位类型。
*/
resolveOrderTableType(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const candidates = [
requestData.tableType,
requestData.tablePosition,
requestData.type,
requestData.moduleName,
];
for (const candidate of candidates) {
const normalizedCandidate = String(candidate ?? '').trim();
if (!normalizedCandidate) {
continue;
}
const normalizedType = ORDER_TABLE_TYPE_ALIASES[normalizedCandidate.toLowerCase()];
if (normalizedType) {
return normalizedType;
}
throw new Error(`不支持的订单表位类型: ${normalizedCandidate}`);
}
return 'current';
}
/**
* 根据表位类型获取订单头模型。
* @param {string} tableType 表位类型。
* @param {number|string} [warehouseId] 仓库ID。
* @return {Promise<Object>} 订单头模型。
*/
async getOrderModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) {
const { ctx } = this;
const contextWarehouseId = this.getWarehouseId();
const normalizedTableType = this.resolveOrderTableType({ tableType });
const actualWarehouseId = warehouseId ?? contextWarehouseId;
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== ''
&& String(actualWarehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}
switch (normalizedTableType) {
case 'history':
return await ctx.model.OrderDeliveryFactory.getHistoryModel(contextWarehouseId);
case 'dispatch':
return await ctx.model.OrderDeliveryFactory.getDispatchModel(contextWarehouseId);
case 'outsourced':
return await ctx.model.OrderDeliveryFactory.getOutsourcedModel(contextWarehouseId);
case 'current':
default:
return await ctx.model.OrderDeliveryFactory.getCurrentModel(contextWarehouseId);
}
}
/**
* 根据表位类型获取订单商品模型。
* @param {string} tableType 表位类型。
* @param {number|string} [warehouseId] 仓库ID。
* @return {Promise<Object>} 订单商品模型。
*/
async getOrderItemsModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) {
const { ctx } = this;
const contextWarehouseId = this.getWarehouseId();
const normalizedTableType = this.resolveOrderTableType({ tableType });
const actualWarehouseId = warehouseId ?? contextWarehouseId;
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== ''
&& String(actualWarehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}
const orderItemsFactory = ctx.model && ctx.model.OrderItemsFactory;
if (!orderItemsFactory) {
throw new Error('订单商品模型工厂不存在');
}
switch (normalizedTableType) {
case 'history':
return await orderItemsFactory.getHistoryModel(contextWarehouseId);
case 'dispatch':
return await orderItemsFactory.getDispatchModel(contextWarehouseId);
case 'outsourced':
return await orderItemsFactory.getOrCreateModel(contextWarehouseId, 'outsourced');
case 'current':
default:
return await orderItemsFactory.getCurrentModel(contextWarehouseId);
}
}
/**
* 查询订单关联运单信息。
* @param {number|string} orderId 订单ID。
* @return {Promise<Object[]>} 运单信息列表。
*/
async getOrderExpressesByOrderId(orderId) {
const normalizedOrderId = Number(orderId || 0);
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
return [];
}
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
return [];
}
const rows = await orderExpressModel.findAll({
where: {
order_id: normalizedOrderId,
},
attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
return (Array.isArray(rows) ? rows : []).map(row => ({
waybill_code: String(row && row.waybill_code || '').trim(),
logistics_code: String(row && row.logistics_code || '').trim(),
logistics_name: String(row && row.logistics_name || '').trim(),
logistics_interface_id: row && row.logistics_interface_id == null ? null : Number(row.logistics_interface_id),
}));
}
/**
* 归一化订单列表中的快递与系统名称字段。
* @param {Object} orderRow 订单行。
* @param {string[]} expressNumbers 快递号列表。
* @return {Object} 归一化后的订单行。
*/
normalizeOrderListRow(orderRow = {}, expressNumbers = []) {
const normalizedExpressNumbers = Array.isArray(expressNumbers)
? Array.from(new Set(expressNumbers.map(item => String(item || '').trim()).filter(Boolean)))
: [];
return {
...orderRow,
name: this.maskListSensitiveValue(orderRow.name),
tel: this.maskListSensitiveValue(orderRow.tel),
mobile: this.maskListSensitiveValue(orderRow.mobile),
wave_strategy_version: this.normalizeWaveStrategyVersion(orderRow.wave_strategy_version),
wave_scan_result: this.normalizeWaveScanResult(orderRow.wave_scan_result),
sys_platform_name: Object.prototype.hasOwnProperty.call(orderRow, 'sys_platform_name')
? (orderRow.sys_platform_name ?? null)
: null,
sys_logistics_name: Object.prototype.hasOwnProperty.call(orderRow, 'sys_logistics_name')
? (orderRow.sys_logistics_name ?? null)
: null,
express_numbers: normalizedExpressNumbers,
waybill_codes: normalizedExpressNumbers,
};
}
/**
* 批量补齐订单列表的快递号信息。
* @param {Object[]} list 订单列表。
* @return {Promise<Object[]>} 补齐后的列表。
*/
async attachOrderExpressNumbers(list = []) {
if (!Array.isArray(list) || list.length === 0) {
return Array.isArray(list) ? list : [];
}
const orderIds = Array.from(new Set(list
.map(item => Number(item && item.id))
.filter(value => Number.isFinite(value) && value > 0)));
if (orderIds.length === 0) {
return list.map(item => this.normalizeOrderListRow(item, []));
}
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
return list.map(item => this.normalizeOrderListRow(item, []));
}
const { Op } = this.app.Sequelize;
const expressRows = await orderExpressModel.findAll({
where: {
order_id: {
[Op.in]: orderIds,
},
},
attributes: [ 'id', 'order_id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'platform_code' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
const expressMap = new Map();
if (Array.isArray(expressRows)) {
for (const row of expressRows) {
const orderId = Number(row && row.order_id);
const waybillCode = String(row && row.waybill_code || '').trim();
if (!Number.isFinite(orderId) || orderId <= 0 || !waybillCode) {
continue;
}
const currentExpressNumbers = expressMap.get(orderId) || [];
currentExpressNumbers.push(waybillCode);
expressMap.set(orderId, currentExpressNumbers);
}
}
return list.map(item => {
const orderId = Number(item && item.id);
const orderExpressNumbers = Number.isFinite(orderId) && orderId > 0
? (expressMap.get(orderId) || [])
: [];
return this.normalizeOrderListRow(item, orderExpressNumbers);
});
}
/**
* 提取订单列表中的运单号虚拟筛选条件。
* @param {Object} whereInput 标准化后的 where 条件。
* @return {{ where: Object, expressNumbers: string[] }} 清洗后的 where 与运单号集合。
*/
extractOrderListExpressVirtualFilter(whereInput = {}) {
const normalizedWhere = this.isPlainObject(whereInput)
? { ...whereInput }
: {};
const waybillCondition = normalizedWhere.waybill_codes;
const expressCondition = normalizedWhere.express_numbers;
delete normalizedWhere.waybill_codes;
delete normalizedWhere.express_numbers;
const expressNumbers = Array.from(new Set([
...this.normalizeExpressFilterValues(waybillCondition),
...this.normalizeExpressFilterValues(expressCondition),
]));
return {
where: normalizedWhere,
expressNumbers,
};
}
/**
* 规范化运单号筛选输入,兼容字符串、数组与 { value } 结构。
* @param {*} condition 运单号筛选条件。
* @return {string[]} 规范化后的运单号列表。
*/
normalizeExpressFilterValues(condition) {
const sourceValue = this.isPlainObject(condition) && Object.prototype.hasOwnProperty.call(condition, 'value')
? condition.value
: condition;
const sourceItems = [];
if (Array.isArray(sourceValue)) {
sourceItems.push(...sourceValue);
} else if (typeof sourceValue === 'string') {
sourceItems.push(...sourceValue.split(','));
} else if (sourceValue !== undefined && sourceValue !== null && sourceValue !== '') {
sourceItems.push(sourceValue);
}
return sourceItems
.map(item => String(item || '').trim())
.filter(Boolean);
}
/**
* 根据运单号筛选条件查询命中的订单ID。
* @param {string[]} expressNumbers 运单号列表。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<number[]>} 命中的订单ID列表。
*/
async findOrderIdsByExpressNumbers(expressNumbers = [], warehouseId = this.getWarehouseId()) {
const contextWarehouseId = this.getWarehouseId();
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
&& String(warehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}
const normalizedExpressNumbers = Array.from(new Set(
(Array.isArray(expressNumbers) ? expressNumbers : [])
.map(item => String(item || '').trim())
.filter(Boolean)
));
if (normalizedExpressNumbers.length === 0) {
return [];
}
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
return [];
}
const { Op } = this.app.Sequelize;
const rows = await orderExpressModel.findAll({
where: {
warehouse_id: contextWarehouseId,
waybill_code: {
[Op.in]: normalizedExpressNumbers,
},
},
attributes: [ 'order_id' ],
raw: true,
});
return Array.from(new Set((Array.isArray(rows) ? rows : [])
.map(row => Number(row && row.order_id))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
}
/**
* 将命中的订单ID并入 Sequelize where 条件。
* @param {Object} queryWhere 原始 where 条件。
* @param {number[]} orderIds 命中的订单ID。
* @return {Object} 合并后的 where 条件。
*/
appendOrderIdsFilterToWhere(queryWhere = {}, orderIds = []) {
const { Op } = this.app.Sequelize;
const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : [])
.map(item => Number(item))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
const orderIdCondition = {
id: {
[Op.in]: normalizedOrderIds,
},
};
if (!this.isPlainObject(queryWhere)
|| (Object.keys(queryWhere).length === 0 && Object.getOwnPropertySymbols(queryWhere).length === 0)) {
return orderIdCondition;
}
if (Array.isArray(queryWhere[Op.and])) {
return {
...queryWhere,
[Op.and]: [ ...queryWhere[Op.and], orderIdCondition ],
};
}
return {
[Op.and]: [ queryWhere, orderIdCondition ],
};
}
/**
* 构造列表排序参数。
* @param {Object} sort 排序参数。
* @param {string} [moduleName='order'] 模块名称。
* @return {Array<Array<string>>} Sequelize order 配置。
*/
buildListOrder(sort = {}, moduleName = 'order') {
const requestSort = this.isPlainObject(sort) ? sort : {};
const sortField = requestSort.sortField || requestSort.field || requestSort.sort_by || requestSort.orderBy;
const sortOrder = String(requestSort.sortOrder || requestSort.order || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const defaultSortField = moduleName === 'deliveryOrder' || moduleName === 'deliveryExpectionOrder'
? 'delivery_time'
: 'updated_at';
const allowedSortFields = new Set([
'id',
'step',
'status',
'inspection_status',
'dispatch_lane',
'delivery_time',
'create_at',
'created_at',
'updated_at',
'delivery_order_code',
'source_platform_code',
'sync_status',
'outbound_status',
]);
const actualSortField = allowedSortFields.has(sortField) ? sortField : defaultSortField;
return [
[ actualSortField, sortOrder ],
[ 'id', 'DESC' ],
];
}
/**
* 构造可直接传给 Sequelize 的 where 条件。
* @param {Object} whereInput where 条件对象。
* @param {number|string} warehouseId 仓库ID(保留兼容参数,实际以上下文 store_id 为准)。
* @param {Object} [options] 解析选项。
* @param {Object} [options.specialFieldMap] 特殊字段映射。
* @return {Object} Sequelize where 条件。
*/
buildWhere(whereInput = {}, warehouseId, options = {}) {
const { Sequelize } = this.app;
const specialFieldMap = this.isPlainObject(options.specialFieldMap) ? options.specialFieldMap : {};
const contextWarehouseId = this.getWarehouseId();
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
&& String(warehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}
const normalizedWhere = this.normalizeWhereInput(whereInput);
const parsed = parseWhereConditions({
where: normalizedWhere,
app: this.app,
specialFieldMap,
});
if (!parsed.ok) {
throw new Error(`where 参数解析失败: ${parsed.reason}`);
}
const mergedConditions = [];
if (contextWarehouseId !== null && contextWarehouseId !== undefined && contextWarehouseId !== '') {
mergedConditions.push({
warehouse_id: contextWarehouseId,
});
}
if (Array.isArray(parsed.result.dynamicConditions)) {
mergedConditions.push(...parsed.result.dynamicConditions);
}
if (this.isPlainObject(parsed.result.bucketConditions)) {
for (const bucketConditions of Object.values(parsed.result.bucketConditions)) {
if (Array.isArray(bucketConditions)) {
mergedConditions.push(...bucketConditions);
}
}
}
const flatWhere = {};
const andConditions = [];
for (const condition of mergedConditions) {
if (this.isMergeableWhereCondition(condition)) {
Object.assign(flatWhere, condition);
continue;
}
andConditions.push(condition);
}
if (andConditions.length === 0) {
return flatWhere;
}
if (Object.keys(flatWhere).length > 0) {
andConditions.unshift(flatWhere);
}
return {
[Sequelize.Op.and]: andConditions,
};
}
/**
* 查询模块列表。
* @param {string} moduleName 模块名称。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async listByModule(moduleName = 'order', data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const contextWarehouseId = this.getWarehouseId();
const { page, pageSize } = this.normalizePagination(requestData.pagination || requestData);
const { where } = this.prepareWhereContext(requestData, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where);
const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), sanitizedWhere);
let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
if (expressNumbers.length > 0) {
const orderIds = await this.findOrderIdsByExpressNumbers(expressNumbers, contextWarehouseId);
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds);
}
const model = await this.getOrderModel(moduleName, contextWarehouseId);
const order = this.buildListOrder(requestData.sort, moduleName);
const offset = (page - 1) * pageSize;
const moduleConfig = this.getModuleConfig(moduleName);
const listAttributes = moduleConfig.modelType === 'history'
? [ ...ORDER_LIST_BASE_ATTRIBUTES, 'archive_time' ]
: [ ...ORDER_LIST_BASE_ATTRIBUTES ];
const [ total, list ] = await Promise.all([
model.count({ where: queryWhere }),
model.findAll({
where: queryWhere,
attributes: listAttributes,
limit: pageSize,
offset,
order,
raw: true,
}),
]);
const normalizedList = await this.attachOrderExpressNumbers(
list.map(order => this.normalizeOrderListItem(order))
);
const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0;
return {
list: normalizedList,
pagination: {
page,
pageSize,
total,
totalPages,
hasPrevious: page > 1,
hasNext: page < totalPages,
},
};
}
/**
* 查询订单详情。
* @param {Object} data 请求体。
* @return {Promise<Object>} 订单头、商品明细和运单信息。
*/
async detail(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderIds = this.normalizeOrderIds(requestData);
const tableType = this.resolveOrderTableType(requestData);
if (orderIds.length === 0) {
throw new Error('订单ID不能为空');
}
if (orderIds.length !== 1) {
throw new Error('订单详情仅支持查询单个订单');
}
const orderId = orderIds[0];
const orderModel = await this.getOrderModelByTableType(tableType, warehouseId);
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
const order = await orderModel.findOne({
where: orderWhere,
raw: true,
});
if (!order) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, warehouseId);
const orderItems = await orderItemsModel.findAll({
where: {
order_id: orderId,
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems);
const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId);
const expresses = await this.getOrderExpressesByOrderId(orderId);
const logs = await this.getOrderOperationLogs(orderId);
return {
detail: order,
items: orderItemsWithImages,
expresses,
logs,
};
}
/**
* 按订单商品批量查询图片并按 stock_id 建立映射。
* @param {Object[]} orderItems 订单商品列表。
* @return {Promise<Map<number, string[]>>} stock_id 对应的图片 URL 列表。
*/
async getOrderItemImagesByStockIds(orderItems = []) {
if (!Array.isArray(orderItems) || orderItems.length === 0) {
return new Map();
}
const stockIds = [ ...new Set(
orderItems
.map(item => Number(item && item.stock_id))
.filter(Boolean)
) ];
if (stockIds.length === 0) {
return new Map();
}
const fileReferenceModel = this.ctx.model && this.ctx.model.FileReference;
const fileModel = this.ctx.model && this.ctx.model.File;
if (!fileReferenceModel || typeof fileReferenceModel.findAll !== 'function' || !fileModel) {
return new Map();
}
try {
const fileReferences = await fileReferenceModel.findAll({
where: {
business_type: 'stock',
business_id: {
[this.app.Sequelize.Op.in]: stockIds,
},
},
include: [{
model: fileModel,
as: 'file',
attributes: [ 'file_url' ],
required: false,
}],
});
const imagesByStockId = new Map();
for (const reference of fileReferences || []) {
const row = reference && typeof reference.get === 'function'
? reference.get({ plain: true })
: reference;
const stockId = Number(row && row.business_id);
const imageUrl = (row && row.file && row.file.file_url) || row?.file_url || row?.url || row?.file_path || '';
if (!stockId || !imageUrl) {
continue;
}
if (!imagesByStockId.has(stockId)) {
imagesByStockId.set(stockId, []);
}
imagesByStockId.get(stockId).push(String(imageUrl));
}
return imagesByStockId;
} catch (error) {
this.ctx.logger?.warn?.('[order.base.detail] 查询订单商品图片失败,已降级为空图片数组', {
error: error.message,
});
return new Map();
}
}
/**
* 将图片映射合并到订单商品列表中。
* @param {Object[]} orderItems 订单商品列表。
* @param {Map<number, string[]>} imagesByStockId 图片映射。
* @return {Object[]} 合并后的订单商品列表。
*/
attachImagesToOrderItems(orderItems = [], imagesByStockId = new Map()) {
if (!Array.isArray(orderItems)) {
return [];
}
return orderItems.map(item => {
const stockId = Number(item && item.stock_id);
const images = stockId ? (imagesByStockId.get(stockId) || []) : [];
return {
...item,
images: [ ...images ],
};
});
}
/**
* 获取订单操作日志列表。
* @param {number} orderId 订单ID。
* @return {Promise<Object[]>} 订单日志数组。
*/
async getOrderOperationLogs(orderId) {
const warehouseId = this.getWarehouseId();
const operationLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
if (!operationLogService || typeof operationLogService.queryOrderLogs !== 'function') {
return [];
}
if (warehouseId === null || warehouseId === undefined || warehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
const queryResult = await operationLogService.queryOrderLogs({
id: orderId,
warehouseId,
page: 1,
pageSize: 200,
});
return Array.isArray(queryResult && queryResult.list) ? queryResult.list : [];
}
/**
* 将审核状态映射为 step。
* @param {string} reviewStatus 审核状态。
* @return {number} 订单步骤。
*/
resolveReviewStep(reviewStatus) {
const status = String(reviewStatus || '').trim();
return REVIEW_STATUS_STEP_MAP[status] ?? 0;
}
/**
* 规范审核提交入参中的订单ID列表,仅接受 ids。
* @param {Object} data 请求体。
* @return {number[]} 订单ID 列表。
*/
normalizeReviewOrderIds(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const unexpectedKeys = Object.keys(requestData).filter(key => !REVIEW_ORDER_ALLOWED_FIELDS.includes(key));
if (unexpectedKeys.length > 0) {
throw new Error('审核接口仅支持 ids 入参,不再支持 id/order_id/review_status/inspection_status/warehouse_id/warehouseId 等兼容字段');
}
const rawIds = requestData.ids;
const sourceIds = Array.isArray(rawIds)
? rawIds
: typeof rawIds === 'string'
? rawIds.split(',')
: rawIds !== undefined && rawIds !== null && rawIds !== ''
? [ rawIds ]
: [];
const normalizedIds = sourceIds
.map(value => Number(String(value).trim()))
.filter(value => Number.isFinite(value) && value > 0);
return Array.from(new Set(normalizedIds));
}
/**
* 构建订单更新条件。
* @param {number[]} orderIds 订单 ID 列表。
* @param {number|string|null} warehouseId 仓库 ID(保留兼容参数,实际以上下文 store_id 为准)。
* @return {Object} where 条件。
*/
buildOrderWhere(orderIds = [], warehouseId = null) {
const { Op } = this.ctx.app.Sequelize;
const contextWarehouseId = this.getWarehouseId();
const normalizedIds = Array.isArray(orderIds)
? Array.from(new Set(orderIds.map(value => Number(value)).filter(value => Number.isFinite(value) && value > 0)))
: [];
if (normalizedIds.length === 0) {
return {};
}
const where = {
id: normalizedIds.length === 1 ? normalizedIds[0] : {
[Op.in]: normalizedIds,
},
};
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
&& String(warehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}
where.warehouse_id = contextWarehouseId;
return where;
}
/**
* 构建审核更新条件。
* @param {number[]} orderIds 订单ID 列表。
* @return {Object} where 条件。
*/
buildReviewOrderWhere(orderIds = []) {
return this.buildOrderWhere(orderIds);
}
/**
* 审核通过订单并进入待处理。
* @param {Object} data 请求体。
* @param {number[]|string} data.ids 批量订单ID。
* @return {Promise<Object>} 更新后的订单信息。
*/
async updateReviewOrder(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderIds = this.normalizeReviewOrderIds(requestData);
if (orderIds.length === 0) {
throw new Error('订单ID不能为空');
}
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildReviewOrderWhere(orderIds);
const existingOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(existingOrders) || existingOrders.length !== orderIds.length) {
throw new Error('订单不存在或不属于当前仓库');
}
const now = new Date();
const updateValues = {
inspection_status: 'fin',
step: 1,
status: 'created',
updated_at: now,
};
const updateResult = await model.update(updateValues, {
where,
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
if (affectedRows <= 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const updatedOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
const normalizedOrders = orderIds
.map(orderId => orderMap.get(orderId))
.filter(Boolean)
.map(order => ({
id: order.id,
inspection_status: order.inspection_status,
step: Number(order.step ?? 1),
updated_at: order.updated_at,
}));
if (normalizedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const firstOrder = normalizedOrders[0];
return {
id: firstOrder.id,
inspection_status: firstOrder.inspection_status,
step: firstOrder.step,
updated_at: firstOrder.updated_at,
updated_count: affectedRows,
ids: normalizedOrders.map(order => order.id),
};
}
/**
* 更新订单审核态。
* @param {Object} data 请求体。
* @param {string} [targetInspectionStatus] 目标审核状态。
* @param {Object} [options] 额外更新配置。
* @param {Object} [options.extraUpdateValues] 附加更新字段。
* @return {Promise<Object>} 更新后的订单信息。
*/
async updateOrderInspectionState(data = {}, targetInspectionStatus = '', options = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderIds = this.normalizeOrderIds(requestData);
const inspectionStatus = String(targetInspectionStatus || requestData.review_status || requestData.inspection_status || '').trim();
const extraUpdateValues = this.isPlainObject(options.extraUpdateValues) ? options.extraUpdateValues : {};
if (orderIds.length === 0) {
throw new Error('订单ID不能为空');
}
if (!inspectionStatus) {
throw new Error('审核状态不能为空');
}
const model = await this.getOrderModel('order', warehouseId);
const step = this.resolveReviewStep(inspectionStatus);
const now = new Date();
const where = this.buildOrderWhere(orderIds, warehouseId);
const updateValues = {
inspection_status: inspectionStatus,
step,
updated_at: now,
...extraUpdateValues,
};
const updateResult = await model.update(updateValues, {
where,
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
if (affectedRows <= 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const updatedOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
const normalizedOrders = orderIds
.map(orderId => orderMap.get(orderId))
.filter(Boolean)
.map(order => ({
id: order.id,
inspection_status: order.inspection_status,
step: Number(order.step ?? step),
updated_at: order.updated_at,
}));
if (normalizedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const firstOrder = normalizedOrders[0];
return {
id: firstOrder.id,
inspection_status: firstOrder.inspection_status,
step: firstOrder.step,
updated_at: firstOrder.updated_at,
updated_count: affectedRows,
ids: normalizedOrders.map(order => order.id),
};
}
}
module.exports = OrderBaseService;