'use strict'; const { Service } = require('egg'); const { ORDER_STATUS, ORDER_ACTIVE_STATUSES, ORDER_STATUS_LIST, ORDER_STATUS_LABELS, ORDER_ARCHIVE_MONTHS, ORDER_INDEX_TABLE, ORDER_ITEM_TABLE, normalizeOrderStatus, orderStatusLabel, orderModelName, orderTableOf, orderCopyFields, } = require('../lib/orderStatus'); const { resolveAccountName } = require('../lib/accountProfile'); const { validateReceiver } = require('../lib/orderReceiver'); const { validateItems } = require('../lib/orderDeliveryItems'); const { notNullDefaultColumnNames } = require('../lib/orderFields'); const { lockOrderStock, releaseOrderStock, deductOrderStock } = require('../utils/orderStock'); /** 归档任务单轮单表最多迁移的条数(避免一次事务搬运过多数据) */ const ARCHIVE_BATCH_LIMIT = 200; /** 手工创建订单在扩展字段(extend_props)中写入的标记(与老发货单一致) */ const HANDMADE_ORDER_LABEL = '手工单'; /** 可编辑单据头/明细的状态(仅未审核的订单允许改) */ const EDITABLE_STATUSES = [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION ]; /** 可删除的状态(已审核及之后禁止删除,避免绕过状态机;已作废保留痕迹同样不可删) */ const DELETABLE_STATUSES = [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION, ORDER_STATUS.CANCELED ]; /** * 生成换号后的新单号:`X` → `X_1` → `X_2`(与老发货单驳回换号口径一致) * @param {String} orderNo 当前单号 * @return {String} 新单号 */ function nextOrderNo(orderNo) { const current = String(orderNo == null ? '' : orderNo).trim(); if (!current) return current; const matched = current.match(/^(.*)_(\d+)$/); if (!matched) return `${current}_1`; return `${matched[1]}_${Number(matched[2]) + 1}`; } /** * 新建订单时**不允许接口直接写入**的托管字段(由系统/回调/状态流转写入) * 其余业务字段(仓库/物流/金额/收件人 12 项/时间/留言/扩展属性…)均可由接口写入,便于导入与迁移。 */ const CREATE_MANAGED_FIELDS = [ 'wms_status', 'wms_order_no', 'wms_synced_at', 'submit_status', 'submit_order_no', 'submit_at', 'submit_msg', 'express_code', 'express_codes', 'operator_name', 'stock_locked', 'pushed_at', 'wms_push_result', 'item_total', 'item_kind', 'shop_sync_status', 'shop_sync_retry_count', 'audit_by', 'audit_time', 'void_at', 'void_by', 'void_reason', 'legacy_order_id', ]; /** * 把入参时间转成 Date:纯日期按当天 00:00:00 / 23:59:59 处理(区间结束补到当天最后一刻) * @param {*} value 入参时间 * @param {Boolean} isEnd 是否为区间结束 * @return {Date|null} Date 或 null */ function toDate(value, isEnd) { const raw = String(value == null ? '' : value).trim(); if (!raw) return null; const dateOnly = /^\d{4}-\d{2}-\d{2}$/.test(raw); const text = dateOnly ? `${raw}T${isEnd ? '23:59:59' : '00:00:00'}` : raw.replace(' ', 'T'); const date = new Date(text); return Number.isNaN(date.getTime()) ? null : date; } /** * 文本归一化(去空白,空值返回 null) * @param {*} value 原值 * @return {String|null} 归一化结果 */ function trimOrNull(value) { const text = String(value == null ? '' : value).trim(); return text === '' ? null : text; } /** * 订单状态流转服务 * * 数据模型:order_index(索引,订单 ID 全局唯一 + current_table/current_status) * + order_status_pending / exception / outsourcing / delivery(4 张同构状态表) * + order_status_history * 流转实现:按索引表定位订单当前所在表 → 目标表 INSERT ... SELECT(原样搬运业务字段与创建时间) * → 来源表删除 → 索引表更新 current_table/current_status,全程单事务。 */ class OrderStatusService extends Service { /** 状态常量(供控制器/其他服务引用,避免枚举漂移) */ static get STATUS() { return ORDER_STATUS; } /** * 按状态取状态表模型 * @param {String} status 状态值(pending/exception/outsourcing/delivery/history) * @return {Object} 对应状态表模型 */ _model(status) { return this.ctx.model[orderModelName(status)]; } /** * 订单 id 列表归一化(去重、去非法值) * @param {Array} ids 原始 id 数组 * @return {Array} 归一化后的 id 数组 */ _normalizeIds(ids) { const list = Array.isArray(ids) ? ids : []; return [ ...new Set(list.map(item => Number(item)).filter(id => Number.isInteger(id) && id > 0)) ]; } /** * 按 id 取索引表记录(主体隔离),并校验全部命中 * @param {Array} ids 订单 id * @param {Number} principalId 主体ID * @return {Promise} 索引记录 */ async _loadIndexRows(ids, principalId) { const { ctx } = this; const Op = ctx.app.Sequelize.Op; if (!ids.length) { const err = new Error('请选择至少一条订单'); err.status = 400; throw err; } const rows = await ctx.model.OrderIndex.findAll({ where: { id: { [Op.in]: ids }, principal_id: principalId }, }); if (rows.length !== ids.length) { const err = new Error(`存在 ${ids.length - rows.length} 条订单不存在或不属于当前主体`); err.status = 400; throw err; } // 索引表说在哪张表,就在哪张表;按表分组校验一次(避免逐条查询),找不到说明数据不一致 const idsByStatus = new Map(); for (const row of rows) { if (!idsByStatus.has(row.current_status)) idsByStatus.set(row.current_status, []); idsByStatus.get(row.current_status).push(Number(row.id)); } for (const [ status, groupIds ] of idsByStatus) { const found = await this._model(status).findAll({ where: { id: { [Op.in]: groupIds }, principal_id: principalId }, attributes: [ 'id' ], }); if (found.length !== groupIds.length) { const row = rows.find(item => item.current_status === status); const err = new Error( `订单 ${row.order_no}(id=${row.id})在 ${orderTableOf(status)} 中不存在,数据不一致请联系管理员` ); err.status = 400; throw err; } } return rows; } /** * 跨表搬运:目标表 INSERT ... SELECT → 来源表删除 → 索引表改 current_table/current_status * * 用 SQL 而非模型实例,是为了原样保留 created_at(归档判断依赖创建时间,不能因流转被刷新)。 * @param {Object} p 参数 * @param {String} p.fromStatus 来源状态(= 来源表) * @param {String} p.toStatus 目标状态(= 目标表) * @param {Array} p.ids 订单 id * @param {Number} p.principalId 主体ID * @param {Object} [p.overrides] 需要改写的列(列名 → 值;值为 undefined 表示原样搬运) * @param {Object} p.transaction 事务 * @return {Promise} 搬运条数 */ async _moveRows({ fromStatus, toStatus, ids, principalId, overrides = {}, transaction }) { const { ctx } = this; const Op = ctx.app.Sequelize.Op; const fromTable = orderTableOf(fromStatus); const toTable = orderTableOf(toStatus); const now = new Date(); const toHistory = toStatus === ORDER_STATUS.HISTORY; // 搬运列按字段定义派生(新增扩展字段会自动纳入),排除 id/status/created_at/updated_at const copyFields = orderCopyFields(ctx.app.Sequelize); // 只保留需要改写的列(值为 undefined 视为不改写,仍按原值搬运) const overrideFields = Object.entries(overrides).filter(([ , value ]) => value !== undefined); // id 取自索引表(订单全局唯一 ID),必须显式带上:目标表主键不自增 const insertCols = [ 'id', ...copyFields, 'status', 'created_at', 'updated_at' ]; if (toHistory) insertCols.push('archived_at', 'transferred_at'); const replacements = { ids, principalId, status: toStatus, now }; // 改写列在 copyFields 内:用占位符替换该列取值,其余列原样搬运 const overrideMap = new Map(overrideFields); const selectCols = [ 'id', ...copyFields.map(col => { if (!overrideMap.has(col)) return col; const key = `ov_${col}`; // Sequelize 位置参数只支持标量:JSON 列(如 wms_push_result / extend_props)先转 JSON 字符串 const raw = overrideMap.get(col); replacements[key] = raw !== null && typeof raw === 'object' && !(raw instanceof Date) ? JSON.stringify(raw) : raw; return `:${key}`; }) ]; selectCols.push(':status', 'created_at', ':now'); if (toHistory) selectCols.push(':now', ':now'); await ctx.model.query( `INSERT INTO \`${toTable}\` (${insertCols.join(', ')}) SELECT ${selectCols.join(', ')} FROM \`${fromTable}\` WHERE principal_id = :principalId AND id IN (:ids)`, { replacements, transaction } ); // 写入条数必须与预期一致,否则整体回滚(避免出现「来源表已删、目标表没写」) const inserted = await this._model(toStatus).count({ where: { principal_id: principalId, id: { [Op.in]: ids } }, transaction, }); if (inserted !== ids.length) { const err = new Error(`流转失败:预期写入 ${ids.length} 条,实际 ${inserted} 条(已回滚)`); err.status = 500; throw err; } await this._model(fromStatus).destroy({ where: { principal_id: principalId, id: { [Op.in]: ids } }, transaction, }); await ctx.model.OrderIndex.update({ current_table: toStatus, current_status: toStatus, }, { where: { principal_id: principalId, id: { [Op.in]: ids } }, transaction, }); return ids.length; } /** * 通用流转编排:校验前置状态 → 按来源状态分组搬运(单事务) * @param {Object} p 参数 * @param {Array} p.ids 订单 id * @param {Array} p.allowedFrom 允许的来源状态 * @param {String} p.toStatus 目标状态 * @param {String} p.actionLabel 动作名(用于报错文案) * @param {String} [p.remark] 需要改写的备注 * @param {Object} [p.overrides] 需要改写的其它列(列名 → 值) * @param {Function} [p.beforeMove] 搬运前的钩子(同事务内执行,用于库存动作等) * @param {Number} [p.principalId] 主体ID(内部任务 / 回调无登录态时显式传入) * @return {Promise} { count, status, status_label, order_nos } */ async _transition({ ids, allowedFrom, toStatus, actionLabel, remark, overrides = {}, beforeMove, principalId: overridePrincipalId }) { const { ctx } = this; const principalId = overridePrincipalId || ctx.state.principalId; const idList = this._normalizeIds(ids); const indexRows = await this._loadIndexRows(idList, principalId); const invalid = indexRows.filter(row => !allowedFrom.includes(row.current_status)); if (invalid.length) { const fromLabels = allowedFrom.map(orderStatusLabel).join(' / '); const err = new Error( `「${actionLabel}」仅适用于${fromLabels}的订单,当前有 ${invalid.length} 条状态不符(如 ${invalid[0].order_no})` ); err.status = 400; throw err; } const groups = new Map(); for (const row of indexRows) { if (!groups.has(row.current_status)) groups.set(row.current_status, []); groups.get(row.current_status).push(Number(row.id)); } const finalOverrides = remark === undefined ? overrides : { ...overrides, remark }; const transaction = await ctx.model.transaction(); try { if (beforeMove) await beforeMove({ indexRows, transaction }); for (const [ fromStatus, groupIds ] of groups) { await this._moveRows({ fromStatus, toStatus, ids: groupIds, principalId, overrides: finalOverrides, transaction }); } await transaction.commit(); } catch (err) { await transaction.rollback(); throw err; } return { count: indexRows.length, status: toStatus, status_label: orderStatusLabel(toStatus), order_nos: indexRows.map(row => row.order_no), }; } /** * 列表分页(按状态定位状态表;历史表另返回归档/转入时间) * @param {Object} p 查询参数(status/page/pageSize + 各筛选项,见控制器注解) * @return {Promise<{list: Array, total: Number}>} 列表与总数 */ async list(p) { const { ctx } = this; const Op = ctx.app.Sequelize.Op; const principalId = ctx.state.principalId; const status = normalizeOrderStatus(p.status, ORDER_STATUS.PENDING); const Model = this._model(status); const where = { principal_id: principalId, status }; const orderNo = trimOrNull(p.order_no); const parentOrderNo = trimOrNull(p.parent_order_no); const receiver = trimOrNull(p.receiver); const address = trimOrNull(p.address); const remark = trimOrNull(p.remark); const keyword = trimOrNull(p.keyword); if (orderNo) where.order_no = { [Op.like]: `%${orderNo}%` }; if (parentOrderNo) where.parent_order_no = { [Op.like]: `%${parentOrderNo}%` }; if (receiver) where.receiver = { [Op.like]: `%${receiver}%` }; if (address) where.address = { [Op.like]: `%${address}%` }; if (remark) where.remark = { [Op.like]: `%${remark}%` }; if (p.shop_id !== undefined && p.shop_id !== '' && p.shop_id !== null) where.shop_id = Number(p.shop_id); if (keyword) { where[Op.or] = [ { order_no: { [Op.like]: `%${keyword}%` } }, { parent_order_no: { [Op.like]: `%${keyword}%` } }, { receiver: { [Op.like]: `%${keyword}%` } }, { address: { [Op.like]: `%${keyword}%` } }, ]; } const createdFrom = toDate(p.created_from, false); const createdTo = toDate(p.created_to, true); if (createdFrom || createdTo) { where.created_at = {}; if (createdFrom) where.created_at[Op.gte] = createdFrom; if (createdTo) where.created_at[Op.lte] = createdTo; } if (status === ORDER_STATUS.HISTORY) { const archivedFrom = toDate(p.archived_from, false); const archivedTo = toDate(p.archived_to, true); if (archivedFrom || archivedTo) { where.archived_at = {}; if (archivedFrom) where.archived_at[Op.gte] = archivedFrom; if (archivedTo) where.archived_at[Op.lte] = archivedTo; } } const { count, rows } = await Model.findAndCountAll({ where, offset: p.offset, limit: p.limit, order: [[ 'id', 'DESC' ]], }); const list = rows.map(row => row.get({ plain: true })); await this._attachListMeta(list, principalId, status); return { list, total: count }; } /** * 列表行补充展示信息:状态中文、店铺名称、商品明细摘要、索引表所在表 * @param {Array} list 列表行 * @param {Number} principalId 主体ID * @param {String} status 当前状态 * @return {Promise} 无 */ async _attachListMeta(list, principalId, status) { const { ctx } = this; const Op = ctx.app.Sequelize.Op; if (!list.length) return; for (const row of list) { row.status_label = orderStatusLabel(row.status); row.current_table = status; row.product_summary = this._productSummary(row.product_info); row.product_kind = Array.isArray(row.product_info) ? row.product_info.length : 0; } // 无 product_info 快照(新建发货单走 items 明细、老数据搬迁)时,按明细表现算摘要, // 保证列表「商品明细」列口径统一(商品名 × 数量),而不是退化成「N 种商品」 const needSummary = list.filter(row => !row.product_summary); if (needSummary.length) { const items = await ctx.model.OrderStatusItem.findAll({ where: { principal_id: principalId, order_id: { [Op.in]: needSummary.map(row => Number(row.id)) } }, attributes: [ 'order_id', 'item_name', 'item_code', 'plan_qty', 'order_line_no' ], order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]], }); const byOrder = new Map(); for (const item of items) { const orderId = Number(item.order_id); if (!byOrder.has(orderId)) byOrder.set(orderId, []); byOrder.get(orderId).push(item.get({ plain: true })); } for (const row of needSummary) { const lines = byOrder.get(Number(row.id)) || []; row.product_summary = this._itemSummary(lines); if (!row.item_kind) row.item_kind = lines.length; if (row.item_total == null) { row.item_total = lines.reduce((sum, line) => sum + (Number(line.plan_qty) || 0), 0); } } } // 店铺名称(状态表只存 shop_id,列表按 id 批量补名称) const shopIds = [ ...new Set(list.map(row => Number(row.shop_id)).filter(id => Number.isInteger(id) && id > 0)) ]; if (shopIds.length) { const shops = await ctx.model.Shop.findAll({ where: { id: { [Op.in]: shopIds }, principal_id: principalId }, attributes: [ 'id', 'name' ], }); const nameById = new Map(shops.map(shop => [ Number(shop.id), shop.name ])); for (const row of list) row.shop_name = nameById.get(Number(row.shop_id)) || null; } } /** * 明细行摘要:`商品名称 ×数量`,最多展示 3 项(与 product_info 摘要同口径) * @param {Array} lines 明细行(含 item_name / item_code / plan_qty) * @return {String} 摘要文案(无明细返回 '') */ _itemSummary(lines) { const list = Array.isArray(lines) ? lines : []; if (!list.length) return ''; const parts = list.slice(0, 3).map(line => { const name = line.item_name || line.item_code || '未知商品'; const qty = line.plan_qty == null ? '' : Number(line.plan_qty); return qty === '' ? String(name) : `${name} ×${qty}`; }); return list.length > 3 ? `${parts.join(';')} 等 ${list.length} 种` : parts.join(';'); } /** * 商品明细摘要:`商品名称 × 数量`,最多展示 3 项 * @param {*} productInfo 商品明细(JSON 数组) * @return {String} 摘要文案(无明细返回 '') */ _productSummary(productInfo) { if (!Array.isArray(productInfo) || !productInfo.length) return ''; const parts = productInfo.slice(0, 3).map(item => { const name = (item && (item.item_name || item.item_code)) || '未知商品'; const qty = item && item.quantity != null ? item.quantity : ''; return qty === '' ? String(name) : `${name} ×${qty}`; }); return productInfo.length > 3 ? `${parts.join(';')} 等 ${productInfo.length} 种` : parts.join(';'); } /** * 把明细行转成列表摘要用的 product_info 快照(商品编码/名称/数量/单价) * @param {Array} items 明细数组 * @return {Array|null} 快照数组(无明细返回 null) */ _productInfoFromItems(items) { const list = Array.isArray(items) ? items : []; if (!list.length) return null; return list.map(item => ({ item_code: trimOrNull(item && item.item_code), item_name: trimOrNull(item && item.item_name), quantity: item && item.plan_qty != null && item.plan_qty !== '' ? Number(item.plan_qty) : null, price: item && item.actual_price != null && item.actual_price !== '' ? Number(item.actual_price) : null, })); } /** * 归一化商品明细快照(只保留白名单字段,数量转数字) * @param {*} value 入参商品明细 * @return {Array|null} 归一化结果 */ _normalizeProductInfo(value) { if (value === undefined || value === null || value === '') return null; if (!Array.isArray(value)) { const err = new Error('product_info(商品明细)需为数组'); err.status = 400; throw err; } return value.map(item => ({ item_code: trimOrNull(item && item.item_code), item_name: trimOrNull(item && item.item_name), quantity: item && item.quantity != null && item.quantity !== '' ? Number(item.quantity) : null, price: item && item.price != null && item.price !== '' ? Number(item.price) : null, })); } /** * 抽取可由接口写入的扩展业务字段(白名单:老表的仓库/物流/金额/收件人/时间/留言等) * 空字符串归一为 null;托管字段(CREATE_MANAGED_FIELDS)与结构字段(id/status/时间戳)一律剔除。 * * 非空且有默认值的列(金额类:total_amount / discount_amount / freight / ar_amount / got_amount 等) * 传 null 时直接跳过,由数据库默认值(0)兜底,避免 notNull Violation。 * @param {Object} payload 请求体 * @return {Object} 可写入的字段子集 */ _pickCreateFields(payload) { const { ctx } = this; const allowed = new Set(orderCopyFields(ctx.app.Sequelize)); const keepDefault = new Set(notNullDefaultColumnNames(ctx.app.Sequelize)); const picked = {}; for (const [ key, value ] of Object.entries(payload || {})) { if (!allowed.has(key)) continue; if (CREATE_MANAGED_FIELDS.includes(key)) continue; if (value === undefined) continue; if (value === null && keepDefault.has(key)) continue; picked[key] = value === '' ? null : value; } return picked; } /** * 按收件人分区字段拼接地址快照(未显式传 address 时使用):省市区镇 + 详细地址 * @param {Object} fields 已抽取的字段 * @return {String|null} 地址快照 */ _composeAddress(fields) { const parts = [ fields.province, fields.city, fields.area, fields.town, fields.detail_address ] .map(part => String(part == null ? '' : part).trim()) .filter(Boolean); if (!parts.length) return null; return parts.join('').slice(0, 255); } /** * 新建订单(含发货单口径:可直接带明细创建) * * 单号规则(与老发货单 / 拆单口径一致): * - 显式传 order_no:校验主体内唯一后使用 * - 未传 order_no 且传了 parent_order_no:`{parent_order_no}-{序号}`(拆单场景) * - 都未传:取索引表自增 ID 生成 `FH_{id}`(手工建单场景) * @param {Object} payload 创建参数(可含 items[] 商品明细) * @return {Promise} { id, order_no, status, status_label, item_count } */ async create(payload = {}) { const { ctx } = this; const principalId = ctx.state.principalId; const parentOrderNo = trimOrNull(payload.parent_order_no); let orderNo = trimOrNull(payload.order_no); if (orderNo) { const dup = await ctx.model.OrderIndex.count({ where: { principal_id: principalId, order_no: orderNo } }); if (dup) { const err = new Error(`order_no(订单号)${orderNo} 已存在`); err.status = 400; throw err; } } let shopId = null; if (payload.shop_id !== undefined && payload.shop_id !== null && payload.shop_id !== '') { shopId = Number(payload.shop_id); const shop = await ctx.model.Shop.findOne({ where: { id: shopId, principal_id: principalId }, attributes: [ 'id', 'name' ], }); if (!shop) { const err = new Error('店铺不存在或不属于当前主体'); err.status = 404; throw err; } } // 仓库:可空(审核前补齐即可),但填了必须是当前主体的仓库,并快照 warehouse_code const fields = this._pickCreateFields(payload); if (fields.warehouse_id !== undefined && fields.warehouse_id !== null && fields.warehouse_id !== '') { const warehouseId = Number(fields.warehouse_id); const warehouse = await ctx.model.Warehouse.findOne({ where: { id: warehouseId, principal_id: principalId }, attributes: [ 'id', 'code' ], }); if (!warehouse) { const err = new Error('仓库不存在或不属于当前主体'); err.status = 404; throw err; } fields.warehouse_id = warehouseId; if (!fields.warehouse_code) fields.warehouse_code = warehouse.code; } const items = Array.isArray(payload.items) ? payload.items : []; if (items.length) { const invalid = validateItems(items); if (!invalid.ok) { const err = new Error(invalid.message); err.status = 400; throw err; } } else { const receiverError = validateReceiver({ ...fields, receiver: payload.receiver }); if (receiverError) { const err = new Error(receiverError); err.status = 400; throw err; } } // 明细优先:未传 product_info 时按 items 生成快照,列表摘要口径统一 const productInfo = this._normalizeProductInfo(payload.product_info) || this._productInfoFromItems(items); const address = trimOrNull(payload.address) || this._composeAddress(fields); const transaction = await ctx.model.transaction(); try { // 先落索引表拿全局唯一 ID:单号缺省时按 FH_{id} 生成(与老发货单号一致) if (!orderNo && !parentOrderNo) { orderNo = `FH_TMP_${Date.now()}_${Math.floor(Math.random() * 100000)}`; } const index = await ctx.model.OrderIndex.create({ order_no: orderNo || `FH_TMP_${Date.now()}_${Math.floor(Math.random() * 100000)}`, parent_order_no: parentOrderNo, principal_id: principalId, current_table: ORDER_STATUS.PENDING, current_status: ORDER_STATUS.PENDING, }, { transaction }); if (!orderNo) { // 有来源订单号:按「来源订单号-序号」生成(序号按索引表内该来源已有订单数 +1,归档后仍连续) const childCount = await ctx.model.OrderIndex.count({ where: { principal_id: principalId, parent_order_no: parentOrderNo }, transaction, }); orderNo = `${parentOrderNo}-${childCount}`; await index.update({ order_no: orderNo }, { transaction }); } else if (String(orderNo).startsWith('FH_TMP_')) { orderNo = `FH_${index.id}`; await index.update({ order_no: orderNo }, { transaction }); } const { name: shopNick } = shopId ? await ctx.model.Shop.findByPk(shopId, { attributes: [ 'name' ], transaction }) || {} : {}; await this._model(ORDER_STATUS.PENDING).create({ ...fields, id: index.id, order_no: orderNo, parent_order_no: parentOrderNo, principal_id: principalId, shop_id: shopId, shop_nick: shopNick || fields.shop_nick || null, product_info: productInfo, receiver: trimOrNull(payload.receiver), address, status: ORDER_STATUS.PENDING, remark: trimOrNull(payload.remark), extend_props: fields.extend_props || { labels: HANDMADE_ORDER_LABEL }, place_order_time: fields.place_order_time || new Date(), created_by: ctx.userId, }, { transaction }); if (items.length) { await this._replaceItems(index.id, principalId, items, transaction); await this._recalcItemStat(index.id, principalId, ORDER_STATUS.PENDING, transaction); } await transaction.commit(); return { id: Number(index.id), order_no: orderNo, status: ORDER_STATUS.PENDING, status_label: orderStatusLabel(ORDER_STATUS.PENDING), item_count: items.length, }; } catch (err) { await transaction.rollback(); throw err; } } /** * 重算单据的明细统计(item_total 总量 / item_kind 种类数 / item_amount 商品总金额) * * 商品总金额 = Σ(plan_qty × actual_price),与老发货单 `recalcOrderDelivery` 口径一致: * 明细增删改后自动回写,不依赖前端传值 * @param {Number} orderId 订单 id * @param {Number} principalId 主体ID * @param {String} status 订单当前状态 * @param {Object} [transaction] 事务 * @return {Promise} 无 */ async _recalcItemStat(orderId, principalId, status = ORDER_STATUS.PENDING, transaction) { const { ctx } = this; const lines = await ctx.model.OrderStatusItem.findAll({ where: { order_id: orderId, principal_id: principalId }, attributes: [ 'plan_qty', 'actual_price' ], transaction, }); let itemTotal = 0; let itemAmount = 0; for (const line of lines) { const qty = Number(line.plan_qty) || 0; itemTotal += qty; itemAmount += qty * (Number(line.actual_price) || 0); } await this._model(status).update( { item_total: Number(itemTotal.toFixed(3)), item_kind: lines.length, item_amount: Number(itemAmount.toFixed(2)), }, { where: { id: orderId, principal_id: principalId }, transaction } ); } /** * 覆盖式写入明细(先清空后写入,行号按数组顺序补全) * @param {Number} orderId 订单 id * @param {Number} principalId 主体ID * @param {Array} items 明细数组 * @param {Object} [transaction] 事务 * @return {Promise} 写入的明细 */ async _replaceItems(orderId, principalId, items, transaction) { const { ctx } = this; await ctx.model.OrderStatusItem.destroy({ where: { order_id: orderId, principal_id: principalId }, transaction }); const rows = items.map((item, idx) => this._buildItemRow(item, { principalId, orderId, lineIndex: idx })); return ctx.model.OrderStatusItem.bulkCreate(rows, { transaction }); } /** * 组装明细行(字段口径对齐 order_status_items:发货单明细 + 平台明细的超集) * @param {Object} raw 明细原始数据 * @param {Object} opts { principalId, orderId, lineIndex } * @return {Object} 行数据 */ _buildItemRow(raw, opts = {}) { const body = raw || {}; const lineIndex = Number(opts.lineIndex) || 0; const num = value => (value == null || value === '' ? null : Number(value)); return { principal_id: opts.principalId, order_id: opts.orderId, shop_id: num(body.shop_id), order_line_no: String(body.order_line_no == null || body.order_line_no === '' ? lineIndex + 1 : body.order_line_no), item_id: num(body.item_id), item_code: body.item_code == null ? null : String(body.item_code).trim(), item_name: body.item_name == null ? null : String(body.item_name).trim(), plan_qty: Number(body.plan_qty == null ? 0 : body.plan_qty), actual_price: num(body.actual_price), retail_price: num(body.retail_price), ext_code: body.ext_code == null ? null : String(body.ext_code).trim(), inventory_type: String(body.inventory_type || 'ZP').trim().toUpperCase() || 'ZP', source_order_code: body.source_order_code == null ? null : String(body.source_order_code).trim(), sub_source_order_code: body.sub_source_order_code == null ? null : String(body.sub_source_order_code).trim(), stock_id: num(body.stock_id), extend_props: body.extend_props && typeof body.extend_props === 'object' ? body.extend_props : null, product_id: num(body.product_id), combo_product_id: num(body.combo_product_id), shop_product_id: num(body.shop_product_id), item_type: Number(body.item_type || 0) || 0, parse_status: Number(body.parse_status || 0) || 0, parse_msg: body.parse_msg == null ? null : String(body.parse_msg).trim(), outer_item_id: body.outer_item_id == null ? null : String(body.outer_item_id).trim(), outer_sku_id: body.outer_sku_id == null ? null : String(body.outer_sku_id).trim(), sku_code: body.sku_code == null ? null : String(body.sku_code).trim(), spec: body.spec == null ? null : String(body.spec).trim(), image: body.image == null ? null : String(body.image).trim(), quantity: Number(body.quantity == null ? body.plan_qty || 0 : body.quantity), price: num(body.price == null ? body.actual_price : body.price), total_amount: Number(body.total_amount == null ? 0 : body.total_amount), raw: body.raw && typeof body.raw === 'object' ? body.raw : null, }; } /** * 批量审核:待审核 / 异常 → 待推送 * * 与老发货单口径一致: * - 必须已录入明细、且已选择店铺(推送时 shopNick 取店铺名称匹配快递策略) * - **审核即锁定库存**(按明细 plan_qty 占用可用,不足则失败),锁定与状态流转同事务 * - 写入审核人(主体账号名称,推送为 operatorName)与审核时间,并清空上一轮推送痕迹 * - 多选时逐单独立事务:库存不足等失败只跳过该单,失败明细见 failures * @param {Object} p { ids } * @return {Promise} { count, status, status_label, failed, failures } */ async audit(p = {}) { const { ctx } = this; const principalId = ctx.state.principalId; const idList = this._normalizeIds(p.ids); const operatorName = await resolveAccountName(ctx, ctx.userId, principalId); // 单条:直接抛出业务错误(前端弹单条原因);多条:逐单独立事务 + 失败清单 if (idList.length === 1) { const result = await this._auditOne(idList[0], principalId, operatorName); return { count: 1, status: ORDER_STATUS.QUEUED, status_label: orderStatusLabel(ORDER_STATUS.QUEUED), order_nos: [ result.order_no ], stock_locked: result.stock_locked, }; } const failures = []; const done = []; for (const id of idList) { try { done.push(await this._auditOne(id, principalId, operatorName)); } catch (err) { failures.push({ id, message: err.message }); ctx.logger.warn(`[order-status] 批量审核跳过 id=${id}:${err.message}`); } } return { count: done.length, status: ORDER_STATUS.QUEUED, status_label: orderStatusLabel(ORDER_STATUS.QUEUED), order_nos: done.map(item => item.order_no), failed: failures.length, failures: failures.slice(0, 10), }; } /** * 单条审核(锁定库存 + 待审核/异常 → 待推送,单事务) * @param {Number} id 订单 id * @param {Number} principalId 主体ID * @param {String} operatorName 审核人名称(推送 operatorName) * @return {Promise} { id, order_no, stock_locked } */ async _auditOne(id, principalId, operatorName) { const { ctx } = this; const [ row ] = await this._loadIndexRows([ id ], principalId); if (![ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION ].includes(row.current_status)) { const err = new Error(`订单 ${row.order_no} 当前为「${orderStatusLabel(row.current_status)}」,仅待审核 / 异常可审核`); err.status = 400; throw err; } const detail = await this._model(row.current_status).findByPk(id); const itemCount = await ctx.model.OrderStatusItem.count({ where: { order_id: id, principal_id: principalId } }); if (!itemCount) { const err = new Error(`订单 ${row.order_no} 无商品明细,无法审核`); err.status = 400; throw err; } if (!(Number(detail.shop_id) > 0)) { const err = new Error(`订单 ${row.order_no} 未设置店铺,无法审核:请先选择店铺(批量操作 → 设置所属店铺)`); err.status = 400; throw err; } // 仓库必填:推送仓库需要 warehouseCode 与仓库接口配置,缺仓库的单据进队列后必然推不出去 if (!(Number(detail.warehouse_id) > 0)) { const err = new Error(`订单 ${row.order_no} 未设置仓库,无法审核:请先选择仓库`); err.status = 400; throw err; } const transaction = await ctx.model.transaction(); try { let lockResult; try { lockResult = await lockOrderStock(ctx, detail, { createdBy: ctx.userId, transaction }); } catch (err) { if (err.code === 'INSUFFICIENT_STOCK') { const product = await ctx.model.Product.findByPk(err.productId, { attributes: [ 'item_code', 'item_name' ] }); const label = product ? `${product.item_name}(${product.item_code})` : `商品#${err.productId}`; const ex = new Error(`库存不足,无法审核:${label} 可用 ${err.available},需 ${err.require}`); ex.status = 400; throw ex; } throw err; } // 审核痕迹与状态流转同事务:流转时会被原样搬到目标状态表 await this._model(row.current_status).update({ audit_by: ctx.userId, audit_time: new Date(), operator_name: operatorName || null, pushed_at: null, wms_push_result: null, }, { where: { id, principal_id: principalId }, transaction }); await this._moveRows({ fromStatus: row.current_status, toStatus: ORDER_STATUS.QUEUED, ids: [ id ], principalId, transaction, }); await transaction.commit(); return { id, order_no: row.order_no, stock_locked: lockResult.affected }; } catch (err) { await transaction.rollback(); throw err; } } /** * 手工标记推送结果(待推送 → 委外中 / 异常):无外部仓库时的流转入口,也可用于修正外部实际结果 * @param {Object} p { ids, outcome: 'success'|'failed', remark } * @return {Promise} 流转结果 */ async push(p = {}) { const outcome = String(p.outcome == null ? '' : p.outcome).trim().toLowerCase(); if (![ 'success', 'failed' ].includes(outcome)) { const err = new Error('outcome 取值非法:success 推送成功(→ 委外中)/ failed 推送失败(→ 异常)'); err.status = 400; throw err; } const failed = outcome === 'failed'; const remark = failed ? trimOrNull(p.remark) || '推送外部失败' : undefined; // 推送失败需释放审核时锁定的库存(与老发货单「推送失败退回」一致) const beforeMove = failed ? this._releaseStockHook('推送失败,释放锁定库存') : undefined; return this._transition({ ids: p.ids, allowedFrom: [ ORDER_STATUS.QUEUED ], toStatus: failed ? ORDER_STATUS.EXCEPTION : ORDER_STATUS.OUTSOURCING, actionLabel: failed ? '标记推送失败' : '标记推送成功', remark, beforeMove, }); } /** * 释放库存的流转前置钩子(同事务内执行,未锁定则自动跳过) * @param {String} remark 释放备注(写库存流水) * @return {Function} 钩子函数 */ _releaseStockHook(remark) { return async ({ indexRows, transaction }) => { const { ctx } = this; for (const row of indexRows) { const detail = await this._model(row.current_status).findByPk(row.id, { transaction }); if (!detail) continue; await releaseOrderStock(ctx, detail, { createdBy: ctx.userId, remark, transaction }); } }; } /** * 推送失败 → 异常(释放审核锁定的库存;供推送服务 / 定时任务调用) * @param {Object} p 参数 * @param {Array} p.ids 订单 id * @param {Number} p.principalId 主体ID(任务无登录态时必传) * @param {String} [p.reason] 异常原因(写入备注) * @return {Promise} 流转结果 */ async markPushFailed(p = {}) { return this._transition({ ids: p.ids, principalId: p.principalId, allowedFrom: [ ORDER_STATUS.QUEUED ], toStatus: ORDER_STATUS.EXCEPTION, actionLabel: '推送失败转异常', remark: trimOrNull(p.reason) || '推送仓库失败,已转异常', beforeMove: this._releaseStockHook('推送失败,释放锁定库存'), }); } /** * 推送成功:待推送 → 委外中(由推送服务在 WMS 成功响应后调用,写入推送痕迹) * @param {Object} p 参数 * @param {Array} p.ids 订单 id * @param {Number} [p.principalId] 主体ID(任务无登录态时显式传入) * @param {Object} [p.overrides] 需要一并改写的列(如 wms_status / wms_order_no / pushed_at) * @return {Promise} 流转结果 */ async markPushed(p = {}) { return this._transition({ ids: p.ids, principalId: p.principalId, allowedFrom: [ ORDER_STATUS.QUEUED ], toStatus: ORDER_STATUS.OUTSOURCING, actionLabel: '推送成功转委外中', overrides: p.overrides || {}, }); } /** * 批量转回待审核:异常 → 待审核 * @param {Object} p { ids } * @return {Promise} 流转结果 */ async returnToPending(p = {}) { return this._transition({ ids: p.ids, allowedFrom: [ ORDER_STATUS.EXCEPTION ], toStatus: ORDER_STATUS.PENDING, actionLabel: '批量转回待审核', }); } /** * 驳回:待推送 → 待审核 * * 与老发货单一致:驳回即换号(`X` → `X_1` → `X_2`,避免重推时外部判「单号已存在」), * 释放审核锁定的库存,并清空审核 / 推送痕迹(重试计数归零); * 已推送成功的(委外中)不再支持驳回:需先用「取消」(会同步取消外部单据)。 * @param {Object} p { ids } * @return {Promise} { count, status, status_label, items } */ async reject(p = {}) { return this._singleFlow({ ids: p.ids, allowedFrom: [ ORDER_STATUS.QUEUED ], toStatus: ORDER_STATUS.PENDING, actionLabel: '驳回', releaseRemark: '订单驳回释放锁定库存', renameNo: true, clearAudit: true, }); } /** * 取消:待审核 / 异常 / 待推送 / 委外中 → 已取消(释放锁定库存;已配送/已作废/已取消不可取消) * * 已推送仓库的在途订单(委外中)会先调用 WMS `order.cancel` 取消外部单据,取消失败(如仓库已开始配货) * 则不流转状态并返回失败原因;取消成功后释放审核锁定的库存(与状态流转同事务)。 * @param {Object} p { ids, remark } * @return {Promise} 流转结果 */ async cancel(p = {}) { const { ctx } = this; const principalId = ctx.state.principalId; const indexRows = await this._loadIndexRows(this._normalizeIds(p.ids), principalId); // 已推送的在途订单:先取消外部单据(外部取消成功才继续释放本地锁定,避免「外部已取消、本地仍锁定」) for (const row of indexRows) { const detail = await this._model(row.current_status).findByPk(row.id); if (!detail || (detail.pushed_at == null && detail.wms_order_no == null)) continue; const result = await ctx.service.orderWms.cancelRemoteOrder(detail); if (!result.ok) { const err = new Error(`订单 ${row.order_no} ${result.message}`); err.status = 502; throw err; } const prev = detail.wms_push_result && typeof detail.wms_push_result === 'object' ? detail.wms_push_result : {}; await detail.update({ wms_push_result: { ...prev, cancelResult: result.response, cancelledAt: new Date().toISOString() }, }); } return this._transition({ ids: p.ids, allowedFrom: [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION, ORDER_STATUS.QUEUED, ORDER_STATUS.OUTSOURCING ], toStatus: ORDER_STATUS.CANCELED, actionLabel: '取消订单', remark: trimOrNull(p.remark) || undefined, beforeMove: this._releaseStockHook('订单取消释放锁定库存'), }); } /** * 作废:待审核 / 异常 / 待推送 → 已作废(记录作废人 / 时间 / 原因,释放锁定库存) * * 与老发货单口径一致:作废针对尚未递交仓库成功的单据;已推送成功的(委外中)请用「取消」 * @param {Object} p { ids, void_reason, remark } * @return {Promise} 流转结果 */ async voidOrder(p = {}) { const { ctx } = this; const reason = trimOrNull(p.void_reason) || null; return this._transition({ ids: p.ids, allowedFrom: [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION, ORDER_STATUS.QUEUED ], toStatus: ORDER_STATUS.VOID, actionLabel: '作废订单', remark: trimOrNull(p.remark) || undefined, overrides: { void_at: new Date(), void_by: ctx.userId, void_reason: reason, }, beforeMove: this._releaseStockHook('订单作废释放锁定库存'), }); } /** * 恢复:已取消 / 已作废 → 待审核 * * 与老发货单一致:**曾推送过的单据恢复时换号**(WMS 侧单号唯一,取消/作废后原号仍被占用), * 并清空审核 / 推送痕迹与作废原因(重回待审核,重试计数归零) * @param {Object} p { ids } * @return {Promise} { count, status, status_label, items } */ async restore(p = {}) { return this._singleFlow({ ids: p.ids, allowedFrom: [ ORDER_STATUS.CANCELED, ORDER_STATUS.VOID ], toStatus: ORDER_STATUS.PENDING, actionLabel: '恢复订单', renameIfPushed: true, clearAudit: true, clearVoid: true, }); } /** * 单据级流转(逐单独立事务,支持换号 / 清痕迹) * @param {Object} p 参数 * @param {Array} p.ids 订单 id * @param {Array} p.allowedFrom 允许的来源状态 * @param {String} p.toStatus 目标状态 * @param {String} p.actionLabel 动作名(用于报错文案) * @param {String} [p.releaseRemark] 传值则先释放锁定库存 * @param {Boolean} [p.renameNo] 是否总是换号 * @param {Boolean} [p.renameIfPushed] 仅在推送过时换号 * @param {Boolean} [p.clearAudit] 是否清空审核 / 推送痕迹 * @param {Boolean} [p.clearVoid] 是否清空作废痕迹 * @return {Promise} { count, status, status_label, items } */ async _singleFlow(p) { const { ctx } = this; const principalId = ctx.state.principalId; const idList = this._normalizeIds(p.ids); const indexRows = await this._loadIndexRows(idList, principalId); const invalid = indexRows.filter(row => !p.allowedFrom.includes(row.current_status)); if (invalid.length) { const fromLabels = p.allowedFrom.map(orderStatusLabel).join(' / '); const err = new Error( `「${p.actionLabel}」仅适用于${fromLabels}的订单,当前有 ${invalid.length} 条状态不符(如 ${invalid[0].order_no})` ); err.status = 400; throw err; } const items = []; for (const row of indexRows) { const transaction = await ctx.model.transaction(); try { const detail = await this._model(row.current_status).findByPk(row.id, { transaction }); if (p.releaseRemark) { await releaseOrderStock(ctx, detail, { createdBy: ctx.userId, remark: p.releaseRemark, transaction }); } // 是否推送过:pushed_at 在每次真实推送前写入,推送结果也落在 wms_push_result const pushedBefore = detail.pushed_at != null || detail.wms_push_result != null; const shouldRename = p.renameNo || (p.renameIfPushed && pushedBefore); const newNo = shouldRename ? nextOrderNo(row.order_no) : null; const overrides = {}; if (newNo) overrides.order_no = newNo; if (p.clearAudit) { overrides.audit_by = null; overrides.audit_time = null; overrides.operator_name = null; overrides.pushed_at = null; overrides.wms_push_result = null; overrides.wms_status = null; overrides.wms_order_no = null; overrides.wms_synced_at = null; // 已推送过的单据换号后重推,库存锁定随之释放 → 标记归零(未推送过的单据保持原锁定) if (pushedBefore) overrides.stock_locked = 0; } if (p.clearVoid) { overrides.void_at = null; overrides.void_by = null; overrides.void_reason = null; } await this._moveRows({ fromStatus: row.current_status, toStatus: p.toStatus, ids: [ row.id ], principalId, overrides, transaction, }); if (newNo) { await ctx.model.OrderIndex.update({ order_no: newNo }, { where: { id: row.id, principal_id: principalId }, transaction }); } await transaction.commit(); items.push({ id: row.id, order_no: newNo || row.order_no, bill_no_changed: Boolean(newNo) }); } catch (err) { await transaction.rollback(); throw err; } } return { count: items.length, status: p.toStatus, status_label: orderStatusLabel(p.toStatus), items, }; } /** * 发货确认(WMS 回传 deliveryorder.confirm):委外中 → 配送,并扣减库存 * @param {Object} p 参数 * @param {Array} p.ids 订单 id * @param {Number} [p.principalId] 主体ID(回调 / 任务无登录态时显式传入) * @return {Promise} 流转结果 */ async confirmDelivery(p = {}) { return this._transition({ ids: p.ids, principalId: p.principalId, allowedFrom: [ ORDER_STATUS.OUTSOURCING ], toStatus: ORDER_STATUS.DELIVERY, actionLabel: '发货确认', beforeMove: this._deductStockHook('订单发货确认扣减库存'), }); } /** * 扣减库存的流转前置钩子(同事务内执行,未锁定则自动跳过) * @param {String} remark 备注(写库存流水) * @return {Function} 钩子函数 */ _deductStockHook(remark) { return async ({ indexRows, transaction }) => { const { ctx } = this; for (const row of indexRows) { const detail = await this._model(row.current_status).findByPk(row.id, { transaction }); if (!detail) continue; await deductOrderStock(ctx, detail, { createdBy: ctx.userId, remark, transaction }); } }; } /** * 订单详情(单据头 + 商品明细 + 索引表定位信息) * @param {Object} p { id } * @return {Promise} { order, items, status_label, current_table } */ async detail(p = {}) { const { ctx } = this; const principalId = ctx.state.principalId; const [ row ] = await this._loadIndexRows([ p.id ], principalId); const order = await this._model(row.current_status).findByPk(row.id); const plain = order.get({ plain: true }); plain.status_label = orderStatusLabel(plain.status); plain.current_table = row.current_status; plain.product_summary = this._productSummary(plain.product_info); if (plain.shop_id) { const shop = await ctx.model.Shop.findByPk(plain.shop_id, { attributes: [ 'id', 'name' ] }); if (shop) plain.shop_name = shop.name; } if (plain.warehouse_id) { const warehouse = await ctx.model.Warehouse.findByPk(plain.warehouse_id, { attributes: [ 'id', 'code', 'name' ] }); if (warehouse) { plain.warehouse_code = plain.warehouse_code || warehouse.code; plain.warehouse_name = warehouse.name; } } const items = await this.listItems({ order_id: row.id }); return { order: plain, items: items.list }; } /** * 明细列表(单据头/详情/明细管理共用) * @param {Object} p { order_id } * @return {Promise<{list: Array, total: Number}>} 明细列表 */ async listItems(p = {}) { const { ctx } = this; const principalId = ctx.state.principalId; const orderId = Number(p.order_id); if (!orderId) { const err = new Error('order_id 为必填项'); err.status = 400; throw err; } const items = await ctx.model.OrderStatusItem.findAll({ where: { order_id: orderId, principal_id: principalId }, order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]], }); return { list: items.map(item => item.get({ plain: true })), total: items.length }; } /** * 覆盖写入明细(新增/编辑明细均走此接口,整体替换后重算统计) * @param {Object} p { order_id, items } * @return {Promise<{total: Number, list: Array}>} 写入后的明细 */ async saveItems(p = {}) { const { ctx } = this; const principalId = ctx.state.principalId; const orderId = Number(p.order_id); const items = Array.isArray(p.items) ? p.items : []; const [ row ] = await this._loadIndexRows([ orderId ], principalId); if (!EDITABLE_STATUSES.includes(row.current_status)) { const err = new Error(`订单当前为「${orderStatusLabel(row.current_status)}」,仅待审核 / 异常可维护商品明细`); err.status = 400; throw err; } if (!items.length) { const err = new Error('明细不能为空:至少保留一行商品'); err.status = 400; throw err; } const invalid = validateItems(items); if (!invalid.ok) { const err = new Error(invalid.message); err.status = 400; throw err; } const transaction = await ctx.model.transaction(); try { await this._replaceItems(orderId, principalId, items, transaction); await this._recalcItemStat(orderId, principalId, row.current_status, transaction); // 同步刷新快照,保证列表「商品明细」列与实际明细一致 await this._model(row.current_status).update( { product_info: this._productInfoFromItems(items) }, { where: { id: orderId, principal_id: principalId }, transaction } ); await transaction.commit(); } catch (err) { await transaction.rollback(); throw err; } return this.listItems({ order_id: orderId }); } /** * 编辑单据头(仅待审核 / 异常可编辑;仓库/店铺变更同步刷新快照,收件人按合并结果校验) * * 传 items 时同一请求内覆盖式保存明细(空行由前端剔除),明细统计与商品总金额随后自动重算 * @param {Object} p { id, ...变更字段, items? } * @return {Promise} { id, order_no } */ async update(p = {}) { const { ctx } = this; const principalId = ctx.state.principalId; const [ row ] = await this._loadIndexRows([ p.id ], principalId); if (!EDITABLE_STATUSES.includes(row.current_status)) { const err = new Error(`订单当前为「${orderStatusLabel(row.current_status)}」,已审核及之后不允许编辑`); err.status = 400; throw err; } const body = { ...p }; delete body.id; delete body.order_no; delete body.parent_order_no; delete body.principal_id; delete body.items; const patch = this._pickCreateFields(body); // 明细随表单一并保存:先校验,避免单据头已改、明细报错造成半成功 const items = Array.isArray(p.items) ? p.items : []; if (items.length) { const invalidItems = validateItems(items); if (!invalidItems.ok) { const err = new Error(invalidItems.message); err.status = 400; throw err; } } // 仓库变更:校验归属 + 刷新 warehouse_code 快照 if (body.warehouse_id !== undefined) { const warehouseId = body.warehouse_id === null || body.warehouse_id === '' ? null : Number(body.warehouse_id); patch.warehouse_id = warehouseId; patch.warehouse_code = null; if (warehouseId) { const warehouse = await ctx.model.Warehouse.findOne({ where: { id: warehouseId, principal_id: principalId }, attributes: [ 'id', 'code' ], }); if (!warehouse) { const err = new Error('仓库不存在或不属于当前主体'); err.status = 404; throw err; } patch.warehouse_code = warehouse.code; } } // 店铺变更:校验归属 + 刷新 shop_nick 快照(推送时靠 shopNick 匹配快递策略) if (body.shop_id !== undefined) { const shopId = body.shop_id === null || body.shop_id === '' ? null : Number(body.shop_id); patch.shop_id = shopId; patch.shop_nick = null; if (shopId) { const shop = await ctx.model.Shop.findOne({ where: { id: shopId, principal_id: principalId }, attributes: [ 'id', 'name' ], }); if (!shop) { const err = new Error('店铺不存在或不属于当前主体'); err.status = 404; throw err; } patch.shop_nick = shop.name; } } const current = await this._model(row.current_status).findByPk(row.id); const merged = { ...current.get({ plain: true }), ...patch }; const receiverError = validateReceiver(merged); if (receiverError) { const err = new Error(receiverError); err.status = 400; throw err; } if (patch.address === undefined || patch.address === null) { patch.address = this._composeAddress(merged) || merged.address; } await this._model(row.current_status).update(patch, { where: { id: row.id, principal_id: principalId } }); // 明细覆盖式保存(含统计与商品总金额重算) if (items.length) { await this.saveItems({ order_id: row.id, items }); } return { id: Number(row.id), order_no: row.order_no }; } /** * 删除订单(仅待审核 / 异常 / 已取消;已锁定库存的订单需先释放,避免锁定泄漏) * @param {Object} p { ids } * @return {Promise} { count, order_nos } */ async remove(p = {}) { const { ctx } = this; const principalId = ctx.state.principalId; const idList = this._normalizeIds(p.ids); const indexRows = await this._loadIndexRows(idList, principalId); const invalid = indexRows.filter(row => !DELETABLE_STATUSES.includes(row.current_status)); if (invalid.length) { const err = new Error( `已审核及之后的订单禁止删除(可改为作废 / 取消):${invalid.map(r => r.order_no).join('、')}` ); err.status = 400; throw err; } const transaction = await ctx.model.transaction(); try { const groups = new Map(); for (const row of indexRows) { const detail = await this._model(row.current_status).findByPk(row.id, { transaction }); if (detail && Number(detail.stock_locked) === 1) { await releaseOrderStock(ctx, detail, { createdBy: ctx.userId, remark: '订单删除释放锁定库存', transaction }); } if (!groups.has(row.current_status)) groups.set(row.current_status, []); groups.get(row.current_status).push(Number(row.id)); } const Op = ctx.app.Sequelize.Op; for (const [ status, ids ] of groups) { await this._model(status).destroy({ where: { principal_id: principalId, id: { [Op.in]: ids } }, transaction }); } await ctx.model.OrderStatusItem.destroy({ where: { principal_id: principalId, order_id: { [Op.in]: indexRows.map(r => Number(r.id)) } }, transaction, }); await ctx.model.OrderIndex.destroy({ where: { principal_id: principalId, id: { [Op.in]: indexRows.map(r => Number(r.id)) } }, transaction }); await transaction.commit(); } catch (err) { await transaction.rollback(); throw err; } return { count: indexRows.length, order_nos: indexRows.map(row => row.order_no) }; } /** * 批量切换发货仓库(待审核 / 异常 / 待推送可切换,已推送后不再变更) * @param {Object} p { ids, warehouse_id } * @return {Promise} { updated, target_warehouse } */ async changeWarehouse(p = {}) { return this._changeOwnerField({ ids: p.ids, field: 'warehouse', value: p.warehouse_id, actionLabel: '切换仓库', allowedFrom: [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION, ORDER_STATUS.QUEUED ], }); } /** * 批量设置所属店铺(只影响推送时的快递策略与 OMS 记录,不回写 WMS,委外中也允许修正) * @param {Object} p { ids, shop_id } * @return {Promise} { updated, target_shop } */ async changeShop(p = {}) { return this._changeOwnerField({ ids: p.ids, field: 'shop', value: p.shop_id, actionLabel: '设置所属店铺', allowedFrom: [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION, ORDER_STATUS.QUEUED, ORDER_STATUS.OUTSOURCING ], }); } /** * 批量变更仓库 / 店铺(按状态分组更新,同步刷新编码 / 名称快照) * @param {Object} p 参数 * @param {Array} p.ids 订单 id * @param {String} p.field warehouse 或 shop * @param {Number} p.value 目标仓库 / 店铺 id * @param {String} p.actionLabel 动作名(用于报错文案) * @param {Array} p.allowedFrom 允许的来源状态 * @return {Promise} { updated, target, scope } */ async _changeOwnerField({ ids, field, value, actionLabel, allowedFrom }) { const { ctx } = this; const Op = ctx.app.Sequelize.Op; const principalId = ctx.state.principalId; const targetId = value === null || value === undefined || value === '' ? null : Number(value); if (!targetId) { const err = new Error(`${field}_id 为必填项`); err.status = 400; throw err; } const idList = this._normalizeIds(ids); const indexRows = await this._loadIndexRows(idList, principalId); const invalid = indexRows.filter(row => !allowedFrom.includes(row.current_status)); if (invalid.length) { const fromLabels = allowedFrom.map(orderStatusLabel).join(' / '); const err = new Error( `「${actionLabel}」仅适用于${fromLabels}的订单,当前有 ${invalid.length} 条状态不符(如 ${invalid[0].order_no})` ); err.status = 400; throw err; } let patch; let target; if (field === 'warehouse') { const warehouse = await ctx.model.Warehouse.findOne({ where: { id: targetId, principal_id: principalId }, attributes: [ 'id', 'code', 'name' ], }); if (!warehouse) { const err = new Error('仓库不存在或不属于当前主体'); err.status = 404; throw err; } patch = { warehouse_id: targetId, warehouse_code: warehouse.code }; target = { id: Number(warehouse.id), code: warehouse.code, name: warehouse.name }; } else { const shop = await ctx.model.Shop.findOne({ where: { id: targetId, principal_id: principalId }, attributes: [ 'id', 'name' ], }); if (!shop) { const err = new Error('店铺不存在或不属于当前主体'); err.status = 404; throw err; } patch = { shop_id: targetId, shop_nick: shop.name }; target = { id: Number(shop.id), name: shop.name }; } let updated = 0; for (const status of new Set(indexRows.map(row => row.current_status))) { const groupIds = indexRows.filter(row => row.current_status === status).map(row => Number(row.id)); const [ count ] = await this._model(status).update(patch, { where: { principal_id: principalId, id: { [Op.in]: groupIds } }, }); updated += Number(count) || 0; } return { updated, target, scope: { ids: indexRows.map(row => Number(row.id)) } }; } /** * 归档到历史:指定订单 → 历史表;未指定则归档当前主体下创建时间超期的订单 * @param {Object} p { ids, months } * @return {Promise} 流转结果 */ async archive(p = {}) { const ids = this._normalizeIds(p.ids); if (ids.length) { return this._transition({ ids, allowedFrom: ORDER_ACTIVE_STATUSES, toStatus: ORDER_STATUS.HISTORY, actionLabel: '归档到历史', }); } return this.archiveExpired({ months: p.months, principalId: this.ctx.state.principalId, }); } /** * 归档超期订单(创建时间超过 months 个月):定时任务调用,不传 principalId 时跨主体处理 * @param {Object} p { months, principalId } * @return {Promise} { count, months, threshold, by_status } */ async archiveExpired(p = {}) { const { ctx } = this; const Op = ctx.app.Sequelize.Op; const months = Number(p.months) > 0 ? Number(p.months) : ORDER_ARCHIVE_MONTHS; const threshold = new Date(Date.now() - months * 30 * 24 * 3600 * 1000); const principalId = p.principalId || null; const byStatus = {}; let count = 0; for (const fromStatus of ORDER_ACTIVE_STATUSES) { const where = { status: fromStatus, created_at: { [Op.lt]: threshold } }; if (principalId) where.principal_id = principalId; const rows = await this._model(fromStatus).findAll({ where, attributes: [ 'id', 'principal_id' ], limit: ARCHIVE_BATCH_LIMIT, }); if (!rows.length) continue; // 跨主体归档时按主体分组(索引表与状态表都以 principal_id 隔离) const groups = new Map(); for (const row of rows) { const pid = Number(row.principal_id); if (!groups.has(pid)) groups.set(pid, []); groups.get(pid).push(Number(row.id)); } const transaction = await ctx.model.transaction(); try { for (const [ groupPrincipalId, groupIds ] of groups) { await this._moveRows({ fromStatus, toStatus: ORDER_STATUS.HISTORY, ids: groupIds, principalId: groupPrincipalId, transaction, }); } await transaction.commit(); } catch (err) { await transaction.rollback(); throw err; } byStatus[fromStatus] = rows.length; count += rows.length; } return { count, months, threshold, by_status: byStatus }; } /** * 筛选条件数据源:状态下拉 + 店铺/仓库下拉 + 归档阈值 * @return {Promise} 筛选数据源 */ async filters() { const { ctx } = this; const shops = await ctx.model.Shop.findAll({ where: { principal_id: ctx.state.principalId }, attributes: [ 'id', 'name' ], order: [[ 'id', 'ASC' ]], limit: 500, }); const warehouses = await ctx.model.Warehouse.findAll({ where: { principal_id: ctx.state.principalId }, attributes: [ 'id', 'code', 'name' ], order: [[ 'id', 'ASC' ]], limit: 500, }); return { statuses: ORDER_STATUS_LIST, status_labels: ORDER_STATUS_LABELS, active_statuses: ORDER_ACTIVE_STATUSES, archive_months: ORDER_ARCHIVE_MONTHS, index_table: ORDER_INDEX_TABLE, item_table: ORDER_ITEM_TABLE, shops: shops.map(shop => ({ id: Number(shop.id), name: shop.name })), warehouses: warehouses.map(warehouse => ({ id: Number(warehouse.id), code: warehouse.code, name: warehouse.name, })), }; } } module.exports = OrderStatusService;