- storeWarehouse.store.saveApiConfig:新增 resolveContractApiInterfaceType, interface_type_id=3(OPEN_API_WAREHOUSE 仓库开放接口)自动映射为 2(OPEN_API 货主开放接口)落库, 不再要求当前主体为仓库(货主可维护自身签约关系下的接口配置) - callback_url 不再取入参(含 callbackUrl 别名),统一写入 config.openapi.defaultCallbackUrl(新增配置项,默认空) - storeWarehouse.store.listApiConfig:interface_type_id 过滤同步映射(传 3 按 2 查询) - 文档:methods/system.json 升级 0.3.350、methods/changes/system.json 变更记录、docs/openapi-callback-events.md 回调地址来源说明 - 测试:saveApiConfig 新增 4 条用例(3→2 落库、忽略入参回调地址、默认值未配置、货主主体可保存、缺失类型 404),listApiConfig 新增 1 条过滤映射用例 同时提交工作区其余在制品改动: - waybill:移除 wms_order_express_trace 模型并新增 drop 迁移,轨迹查询/取号/打印链路调整 - order:订单 SN 编码(order_item_sn / order_item_sn_log / sn_code_rule、has_sn_item 回填迁移),pendingOrder/recheckOrder/wave/base 调整 - express_platform、order_async、order_export、order_storage_allocation、storage.report、stock_store 配套修复 - lib:新增 jd_client,调整 qimen_client、callback_functions 及配套测试 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2599 lines
90 KiB
JavaScript
2599 lines
90 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../../main');
|
||
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
|
||
const { isInterceptedOrderStatus } = require('../../../lib/intercept_guard');
|
||
const { isLockedOrderStatus } = require('../../../lib/lock_guard');
|
||
|
||
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', 'packages_weight',
|
||
'has_sn_item',
|
||
'wave_id',
|
||
'wave_no',
|
||
'wave_strategy_version',
|
||
'wave_scan_result',
|
||
'post_status', 'storage_status', 'pick_status', 'pack_status',
|
||
'inspection_status', 'print_status', 'confirm_print_status', 'claim_status',
|
||
'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status', 'recheck_time',
|
||
'create_channel',
|
||
'store_id',
|
||
];
|
||
|
||
const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({
|
||
0: '常规',
|
||
1: '轻货',
|
||
2: '重货',
|
||
3: '冷链',
|
||
});
|
||
const CREATE_CHANNEL_LABELS = Object.freeze({
|
||
MANUAL: '手工单',
|
||
API: '接口',
|
||
QM: '奇门',
|
||
STOCKOUT: '出库转单',
|
||
});
|
||
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,
|
||
},
|
||
},
|
||
},
|
||
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]}`;
|
||
}
|
||
|
||
/**
|
||
* 判断订单拦截状态是否属于"已进入拦截流程"的状态。
|
||
*
|
||
* requested/requesting/intercepting 为拦截发起中,intercepted_in_transit 为途中拦截成功,
|
||
* intercepted_at_warehouse 为仓库拦截成功;intercepted 为历史遗留值,一并兼容。
|
||
*
|
||
* @param {*} status 拦截状态值。
|
||
* @return {boolean} 是否已进入拦截流程。
|
||
*/
|
||
isInterceptedOrderStatus(status = '') {
|
||
return isInterceptedOrderStatus(status);
|
||
}
|
||
|
||
/**
|
||
* 判断订单锁定状态是否属于"已锁定"(lock_status != none)。
|
||
*
|
||
* @param {*} status 锁定状态值。
|
||
* @return {boolean} 是否已锁定。
|
||
*/
|
||
isLockedOrderStatus(status = '') {
|
||
return isLockedOrderStatus(status);
|
||
}
|
||
|
||
/**
|
||
* 断言订单未进入拦截流程,否则抛出阻断异常。
|
||
*
|
||
* @param {Object} orderRow 订单行(需含 intercept_status 字段)。
|
||
* @param {string} [actionText='继续作业'] 被阻断的作业文案。
|
||
* @return {void} 无返回值。
|
||
*/
|
||
assertOrderNotIntercepted(orderRow = {}, actionText = '继续作业') {
|
||
if (!this.isPlainObject(orderRow)) {
|
||
return;
|
||
}
|
||
|
||
if (this.isInterceptedOrderStatus(orderRow.intercept_status)) {
|
||
throw new Error(`订单已被拦截,无法${actionText}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取当前请求对应的仓库ID。
|
||
* @return {number|string|null} 仓库ID。
|
||
*/
|
||
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];
|
||
}
|
||
|
||
/**
|
||
* 将创建来源渠道编码转换为中文展示值。
|
||
* @param {string} channel 创建来源渠道编码。
|
||
* @return {string} 中文渠道名称。
|
||
*/
|
||
formatCreateChannelLabel(channel) {
|
||
if (!channel || typeof channel !== 'string') {
|
||
return '';
|
||
}
|
||
|
||
const trimmedChannel = channel.trim();
|
||
if (Object.prototype.hasOwnProperty.call(CREATE_CHANNEL_LABELS, trimmedChannel)) {
|
||
return CREATE_CHANNEL_LABELS[trimmedChannel];
|
||
}
|
||
|
||
return trimmedChannel;
|
||
}
|
||
|
||
/**
|
||
* 规范波次扫描结果,空值时默认返回 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;
|
||
}
|
||
|
||
/**
|
||
* 规范化订单锁定状态展示值。
|
||
* none 返回 N,其余状态(warehouse/store 等)一律返回 Y。
|
||
* @param {*} lockStatus 锁定状态值。
|
||
* @return {string} Y 或 N。
|
||
*/
|
||
normalizeLockStatusFlag(lockStatus) {
|
||
const normalizedStatus = String(lockStatus || '').trim() || 'none';
|
||
return normalizedStatus === 'none' ? 'N' : 'Y';
|
||
}
|
||
|
||
/**
|
||
* 规范订单列表单行输出,保证重量类型直接返回中文。
|
||
* @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),
|
||
create_channel: this.formatCreateChannelLabel(order.create_channel),
|
||
lock_status: this.normalizeLockStatusFlag(order.lock_status),
|
||
is_sn_order: String(order.has_sn_item || '').trim().toUpperCase() === 'Y' ? 'Y' : 'N',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 获取指定模块的角标展示值。
|
||
* @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);
|
||
let contextWarehouseId = this.getWarehouseId();
|
||
|
||
const hasContextWarehouseId = contextWarehouseId !== null
|
||
&& contextWarehouseId !== undefined
|
||
&& contextWarehouseId !== '';
|
||
const hasParamWarehouseId = warehouseId !== null
|
||
&& warehouseId !== undefined
|
||
&& warehouseId !== '';
|
||
|
||
if (!hasContextWarehouseId && !hasParamWarehouseId) {
|
||
throw new Error('缺少当前用户仓库上下文 store_id');
|
||
}
|
||
|
||
if (!hasContextWarehouseId) {
|
||
contextWarehouseId = warehouseId;
|
||
}
|
||
|
||
if (hasContextWarehouseId && hasParamWarehouseId
|
||
&& 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;
|
||
let contextWarehouseId = this.getWarehouseId();
|
||
const normalizedTableType = this.resolveOrderTableType({ tableType });
|
||
const actualWarehouseId = warehouseId ?? contextWarehouseId;
|
||
|
||
const hasContextWarehouseId = contextWarehouseId !== null
|
||
&& contextWarehouseId !== undefined
|
||
&& contextWarehouseId !== '';
|
||
const hasActualWarehouseId = actualWarehouseId !== null
|
||
&& actualWarehouseId !== undefined
|
||
&& actualWarehouseId !== '';
|
||
|
||
if (!hasContextWarehouseId && !hasActualWarehouseId) {
|
||
throw new Error('缺少当前用户仓库上下文 store_id');
|
||
}
|
||
|
||
if (!hasContextWarehouseId) {
|
||
contextWarehouseId = actualWarehouseId;
|
||
}
|
||
|
||
if (hasContextWarehouseId && hasActualWarehouseId
|
||
&& 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;
|
||
let contextWarehouseId = this.getWarehouseId();
|
||
const normalizedTableType = this.resolveOrderTableType({ tableType });
|
||
const actualWarehouseId = warehouseId ?? contextWarehouseId;
|
||
|
||
const hasContextWarehouseId = contextWarehouseId !== null
|
||
&& contextWarehouseId !== undefined
|
||
&& contextWarehouseId !== '';
|
||
const hasActualWarehouseId = actualWarehouseId !== null
|
||
&& actualWarehouseId !== undefined
|
||
&& actualWarehouseId !== '';
|
||
|
||
if (!hasContextWarehouseId && !hasActualWarehouseId) {
|
||
throw new Error('缺少当前用户仓库上下文 store_id');
|
||
}
|
||
|
||
if (!hasContextWarehouseId) {
|
||
contextWarehouseId = actualWarehouseId;
|
||
}
|
||
|
||
if (hasContextWarehouseId && hasActualWarehouseId
|
||
&& 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);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 查询订单关联运单信息。
|
||
*
|
||
* 强制同仓校验:查询条件必须同时包含订单ID与仓库ID,
|
||
* 禁止仅凭订单ID读取 wms_order_express,避免跨仓串读运单号。
|
||
* 仓库ID优先取订单详情行(order.warehouse_id),缺省时回退当前用户上下文仓库。
|
||
*
|
||
* @param {number|string} orderId 订单ID。
|
||
* @param {Object} [order] 订单详情行,用于补充 sys_logistics_code / sys_logistics_name 与仓库ID。
|
||
* @return {Promise<Object[]>} 运单信息列表。
|
||
*/
|
||
async getOrderExpressesByOrderId(orderId, order) {
|
||
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 [];
|
||
}
|
||
|
||
// 强制同仓校验:仓库ID优先取订单行,缺省回退当前上下文仓库;均缺失时拒绝读取
|
||
const contextWarehouseId = this.getWarehouseId();
|
||
const orderWarehouseId = Number(order && order.warehouse_id);
|
||
const warehouseId = Number.isFinite(orderWarehouseId) && orderWarehouseId > 0
|
||
? orderWarehouseId
|
||
: (contextWarehouseId !== null && contextWarehouseId !== undefined && contextWarehouseId !== ''
|
||
? Number(contextWarehouseId)
|
||
: 0);
|
||
|
||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||
return [];
|
||
}
|
||
|
||
const rows = await orderExpressModel.findAll({
|
||
where: {
|
||
order_id: normalizedOrderId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'logistics_interface_name', 'weighing_weight', 'business_key', 'create_at', 'package_material_id', 'package_material_name_snapshot' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
const sysLogisticsCode = order && order.sys_logistics_code != null
|
||
? String(order.sys_logistics_code).trim()
|
||
: '';
|
||
const sysLogisticsName = order && order.sys_logistics_name != null
|
||
? String(order.sys_logistics_name).trim()
|
||
: '';
|
||
|
||
return (Array.isArray(rows) ? rows : []).map(row => ({
|
||
waybill_code: String(row && row.waybill_code || '').trim(),
|
||
weighing_weight: row && row.weighing_weight != null ? Number(row.weighing_weight) : null,
|
||
sys_logistics_code: sysLogisticsCode,
|
||
sys_logistics_name: sysLogisticsName,
|
||
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),
|
||
logistics_interface_name: String(row && row.logistics_interface_name || '').trim(),
|
||
business_key: String(row && row.business_key || '').trim(),
|
||
create_at: row && row.create_at != null ? new Date(row.create_at).getTime() : null,
|
||
package_material_id: row && row.package_material_id != null ? Number(row.package_material_id) : null,
|
||
package_material_name_snapshot: row && row.package_material_name_snapshot != null ? String(row.package_material_name_snapshot).trim() : null,
|
||
}));
|
||
}
|
||
|
||
/**
|
||
* 归一化订单列表中的快递与系统名称字段。
|
||
* @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,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 批量补齐订单列表的快递号信息。
|
||
*
|
||
* 强制同仓校验:运单查询按「订单ID + 仓库ID」分组执行,
|
||
* 禁止仅凭订单ID读取 wms_order_express,避免跨仓串读运单号。
|
||
*
|
||
* @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;
|
||
|
||
// 强制同仓校验:逐订单解析仓库归属(行内 warehouse_id 优先,缺省回退当前上下文仓库),
|
||
// 无法确定仓库归属的订单不参与运单查询,避免仅凭订单ID跨仓串读
|
||
const contextWarehouseId = this.getWarehouseId();
|
||
const warehouseIdByOrder = new Map();
|
||
for (const item of list) {
|
||
const orderId = Number(item && item.id);
|
||
if (!Number.isFinite(orderId) || orderId <= 0) {
|
||
continue;
|
||
}
|
||
const rowWarehouseId = Number(item && item.warehouse_id);
|
||
if (Number.isFinite(rowWarehouseId) && rowWarehouseId > 0) {
|
||
warehouseIdByOrder.set(orderId, rowWarehouseId);
|
||
} else if (contextWarehouseId !== null && contextWarehouseId !== undefined && contextWarehouseId !== '') {
|
||
warehouseIdByOrder.set(orderId, Number(contextWarehouseId));
|
||
}
|
||
}
|
||
|
||
const scopedOrderIds = orderIds.filter(orderId => warehouseIdByOrder.has(orderId));
|
||
const expressRows = [];
|
||
if (scopedOrderIds.length > 0) {
|
||
const orderIdsByWarehouse = new Map();
|
||
for (const orderId of scopedOrderIds) {
|
||
const orderWarehouseId = warehouseIdByOrder.get(orderId);
|
||
if (!orderIdsByWarehouse.has(orderWarehouseId)) {
|
||
orderIdsByWarehouse.set(orderWarehouseId, []);
|
||
}
|
||
orderIdsByWarehouse.get(orderWarehouseId).push(orderId);
|
||
}
|
||
|
||
for (const [ orderWarehouseId, warehouseOrderIds ] of orderIdsByWarehouse.entries()) {
|
||
const rows = await orderExpressModel.findAll({
|
||
where: {
|
||
order_id: {
|
||
[Op.in]: warehouseOrderIds,
|
||
},
|
||
warehouse_id: orderWarehouseId,
|
||
},
|
||
attributes: [ 'id', 'order_id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'platform_code' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
if (Array.isArray(rows)) {
|
||
expressRows.push(...rows);
|
||
}
|
||
}
|
||
}
|
||
|
||
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);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 批量补齐订单列表的波次内序号(wms_order_wave_index.wave_index)。
|
||
* 表无记录或查询异常时降级为 0,不影响列表主流程。
|
||
* @param {Object[]} list 订单列表,每项需含 id(订单ID)。
|
||
* @return {Promise<Object[]>} 补齐 wave_index 后的列表。
|
||
*/
|
||
async attachOrderWaveIndex(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 => ({ ...item, wave_index: 0 }));
|
||
}
|
||
|
||
const warehouseId = this.getWarehouseId();
|
||
const { ctx } = this;
|
||
const waveIndexMap = new Map();
|
||
|
||
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
|
||
&& ctx.model && typeof ctx.model.query === 'function') {
|
||
try {
|
||
const rows = await ctx.model.query(`
|
||
SELECT order_id, wave_index
|
||
FROM wms_order_wave_index
|
||
WHERE warehouse_id = :warehouseId
|
||
AND order_id IN (:orderIds)
|
||
`, {
|
||
replacements: { warehouseId, orderIds },
|
||
type: ctx.model.QueryTypes && ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
for (const row of (Array.isArray(rows) ? rows : [])) {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
if (orderId > 0) {
|
||
waveIndexMap.set(orderId, Number(row && row.wave_index || 0));
|
||
}
|
||
}
|
||
} catch (error) {
|
||
ctx.logger && ctx.logger.warn && ctx.logger.warn('[order.base.attachOrderWaveIndex] 查询波次序号失败,已降级为 0', {
|
||
warehouseId,
|
||
orderCount: orderIds.length,
|
||
error: error && error.message ? error.message : `${error}`,
|
||
});
|
||
}
|
||
}
|
||
|
||
return list.map(item => {
|
||
const orderId = Number(item && item.id);
|
||
return {
|
||
...item,
|
||
wave_index: Number.isFinite(orderId) && orderId > 0 && waveIndexMap.has(orderId)
|
||
? waveIndexMap.get(orderId)
|
||
: 0,
|
||
};
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 提取订单列表中的运单号虚拟筛选条件。
|
||
* @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,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 提取买家留言虚拟筛选条件 buyer_message_has。
|
||
* 覆盖 buyer_message / seller_message / remark 三个字段,任一有值即为"有留言"。
|
||
* 将其从 where 中移除并解析为布尔值,后续在 buildWhere 之后注入 Sequelize 条件。
|
||
* @param {Object} whereInput 标准化后的 where 条件。
|
||
* @return {{ where: Object, buyerMessageHas: boolean|null }} 清洗后的 where 与买家留言标记。
|
||
*/
|
||
extractBuyerMessageHasVirtualFilter(whereInput = {}) {
|
||
const normalizedWhere = this.isPlainObject(whereInput)
|
||
? { ...whereInput }
|
||
: {};
|
||
const buyerMessageHasCondition = normalizedWhere.buyer_message_has;
|
||
|
||
delete normalizedWhere.buyer_message_has;
|
||
|
||
if (!buyerMessageHasCondition) {
|
||
return { where: normalizedWhere, buyerMessageHas: null };
|
||
}
|
||
|
||
const rawValue = this.isPlainObject(buyerMessageHasCondition)
|
||
&& Object.prototype.hasOwnProperty.call(buyerMessageHasCondition, 'value')
|
||
? buyerMessageHasCondition.value
|
||
: buyerMessageHasCondition;
|
||
|
||
// 兼容布尔值、字符串 'true'/'false'、'Y'/'N'、数字 1/0、以及前端 select 组件值 'has'/'empty'/'none'
|
||
const normalizedRawValue = typeof rawValue === 'string' ? rawValue.trim().toLowerCase() : rawValue;
|
||
if (rawValue === true || normalizedRawValue === 'true' || normalizedRawValue === 'y' || normalizedRawValue === 'has' || rawValue === 1) {
|
||
return { where: normalizedWhere, buyerMessageHas: true };
|
||
}
|
||
if (rawValue === false || normalizedRawValue === 'false' || normalizedRawValue === 'n' || normalizedRawValue === 'empty' || normalizedRawValue === 'none' || rawValue === 0) {
|
||
return { where: normalizedWhere, buyerMessageHas: false };
|
||
}
|
||
|
||
return { where: normalizedWhere, buyerMessageHas: null };
|
||
}
|
||
|
||
/**
|
||
* 提取 stock_query 虚拟筛选条件。
|
||
* 将其从 where 中移除并返回清洗后的 where 与 stock_query 关键字。
|
||
* @param {Object} whereInput 标准化后的 where 条件。
|
||
* @return {{ where: Object, stockQuery: string }} 清洗后的 where 与 stock_query 值。
|
||
*/
|
||
extractStockQueryVirtualFilter(whereInput = {}) {
|
||
const normalizedWhere = this.isPlainObject(whereInput)
|
||
? { ...whereInput }
|
||
: {};
|
||
const stockQueryCondition = normalizedWhere.stock_query;
|
||
|
||
delete normalizedWhere.stock_query;
|
||
|
||
if (!stockQueryCondition) {
|
||
return { where: normalizedWhere, stockQuery: '' };
|
||
}
|
||
|
||
const rawValue = this.isPlainObject(stockQueryCondition)
|
||
&& Object.prototype.hasOwnProperty.call(stockQueryCondition, 'value')
|
||
? stockQueryCondition.value
|
||
: stockQueryCondition;
|
||
|
||
const stockQuery = typeof rawValue === 'string' ? rawValue.trim() : '';
|
||
|
||
return { where: normalizedWhere, stockQuery };
|
||
}
|
||
|
||
/**
|
||
* 提取 wave_index(波次内序号)虚拟筛选条件。
|
||
* 序号存储在 wms_order_wave_index 副表,需先查副表得到订单 ID 集合再注入主查询。
|
||
* 支持 eq / in / gt / lt / ge / le / between / notbetween 等操作符,
|
||
* 其中 between 要求 value 为长度为 2 的数组(如 [1, 50])。
|
||
* @param {Object} whereInput 标准化后的 where 条件。
|
||
* @return {{ where: Object, waveIndexCondition: Object|null }} 清洗后的 where 与序号筛选条件。
|
||
*/
|
||
extractWaveIndexVirtualFilter(whereInput = {}) {
|
||
const normalizedWhere = this.isPlainObject(whereInput)
|
||
? { ...whereInput }
|
||
: {};
|
||
const waveIndexCondition = normalizedWhere.wave_index ?? normalizedWhere.waveIndex;
|
||
|
||
delete normalizedWhere.wave_index;
|
||
delete normalizedWhere.waveIndex;
|
||
|
||
// 条件为空时忽略
|
||
if (waveIndexCondition === undefined || waveIndexCondition === null || waveIndexCondition === '') {
|
||
return { where: normalizedWhere, waveIndexCondition: null };
|
||
}
|
||
|
||
if (this.isPlainObject(waveIndexCondition)
|
||
&& (waveIndexCondition.value === undefined || waveIndexCondition.value === null || waveIndexCondition.value === '')) {
|
||
return { where: normalizedWhere, waveIndexCondition: null };
|
||
}
|
||
|
||
// 兼容简写:wave_index 直接传数值时按 eq 处理
|
||
const normalizedCondition = this.isPlainObject(waveIndexCondition)
|
||
? { ...waveIndexCondition }
|
||
: { operator: 'eq', value: waveIndexCondition };
|
||
|
||
return { where: normalizedWhere, waveIndexCondition: normalizedCondition };
|
||
}
|
||
|
||
/**
|
||
* 提取 wave_scope(波次范围)虚拟筛选条件。
|
||
* 将其从 where 中移除并解析为波次范围值集合,后续直接生成订单表 wave_scope 字段过滤。
|
||
* 取值约定:0=未分配波次,1=大团购,2=散单,3=小团购,4=单品单件;value 支持单个值或数组(多选)。
|
||
* @param {Object} whereInput 标准化后的 where 条件。
|
||
* @return {{ where: Object, waveScope: number[]|null }} 清洗后的 where 与波次范围值集合。
|
||
*/
|
||
extractWaveScopeVirtualFilter(whereInput = {}) {
|
||
const normalizedWhere = this.isPlainObject(whereInput)
|
||
? { ...whereInput }
|
||
: {};
|
||
const waveScopeCondition = normalizedWhere.wave_scope ?? normalizedWhere.waveScope;
|
||
|
||
delete normalizedWhere.wave_scope;
|
||
delete normalizedWhere.waveScope;
|
||
|
||
// 条件为空时忽略
|
||
if (waveScopeCondition === undefined || waveScopeCondition === null || waveScopeCondition === '') {
|
||
return { where: normalizedWhere, waveScope: null };
|
||
}
|
||
|
||
const sourceValue = this.isPlainObject(waveScopeCondition)
|
||
&& Object.prototype.hasOwnProperty.call(waveScopeCondition, 'value')
|
||
? waveScopeCondition.value
|
||
: waveScopeCondition;
|
||
|
||
// 兼容简写:wave_scope 直接传数值或数组时按 eq/in 处理
|
||
const sourceItems = Array.isArray(sourceValue) ? sourceValue : [ sourceValue ];
|
||
const normalizedScopes = Array.from(new Set(
|
||
sourceItems
|
||
.filter(item => item !== undefined && item !== null && item !== '')
|
||
.map(item => Number(item))
|
||
));
|
||
|
||
for (const scope of normalizedScopes) {
|
||
if (!Number.isInteger(scope) || scope < 0 || scope > 4) {
|
||
throw new Error('wave_scope 参数不合法,仅支持 0(未分配波次)/1(大团购)/2(散单)/3(小团购)/4(单品单件)');
|
||
}
|
||
}
|
||
|
||
return {
|
||
where: normalizedWhere,
|
||
waveScope: normalizedScopes.length > 0 ? normalizedScopes : null,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 提取 is_sn_order(是否序列号订单)虚拟筛选条件。
|
||
*
|
||
* 订单表已冗余 has_sn_item 字段(建单时按明细 stock_warehouse.is_sn_mgmt 聚合),
|
||
* 因此这里仅做参数归一化,后续直接生成订单表字段条件,无需反查明细。
|
||
* 原始列 has_sn_item 仍走通用 where 解析,可继续按标准操作符(eq/ne/in 等)使用。
|
||
*
|
||
* 取值兼容:Y/N、1/0、true/false、是/否,以及 { value } 标准结构。
|
||
*
|
||
* @param {Object} whereInput 标准化后的 where 条件。
|
||
* @return {{ where: Object, isSnOrder: boolean|null }} 清洗后的 where 与序列号订单筛选值。
|
||
*/
|
||
extractSnOrderVirtualFilter(whereInput = {}) {
|
||
const normalizedWhere = this.isPlainObject(whereInput)
|
||
? { ...whereInput }
|
||
: {};
|
||
const snCondition = normalizedWhere.is_sn_order
|
||
?? normalizedWhere.isSnOrder;
|
||
|
||
delete normalizedWhere.is_sn_order;
|
||
delete normalizedWhere.isSnOrder;
|
||
|
||
if (snCondition === undefined || snCondition === null || snCondition === '') {
|
||
return { where: normalizedWhere, isSnOrder: null };
|
||
}
|
||
|
||
const rawValue = this.isPlainObject(snCondition)
|
||
&& Object.prototype.hasOwnProperty.call(snCondition, 'value')
|
||
? snCondition.value
|
||
: snCondition;
|
||
|
||
if (rawValue === undefined || rawValue === null || rawValue === '') {
|
||
return { where: normalizedWhere, isSnOrder: null };
|
||
}
|
||
|
||
const normalizedValue = typeof rawValue === 'string'
|
||
? rawValue.trim().toLowerCase()
|
||
: rawValue;
|
||
|
||
if (normalizedValue === true || normalizedValue === 1
|
||
|| [ 'y', 'yes', 'true', '1', '是' ].includes(normalizedValue)) {
|
||
return { where: normalizedWhere, isSnOrder: true };
|
||
}
|
||
|
||
if (normalizedValue === false || normalizedValue === 0
|
||
|| [ 'n', 'no', 'false', '0', '否' ].includes(normalizedValue)) {
|
||
return { where: normalizedWhere, isSnOrder: false };
|
||
}
|
||
|
||
throw new Error('is_sn_order 参数不合法,仅支持 Y/N(或 true/false、1/0)');
|
||
}
|
||
|
||
/**
|
||
* 构建 is_sn_order(是否序列号订单)筛选条件。
|
||
*
|
||
* has_sn_item='Y' 视为序列号订单;N 条件兼容历史 NULL 行(未回填前按非序列号订单处理)。
|
||
*
|
||
* @param {boolean|null} isSnOrder true=仅序列号订单,false=仅非序列号订单,null=不过滤。
|
||
* @return {Object|null} Sequelize 条件,无效值返回 null。
|
||
*/
|
||
buildSnOrderFilterCondition(isSnOrder) {
|
||
if (typeof isSnOrder !== 'boolean') {
|
||
return null;
|
||
}
|
||
|
||
const { Op } = this.app.Sequelize;
|
||
|
||
if (isSnOrder) {
|
||
return {
|
||
has_sn_item: { [Op.eq]: 'Y' },
|
||
};
|
||
}
|
||
|
||
return {
|
||
[Op.or]: [
|
||
{ has_sn_item: { [Op.is]: null } },
|
||
{ has_sn_item: { [Op.ne]: 'Y' } },
|
||
],
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 提取 sn_code(按 SN 码反查订单)虚拟筛选条件。
|
||
*
|
||
* 兼容 sn_code / snCode / sn_codes / snCodes 四种写法,值支持单个字符串
|
||
* (逗号/空格/分号分隔多个)、字符串数组,以及 { value } 标准结构。
|
||
* 取值仅做 trim 与去重,不做模糊匹配(扫码得到的是完整 SN 码)。
|
||
*
|
||
* @param {Object} whereInput 标准化后的 where 条件。
|
||
* @return {{ where: Object, snCodes: string[] }} 清洗后的 where 与 SN 码列表。
|
||
*/
|
||
extractSnCodeVirtualFilter(whereInput = {}) {
|
||
const normalizedWhere = this.isPlainObject(whereInput)
|
||
? { ...whereInput }
|
||
: {};
|
||
|
||
const rawCondition = normalizedWhere.sn_code
|
||
?? normalizedWhere.snCode
|
||
?? normalizedWhere.sn_codes
|
||
?? normalizedWhere.snCodes;
|
||
|
||
delete normalizedWhere.sn_code;
|
||
delete normalizedWhere.snCode;
|
||
delete normalizedWhere.sn_codes;
|
||
delete normalizedWhere.snCodes;
|
||
|
||
const value = this.isPlainObject(rawCondition)
|
||
&& Object.prototype.hasOwnProperty.call(rawCondition, 'value')
|
||
? rawCondition.value
|
||
: rawCondition;
|
||
|
||
const candidates = Array.isArray(value) ? value : [ value ];
|
||
const snCodes = Array.from(new Set(
|
||
candidates
|
||
.flatMap(item => String(item === undefined || item === null ? '' : item).split(/[\s,;]+/))
|
||
.map(code => code.trim())
|
||
.filter(Boolean)
|
||
));
|
||
|
||
return {
|
||
where: normalizedWhere,
|
||
snCodes,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 根据 SN 码查询 wms_order_item_sn 命中的订单ID。
|
||
*
|
||
* 订单表结构不变,仅用 SN 码表反查 order_id 后回填到订单列表条件中;
|
||
* 查询走 (warehouse_id, sn_code) 唯一键或 idx_wms_order_item_sn_sn_code。
|
||
*
|
||
* @param {string[]} snCodes SN 码列表。
|
||
* @param {number|string} [warehouseId] 仓库ID(必须与当前上下文一致)。
|
||
* @return {Promise<number[]>} 命中的订单ID列表。
|
||
*/
|
||
async findOrderIdsBySnCodes(snCodes = [], 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 normalizedSnCodes = Array.from(new Set(
|
||
(Array.isArray(snCodes) ? snCodes : [])
|
||
.map(code => String(code || '').trim())
|
||
.filter(Boolean)
|
||
));
|
||
|
||
if (normalizedSnCodes.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
const orderItemSnModel = this.ctx.model && this.ctx.model.OrderItemSn;
|
||
if (!orderItemSnModel || typeof orderItemSnModel.findAll !== 'function') {
|
||
return [];
|
||
}
|
||
|
||
const { Op } = this.app.Sequelize;
|
||
const rows = await orderItemSnModel.findAll({
|
||
where: {
|
||
warehouse_id: contextWarehouseId,
|
||
sn_code: { [Op.in]: normalizedSnCodes },
|
||
},
|
||
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)));
|
||
}
|
||
|
||
/**
|
||
* 根据 wave_index 筛选条件查询 wms_order_wave_index 命中的订单ID。
|
||
* @param {Object} waveIndexCondition 序号筛选条件(含 operator/value)。
|
||
* @param {number|string} warehouseId 仓库ID。
|
||
* @return {Promise<number[]>} 命中的订单ID列表。
|
||
*/
|
||
async findOrderIdsByWaveIndexCondition(waveIndexCondition = null, 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。');
|
||
}
|
||
|
||
if (!waveIndexCondition || !this.isPlainObject(waveIndexCondition)) {
|
||
return [];
|
||
}
|
||
|
||
const orderWaveIndexModel = this.ctx.model && this.ctx.model.OrderWaveIndex;
|
||
if (!orderWaveIndexModel || typeof orderWaveIndexModel.findAll !== 'function') {
|
||
return [];
|
||
}
|
||
|
||
const parsed = parseWhereConditions({
|
||
where: { wave_index: waveIndexCondition },
|
||
app: this.app,
|
||
});
|
||
|
||
if (!parsed.ok) {
|
||
throw new Error(`wave_index 参数解析失败: ${parsed.reason}`);
|
||
}
|
||
|
||
const { Sequelize } = this.app;
|
||
const conditions = Array.isArray(parsed.result.dynamicConditions)
|
||
? parsed.result.dynamicConditions
|
||
: [];
|
||
|
||
if (conditions.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
const waveIndexWhere = conditions.length > 1
|
||
? { [Sequelize.Op.and]: conditions }
|
||
: conditions[0];
|
||
|
||
const rows = await orderWaveIndexModel.findAll({
|
||
where: {
|
||
[Sequelize.Op.and]: [
|
||
waveIndexWhere,
|
||
{ warehouse_id: contextWarehouseId },
|
||
],
|
||
},
|
||
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)));
|
||
}
|
||
|
||
/**
|
||
* 根据波次范围(wave_scope)构建订单表 wave_scope 字段过滤条件。
|
||
* 订单表已冗余 wave_scope 字段(写入波次时维护),直接按字段过滤,
|
||
* 无需再反查 wms_wave_batch。
|
||
* @param {Array<number>} waveScopes 波次范围值集合(0/1/2/3/4)。
|
||
* @return {Object|null} Sequelize 条件,无有效范围时返回 null。
|
||
*/
|
||
buildWaveScopeFilterCondition(waveScopes = []) {
|
||
const { Op } = this.app.Sequelize;
|
||
const normalizedScopes = Array.from(new Set(
|
||
(Array.isArray(waveScopes) ? waveScopes : [ waveScopes ])
|
||
.filter(scope => scope !== undefined && scope !== null && scope !== '')
|
||
.map(scope => Number(scope))
|
||
)).filter(scope => Number.isInteger(scope) && scope >= 0 && scope <= 4);
|
||
|
||
if (normalizedScopes.length === 0) {
|
||
return null;
|
||
}
|
||
|
||
return {
|
||
wave_scope: {
|
||
[Op.in]: normalizedScopes,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 构建 buyer_message_has 虚拟字段的 Sequelize where 条件。
|
||
* 覆盖三个留言/备注字段:buyer_message、seller_message、remark。
|
||
* @param {boolean} hasMessage true=任一字段有留言,false=三个字段全部为空。
|
||
* @return {Object|null} Sequelize where 条件,无效时返回 null。
|
||
*/
|
||
buildBuyerMessageHasCondition(hasMessage) {
|
||
if (typeof hasMessage !== 'boolean') {
|
||
return null;
|
||
}
|
||
const { Op } = this.app.Sequelize;
|
||
const hasContent = col => ({
|
||
[Op.and]: [
|
||
{ [col]: { [Op.not]: null } },
|
||
{ [col]: { [Op.ne]: '' } },
|
||
],
|
||
});
|
||
const isEmpty = col => ({
|
||
[Op.or]: [
|
||
{ [col]: { [Op.is]: null } },
|
||
{ [col]: { [Op.eq]: '' } },
|
||
],
|
||
});
|
||
const fields = [ 'buyer_message', 'seller_message', 'remark' ];
|
||
if (hasMessage) {
|
||
return { [Op.or]: fields.map(col => hasContent(col)) };
|
||
}
|
||
return { [Op.and]: fields.map(col => isEmpty(col)) };
|
||
}
|
||
|
||
/**
|
||
* 将附加条件并入 queryWhere,兼容 flat 对象与 { [Op.and]: [...] } 结构。
|
||
* @param {Object} queryWhere 现有 Sequelize where 条件。
|
||
* @param {Object} extraCondition 待并入的条件。
|
||
* @return {Object} 合并后的 where 条件。
|
||
*/
|
||
appendConditionToWhere(queryWhere = {}, extraCondition = null) {
|
||
if (!extraCondition || !this.isPlainObject(extraCondition)
|
||
|| (Object.keys(extraCondition).length === 0 && Object.getOwnPropertySymbols(extraCondition).length === 0)) {
|
||
return queryWhere;
|
||
}
|
||
const { Op } = this.app.Sequelize;
|
||
|
||
if (!this.isPlainObject(queryWhere)
|
||
|| (Object.keys(queryWhere).length === 0 && Object.getOwnPropertySymbols(queryWhere).length === 0)) {
|
||
return extraCondition;
|
||
}
|
||
|
||
if (Array.isArray(queryWhere[Op.and])) {
|
||
return {
|
||
...queryWhere,
|
||
[Op.and]: [ ...queryWhere[Op.and], extraCondition ],
|
||
};
|
||
}
|
||
|
||
return {
|
||
[Op.and]: [ queryWhere, extraCondition ],
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 规范化运单号筛选输入,兼容字符串、数组与 { 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)));
|
||
}
|
||
|
||
/**
|
||
* 根据 stock_query 模糊查询 stock_warehouse(商品编码、商品名称、主键ID)和 stock_barcodes(条码),
|
||
* 找到匹配的 stock_id,再通过 order_items 查找关联的订单 ID。
|
||
* 若未匹配到任何 stock 则返回空数组,下游会将订单列表结果置空。
|
||
* @param {string} stockQuery 模糊查询关键词。
|
||
* @param {string} moduleName 模块名称(用于确定 order_items 表类型)。
|
||
* @param {number|string} [warehouseId] 仓库ID。
|
||
* @return {Promise<number[]>} 命中的订单ID列表。
|
||
*/
|
||
async findOrderIdsByStockQuery(stockQuery = '', moduleName = 'order', warehouseId = null) {
|
||
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。');
|
||
}
|
||
|
||
if (!stockQuery || typeof stockQuery !== 'string') {
|
||
return [];
|
||
}
|
||
|
||
const trimmedQuery = stockQuery.trim();
|
||
if (!trimmedQuery) {
|
||
return [];
|
||
}
|
||
|
||
const { Op } = this.app.Sequelize;
|
||
const likePattern = `%${trimmedQuery}%`;
|
||
|
||
// 第一步:从 stock_warehouse 模糊查询 item_code、item_name 和 id
|
||
const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse;
|
||
const stockIdsFromWarehouse = [];
|
||
if (stockWarehouseModel) {
|
||
const stockRows = await stockWarehouseModel.findAll({
|
||
where: {
|
||
warehouse_id: contextWarehouseId,
|
||
is_valid: 'Y',
|
||
[Op.or]: [
|
||
{ item_code: { [Op.like]: likePattern } },
|
||
{ item_name: { [Op.like]: likePattern } },
|
||
{ id: { [Op.like]: likePattern } },
|
||
],
|
||
},
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
for (const row of stockRows) {
|
||
stockIdsFromWarehouse.push(Number(row.id));
|
||
}
|
||
}
|
||
|
||
// 第二步:从 stock_barcodes 模糊查询 barcode
|
||
const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode;
|
||
const stockIdsFromBarcodes = [];
|
||
if (stockBarcodeModel) {
|
||
const barcodeRows = await stockBarcodeModel.findAll({
|
||
where: {
|
||
warehouse_id: contextWarehouseId,
|
||
barcode: { [Op.like]: likePattern },
|
||
},
|
||
attributes: [ 'stock_id' ],
|
||
raw: true,
|
||
});
|
||
for (const row of barcodeRows) {
|
||
stockIdsFromBarcodes.push(Number(row.stock_id));
|
||
}
|
||
}
|
||
|
||
// 第三步:合并去重所有匹配的 stock_id
|
||
const allStockIds = Array.from(new Set([ ...stockIdsFromWarehouse, ...stockIdsFromBarcodes ]))
|
||
.filter(id => Number.isFinite(id) && id > 0);
|
||
|
||
if (allStockIds.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
// 第四步:通过 order_items 查找关联的 order_id
|
||
const moduleConfig = this.getModuleConfig(moduleName);
|
||
const tableType = moduleConfig.modelType || 'current';
|
||
const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, contextWarehouseId);
|
||
const orderItemRows = await orderItemsModel.findAll({
|
||
where: {
|
||
stock_id: { [Op.in]: allStockIds },
|
||
},
|
||
attributes: [ 'order_id' ],
|
||
raw: true,
|
||
});
|
||
|
||
return Array.from(new Set(
|
||
(Array.isArray(orderItemRows) ? orderItemRows : [])
|
||
.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 { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere);
|
||
const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage);
|
||
const { where: whereAfterWaveIndex, waveIndexCondition } = this.extractWaveIndexVirtualFilter(whereAfterStockQuery);
|
||
const { where: whereAfterWaveScope, waveScope } = this.extractWaveScopeVirtualFilter(whereAfterWaveIndex);
|
||
const { where: whereAfterSnOrder, isSnOrder } = this.extractSnOrderVirtualFilter(whereAfterWaveScope);
|
||
const { where: whereAfterSnCode, snCodes } = this.extractSnCodeVirtualFilter(whereAfterSnOrder);
|
||
const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterSnCode);
|
||
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);
|
||
}
|
||
|
||
if (buyerMessageHas !== null) {
|
||
const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas);
|
||
queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition);
|
||
}
|
||
|
||
if (stockQuery) {
|
||
const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, moduleName, contextWarehouseId);
|
||
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds);
|
||
}
|
||
|
||
if (waveIndexCondition) {
|
||
const waveIndexOrderIds = await this.findOrderIdsByWaveIndexCondition(waveIndexCondition, contextWarehouseId);
|
||
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, waveIndexOrderIds);
|
||
}
|
||
|
||
if (waveScope) {
|
||
const waveScopeCondition = this.buildWaveScopeFilterCondition(waveScope);
|
||
queryWhere = this.appendConditionToWhere(queryWhere, waveScopeCondition);
|
||
}
|
||
|
||
if (isSnOrder !== null) {
|
||
const snOrderCondition = this.buildSnOrderFilterCondition(isSnOrder);
|
||
queryWhere = this.appendConditionToWhere(queryWhere, snOrderCondition);
|
||
}
|
||
|
||
if (snCodes.length > 0) {
|
||
const snOrderIds = await this.findOrderIdsBySnCodes(snCodes, contextWarehouseId);
|
||
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, snOrderIds);
|
||
}
|
||
|
||
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 normalized = list.map(order => this.normalizeOrderListItem(order));
|
||
|
||
// 批量查询货主备注(wms_store_warehouse.store_remask)
|
||
const storeRemarkMap = new Map();
|
||
if (normalized.length > 0 && this.ctx.model && this.ctx.model.StoreWarehouse) {
|
||
const storeIds = [
|
||
...new Set(
|
||
normalized
|
||
.map(row => Number(row.store_id || 0))
|
||
.filter(id => id > 0)
|
||
),
|
||
];
|
||
if (storeIds.length > 0) {
|
||
const swRows = await this.ctx.model.StoreWarehouse.findAll({
|
||
where: {
|
||
store_id: { [this.app.Sequelize.Op.in]: storeIds },
|
||
warehouse_id: contextWarehouseId,
|
||
},
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
raw: true,
|
||
});
|
||
for (const sw of (Array.isArray(swRows) ? swRows : [])) {
|
||
const sid = Number(sw.store_id || 0);
|
||
if (sid > 0 && !storeRemarkMap.has(sid)) {
|
||
storeRemarkMap.set(sid, String(sw.store_remask || '').trim());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
const listWithRemark = normalized.map(row => ({
|
||
...row,
|
||
store_remark: storeRemarkMap.has(Number(row.store_id || 0))
|
||
? storeRemarkMap.get(Number(row.store_id || 0))
|
||
: '',
|
||
}));
|
||
|
||
const normalizedList = await this.attachOrderExpressNumbers(listWithRemark);
|
||
const listWithWaveIndex = await this.attachOrderWaveIndex(normalizedList);
|
||
|
||
const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0;
|
||
|
||
return {
|
||
list: listWithWaveIndex,
|
||
pagination: {
|
||
page,
|
||
pageSize,
|
||
total,
|
||
totalPages,
|
||
hasPrevious: page > 1,
|
||
hasNext: page < totalPages,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 查询订单详情。
|
||
*
|
||
* 兜底查询:当表位类型为配送表(dispatch)且查询不到订单时,
|
||
* 自动回退到待处理表(current)再查询一次,避免订单在配送表与
|
||
* 待处理表之间流转后详情查询落空。
|
||
*
|
||
* @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 orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
|
||
|
||
// 实际使用的表位类型:配送表(dispatch)查询不到时兜底查询待处理表(current)
|
||
let actualTableType = tableType;
|
||
let orderModel = await this.getOrderModelByTableType(actualTableType, warehouseId);
|
||
let order = await orderModel.findOne({
|
||
where: orderWhere,
|
||
raw: true,
|
||
});
|
||
|
||
if (!order && actualTableType === 'dispatch') {
|
||
actualTableType = 'current';
|
||
orderModel = await this.getOrderModelByTableType(actualTableType, warehouseId);
|
||
order = await orderModel.findOne({
|
||
where: orderWhere,
|
||
raw: true,
|
||
});
|
||
}
|
||
|
||
if (!order) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const orderItemsModel = await this.getOrderItemsModelByTableType(actualTableType, warehouseId);
|
||
const orderItems = await orderItemsModel.findAll({
|
||
where: {
|
||
order_id: orderId,
|
||
},
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
// 通过 getStockDetails(带缓存)批量查询 stock_warehouse 标准信息
|
||
// 为 items 附加 image_url、barcodes、item_name 等标准字段
|
||
const orderItemsWithStockInfo = await this.attachStockDetailsToOrderItems(orderItems, warehouseId);
|
||
|
||
const expresses = await this.getOrderExpressesByOrderId(orderId, order);
|
||
const logs = await this.getOrderOperationLogs(orderId);
|
||
|
||
// 从运单列表中提取去重后的运单号数组
|
||
const waybillCodes = Array.isArray(expresses)
|
||
? [ ...new Set(expresses.map(expr => String(expr && expr.waybill_code || '').trim()).filter(Boolean)) ]
|
||
: [];
|
||
|
||
return {
|
||
detail: order,
|
||
items: orderItemsWithStockInfo,
|
||
expresses,
|
||
waybill_codes: waybillCodes,
|
||
logs,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 通过 stock_warehouse 带缓存的标准方法(getStockDetails),批量查询商品详情,
|
||
* 将 order_items 仅作为 stock_id 来源,返回 getStockDetails 标准格式数据。
|
||
* 每个结果会附带以下 order_items 关键关联字段:
|
||
* - plan_qty:需求量
|
||
* - order_line_no:行号
|
||
* - stock_id:原 order_items 中的 stock_id 关联键
|
||
* - order_item_id:原 order_items 主键 id,供下游(如 pendingOrder)关联使用
|
||
* - order_id:所属订单 id
|
||
*
|
||
* @param {Object[]} orderItems 订单商品列表。
|
||
* @param {number|string} warehouseId 仓库ID。
|
||
* @return {Promise<Object[]>} 以 stock_warehouse 标准格式为主,附带少量 order_items 关键字段的数据。
|
||
*/
|
||
async attachStockDetailsToOrderItems(orderItems = [], warehouseId) {
|
||
if (!Array.isArray(orderItems) || orderItems.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
// 构建 stockId → orderItem 关键字段的映射
|
||
const stockIdToOrderItemMap = new Map();
|
||
const stockIdsSet = new Set();
|
||
for (const item of orderItems) {
|
||
const stockId = Number(item && item.stock_id);
|
||
if (stockId) {
|
||
stockIdsSet.add(stockId);
|
||
// 同一个 stock_id 可能对应多条 order_items 行,保留最后一条的关键字段
|
||
stockIdToOrderItemMap.set(stockId, {
|
||
plan_qty: item.plan_qty != null ? item.plan_qty : 0,
|
||
order_line_no: item.order_line_no || '',
|
||
stock_id: stockId,
|
||
order_item_id: item.id != null ? item.id : 0,
|
||
order_id: item.order_id != null ? item.order_id : 0,
|
||
});
|
||
}
|
||
}
|
||
|
||
const stockIds = [ ...stockIdsSet ];
|
||
|
||
if (stockIds.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
/** @type {Map<number, Object>} */
|
||
const stockDetailMap = new Map();
|
||
try {
|
||
const stockWarehouseSvc = this.ctx.service?.systems?.stockWarehouse;
|
||
if (stockWarehouseSvc && typeof stockWarehouseSvc.getStockDetails === 'function') {
|
||
const stockDetails = await stockWarehouseSvc.getStockDetails(stockIds, { warehouseId });
|
||
for (const detail of stockDetails) {
|
||
stockDetailMap.set(Number(detail.id), detail);
|
||
}
|
||
}
|
||
} catch (error) {
|
||
this.ctx.logger?.warn?.('[order.base.attachStockDetailsToOrderItems] 查询 stock_warehouse 详情失败,已降级为原始 items', {
|
||
error: error.message,
|
||
});
|
||
return [];
|
||
}
|
||
|
||
// 降级:当 getStockDetails 缓存层没有返回某些 stockId 的数据时,直接查 DB 补齐
|
||
const missedIds = stockIds.filter(sid => !stockDetailMap.has(sid));
|
||
if (missedIds.length > 0) {
|
||
this.ctx.logger?.info?.('[order.base.attachStockDetailsToOrderItems] getStockDetails 未返回部分 stock 详情,降级为直接查 DB', {
|
||
missedIds,
|
||
warehouseId,
|
||
});
|
||
try {
|
||
const { app } = this;
|
||
const [ fallbackStockRows, fallbackBarcodeRows, fallbackImageRows ] = await Promise.all([
|
||
app.model.StockWarehouse.findAll({
|
||
where: { id: { [app.Sequelize.Op.in]: missedIds }, is_valid: 'Y' },
|
||
attributes: [
|
||
'id', 'item_code', 'item_name', 'sku_property',
|
||
'quantity', 'locked_quantity', 'is_batch_mgmt',
|
||
'is_shelf_life_mgmt', 'is_images',
|
||
'store_id', 'packing_requirements', 'pick_requirements',
|
||
'recheck_requirements', 'merge_requirements', 'stock_unit',
|
||
],
|
||
raw: true,
|
||
}),
|
||
app.model.StockBarcode.findAll({
|
||
where: { stock_id: { [app.Sequelize.Op.in]: missedIds } },
|
||
attributes: [ 'id', 'barcode', 'stock_id' ],
|
||
raw: true,
|
||
}),
|
||
app.model.FileReference.findAll({
|
||
where: {
|
||
business_type: 'stock',
|
||
business_id: { [app.Sequelize.Op.in]: missedIds.map(String) },
|
||
},
|
||
include: [{
|
||
model: app.model.File,
|
||
as: 'file',
|
||
attributes: [ 'file_url' ],
|
||
required: false,
|
||
}],
|
||
order: [[ 'display_order', 'ASC' ]],
|
||
raw: true,
|
||
}),
|
||
]);
|
||
|
||
const fallbackBarcodeMap = new Map();
|
||
for (const row of fallbackBarcodeRows) {
|
||
const sid = row.stock_id;
|
||
if (!fallbackBarcodeMap.has(sid)) {
|
||
fallbackBarcodeMap.set(sid, []);
|
||
}
|
||
fallbackBarcodeMap.get(sid).push({
|
||
id: row.id,
|
||
barcode: row.barcode,
|
||
});
|
||
}
|
||
|
||
const fallbackImageUrlMap = new Map();
|
||
for (const row of fallbackImageRows) {
|
||
const sid = Number(row.business_id);
|
||
if (!fallbackImageUrlMap.has(sid)) {
|
||
fallbackImageUrlMap.set(sid, []);
|
||
}
|
||
const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || '';
|
||
if (url) {
|
||
fallbackImageUrlMap.get(sid).push(url);
|
||
}
|
||
}
|
||
|
||
for (const row of fallbackStockRows) {
|
||
stockDetailMap.set(row.id, {
|
||
id: row.id,
|
||
item_code: row.item_code,
|
||
item_name: row.item_name,
|
||
sku_property: row.sku_property || '',
|
||
quantity: row.quantity || 0,
|
||
locked_quantity: row.locked_quantity || 0,
|
||
is_batch_mgmt: row.is_batch_mgmt || 'N',
|
||
is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N',
|
||
is_images: row.is_images || 'N',
|
||
store_id: row.store_id != null ? Number(row.store_id) : 0,
|
||
packing_requirements: row.packing_requirements || '',
|
||
pick_requirements: (row.merge_requirements || 'Y') === 'Y'
|
||
? (row.packing_requirements || '')
|
||
: (row.pick_requirements || ''),
|
||
recheck_requirements: (row.merge_requirements || 'Y') === 'Y'
|
||
? (row.packing_requirements || '')
|
||
: (row.recheck_requirements || ''),
|
||
merge_requirements: row.merge_requirements || 'Y',
|
||
stock_unit: row.stock_unit || '',
|
||
image_url: fallbackImageUrlMap.get(row.id) || [],
|
||
barcodes: fallbackBarcodeMap.get(row.id) || [],
|
||
});
|
||
}
|
||
} catch (fallbackError) {
|
||
this.ctx.logger?.warn?.('[order.base.attachStockDetailsToOrderItems] 降级查询也失败', {
|
||
error: fallbackError.message,
|
||
});
|
||
}
|
||
}
|
||
|
||
// 以 getStockDetails 返回的标准格式为主,
|
||
// 仅从 order_items 中附加 plan_qty、order_line_no、stock_id、order_item_id、order_id 关键关联字段
|
||
return stockIds.map(stockId => {
|
||
const stockDetail = stockDetailMap.get(stockId) || null;
|
||
const orderItemFields = stockIdToOrderItemMap.get(stockId) || {};
|
||
|
||
if (!stockDetail) {
|
||
return {
|
||
id: stockId,
|
||
item_code: '',
|
||
item_name: '',
|
||
sku_property: '',
|
||
quantity: 0,
|
||
locked_quantity: 0,
|
||
is_batch_mgmt: 'N',
|
||
is_shelf_life_mgmt: 'N',
|
||
is_images: 'N',
|
||
store_id: 0,
|
||
packing_requirements: '',
|
||
pick_requirements: '',
|
||
recheck_requirements: '',
|
||
merge_requirements: 'Y',
|
||
stock_unit: '',
|
||
image_url: [],
|
||
barcodes: [],
|
||
plan_qty: orderItemFields.plan_qty || 0,
|
||
order_line_no: orderItemFields.order_line_no || '',
|
||
stock_id: orderItemFields.stock_id || stockId,
|
||
order_item_id: orderItemFields.order_item_id || 0,
|
||
order_id: orderItemFields.order_id || 0,
|
||
};
|
||
}
|
||
|
||
return {
|
||
id: stockDetail.id,
|
||
item_code: stockDetail.item_code || '',
|
||
item_name: stockDetail.item_name || '',
|
||
sku_property: stockDetail.sku_property || '',
|
||
quantity: stockDetail.quantity != null ? stockDetail.quantity : 0,
|
||
locked_quantity: stockDetail.locked_quantity != null ? stockDetail.locked_quantity : 0,
|
||
is_batch_mgmt: stockDetail.is_batch_mgmt || 'N',
|
||
is_shelf_life_mgmt: stockDetail.is_shelf_life_mgmt || 'N',
|
||
is_images: stockDetail.is_images || 'N',
|
||
store_id: stockDetail.store_id != null ? Number(stockDetail.store_id) : 0,
|
||
packing_requirements: stockDetail.packing_requirements || '',
|
||
pick_requirements: stockDetail.pick_requirements || '',
|
||
recheck_requirements: stockDetail.recheck_requirements || '',
|
||
merge_requirements: stockDetail.merge_requirements || 'Y',
|
||
stock_unit: stockDetail.stock_unit || '',
|
||
image_url: Array.isArray(stockDetail.image_url) ? [ ...stockDetail.image_url ] : [],
|
||
barcodes: Array.isArray(stockDetail.barcodes) ? [ ...stockDetail.barcodes ] : [],
|
||
plan_qty: orderItemFields.plan_qty || 0,
|
||
order_line_no: orderItemFields.order_line_no || '',
|
||
stock_id: orderItemFields.stock_id || stockId,
|
||
order_item_id: orderItemFields.order_item_id || 0,
|
||
order_id: orderItemFields.order_id || 0,
|
||
};
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 获取订单操作日志列表。
|
||
* @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;
|