'use strict'; const MainService = require('../../main'); const { parseWhereConditions } = require('../../../lib/query_condition_parser'); const DEFAULT_PAGE_SIZE = 20; const MAX_PAGE_SIZE = 200; 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_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 ], }, }, }, outboundOrder: { modelType: 'current', defaultWhere: { outbound_status: { operator: 'in', value: [ 'none', 'padding' ], }, step: { operator: 'in', value: [ 1, 2 ], }, }, }, 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 { /** * 获取当前请求对应的仓库ID。 * @return {number|string|null} 仓库ID。 */ getWarehouseId() { const { ctx } = this; const warehouseId = ctx?.user?.store_id ?? null; return warehouseId === '' ? null : warehouseId; } /** * 规范分页参数并限制 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 {string} moduleName 模块名称。 * @param {number|string} [warehouseId] 仓库ID。 * @return {Promise} 角标展示值。 */ 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} 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} 订单头模型。 */ 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} 订单商品模型。 */ 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} 运单信息列表。 */ 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, 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} 补齐后的列表。 */ 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} sort 排序参数。 * @param {string} [moduleName='order'] 模块名称。 * @return {Array>} 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} 列表与分页信息。 */ 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 mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), where); const queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { specialFieldMap: { quickWhere: { bucket: 'quick', }, }, }); const model = await this.getOrderModel(moduleName, contextWarehouseId); const order = this.buildListOrder(requestData.sort, moduleName); const offset = (page - 1) * pageSize; const [ total, list ] = await Promise.all([ model.count({ where: queryWhere }), model.findAll({ where: queryWhere, limit: pageSize, offset, order, raw: true, }), ]); const normalizedList = await this.attachOrderExpressNumbers(list); 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} 订单头、商品明细和运单信息。 */ 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 expresses = await this.getOrderExpressesByOrderId(orderId); const waybillCodes = Array.from(new Set(expresses .map(item => String(item && item.waybill_code || '').trim()) .filter(Boolean))); return { order, detail: order, orderItems: Array.isArray(orderItems) ? orderItems : [], items: Array.isArray(orderItems) ? orderItems : [], expresses, waybill_codes: waybillCodes, }; } /** * 将审核状态映射为 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} 更新后的订单信息。 */ 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, 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} 更新后的订单信息。 */ 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;