- 订单筛选项新增 platforms:系统预设 ∪ 当前主体订单里实际出现过的编码(带数量, 未收录进预设的标记 preset=false),下拉按用量排序,店管家新增平台类型时不会「筛不到」 - 手工单默认 source_platform_code=TB(淘宝),新建/编辑弹窗新增「电商平台」下拉; 编辑改平台时按系统预设同步名称;外部打单平台拉取的订单该字段置灰不可改 - 数据库店铺拉单按店铺配置的平台落库(未配置时默认淘宝),待审核订单可见可筛 - 迁移 20261107010000:把「数据库店铺订单(extend_props.source=shop_database)」与 「手工单(extend_props.labels 含手工单)」里为空的电商平台回填为 TB/淘宝 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2201 lines
90 KiB
JavaScript
2201 lines
90 KiB
JavaScript
'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,
|
||
ORDER_TABLE_BY_STATUS,
|
||
normalizeOrderStatus,
|
||
orderStatusLabel,
|
||
orderModelName,
|
||
orderTableOf,
|
||
orderCopyFields,
|
||
} = require('../lib/orderStatus');
|
||
const { resolveAccountName } = require('../lib/accountProfile');
|
||
const { PLATFORM_PRESETS, platformNameOf, resolvePlatform } = require('../lib/platformCode');
|
||
const { validateReceiver } = require('../lib/orderReceiver');
|
||
const { validateItems } = require('../lib/orderDeliveryItems');
|
||
|
||
/** 外部发货同步状态文案(与 service/externalSendSync.js 的 SEND_STATUS 对齐) */
|
||
const EXTERNAL_SEND_STATUS_LABELS = {
|
||
0: '待同步外部',
|
||
1: '已同步外部',
|
||
2: '同步失败待重试',
|
||
3: '同步异常',
|
||
};
|
||
const { notNullDefaultColumnNames } = require('../lib/orderFields');
|
||
const { lockOrderStock, releaseOrderStock, deductOrderStock } = require('../utils/orderStock');
|
||
|
||
/** 归档任务单轮单表最多迁移的条数(避免一次事务搬运过多数据) */
|
||
const ARCHIVE_BATCH_LIMIT = 200;
|
||
|
||
/** 手工创建订单在扩展字段(extend_props)中写入的标记(与老发货单一致) */
|
||
const HANDMADE_ORDER_LABEL = '手工单';
|
||
|
||
/** 手工单默认电商平台(订单页按平台筛选/展示;可用 source_platform_code 覆盖) */
|
||
const HANDMADE_DEFAULT_PLATFORM = 'TB';
|
||
|
||
/** 店铺类型:2 外部打单平台商家(其订单只能由平台拉取,手工建单不可选) */
|
||
const SHOP_TYPE_EXTERNAL = 2;
|
||
|
||
/** 可编辑单据头/明细的状态(仅未审核的订单允许改) */
|
||
const EDITABLE_STATUSES = [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION ];
|
||
|
||
/**
|
||
* 可删除的状态:仅「已取消」允许删除
|
||
*
|
||
* 待审核 / 异常 / 待推送等视图需先取消再删除,避免绕过状态机把在途单据直接抹掉;
|
||
* 已作废要保留痕迹,同样不可删。
|
||
*/
|
||
const DELETABLE_STATUSES = [ 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;
|
||
}
|
||
|
||
/**
|
||
* 多值筛选参数归一化(数组或逗号分隔字符串 → 去重后的字符串数组)
|
||
* @param {*} value 原始参数
|
||
* @param {number} max 最多保留的取值个数
|
||
* @return {Array<String>} 归一化结果
|
||
*/
|
||
function parseFilterValues(value, max = 200) {
|
||
const raw = Array.isArray(value) ? value : String(value == null ? '' : value).split(/[,,;;\n]/);
|
||
const list = [];
|
||
for (const item of raw) {
|
||
const text = String(item == null ? '' : item).trim();
|
||
if (text && !list.includes(text)) list.push(text);
|
||
if (list.length >= max) break;
|
||
}
|
||
return list;
|
||
}
|
||
|
||
/**
|
||
* 订单状态流转服务
|
||
*
|
||
* 数据模型: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)) ];
|
||
}
|
||
|
||
/**
|
||
* 当前账号在该主体下的权限范围(集团 / 所在公司)
|
||
* @param {Number} principalId 主体ID
|
||
* @return {Promise<{isGroup: boolean, ownIds: Array<number>}>} 范围信息
|
||
*/
|
||
async _scopeAccess(principalId) {
|
||
const { ctx } = this;
|
||
// 内部任务 / 平台回调 / 定时任务没有登录态(ctx.userId 为空):按系统操作处理,不做货主范围限制
|
||
if (!ctx.userId) return { isGroup: true, ownIds: [] };
|
||
const access = await ctx.service.access.resolve(ctx.userId, principalId);
|
||
return { isGroup: !!access.isGroup, ownIds: (access.ownCompanyIds || []).map(Number) };
|
||
}
|
||
|
||
/**
|
||
* 判断订单货主是否在当前账号可见范围内
|
||
* @param {Object} access 权限范围
|
||
* @param {Number|null} subsidiaryId 订单货主ID
|
||
* @return {Boolean} 是否可见/可操作
|
||
*/
|
||
_isOwnAccess(access, subsidiaryId) {
|
||
if (access.isGroup) return true;
|
||
if (subsidiaryId === null || subsidiaryId === undefined) return false;
|
||
return access.ownIds.includes(Number(subsidiaryId));
|
||
}
|
||
|
||
/**
|
||
* 按 id 取索引表记录(主体隔离),并校验全部命中
|
||
* @param {Array} ids 订单 id
|
||
* @param {Number} principalId 主体ID
|
||
* @return {Promise<Array>} 索引记录
|
||
*/
|
||
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 access = await this._scopeAccess(principalId);
|
||
if (!access.isGroup) {
|
||
const denied = rows.find(row => !this._isOwnAccess(access, row.subsidiary_id));
|
||
if (denied) {
|
||
const err = new Error(`订单 ${denied.order_no} 不属于自己所属公司(货主),无权操作`);
|
||
err.status = 403;
|
||
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<Number>} 搬运条数
|
||
*/
|
||
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<Object>} { 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);
|
||
|
||
// 电商平台(系统预设编码,可多选)与平台单号(多个精确匹配,类似店铺商品的商家编码批量查询)
|
||
const platformCodes = parseFilterValues(p.platform_codes, 50).map(code => code.toUpperCase());
|
||
if (platformCodes.length) where.source_platform_code = { [Op.in]: platformCodes };
|
||
const platformOrderNos = parseFilterValues(p.platform_order_nos, 200).map(no => no.slice(0, 50));
|
||
if (platformOrderNos.length) where.oaid_order_source_code = { [Op.in]: platformOrderNos };
|
||
|
||
// 所在公司权限:仅列出自己所属公司(货主)的订单
|
||
const access = await this._scopeAccess(principalId);
|
||
if (!access.isGroup) {
|
||
where.subsidiary_id = { [Op.in]: access.ownIds };
|
||
}
|
||
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;
|
||
}
|
||
}
|
||
|
||
// 外部发货同步状态筛选(配送视图用:0待同步 1已同步 2待重试 3异常;支持多选逗号分隔)
|
||
const externalSendStatus = trimOrNull(p.external_send_status);
|
||
if (externalSendStatus) {
|
||
const values = String(externalSendStatus)
|
||
.split(',')
|
||
.map(item => Number(item.trim()))
|
||
.filter(item => Number.isFinite(item));
|
||
if (values.length) where.external_send_status = { [Op.in]: values };
|
||
}
|
||
|
||
// 只列索引表里存在的订单:详情按 order_index 校验主体,
|
||
// 若状态表存在没有索引记录的历史脏数据,列表会看得到却点不开,这里直接挡掉
|
||
where[Op.and] = [
|
||
ctx.app.Sequelize.literal(
|
||
'EXISTS (SELECT 1 FROM order_index oi WHERE oi.id = `' + Model.tableName + '`.id ' +
|
||
`AND oi.principal_id = ${principalId})`
|
||
),
|
||
];
|
||
|
||
// exclude_unbound=1:排除「有未绑定系统商品的明细」的订单(订单页默认只看已解析订单)
|
||
// 用 EXISTS 子查询而非 IN 列表,避免未绑定订单很多时拼接超长参数
|
||
if (String(p.exclude_unbound) === '1') {
|
||
where[Op.and].push(
|
||
ctx.app.Sequelize.literal(
|
||
'NOT EXISTS (SELECT 1 FROM order_status_items oi WHERE oi.order_id = `' + Model.tableName + '`.id ' +
|
||
`AND oi.principal_id = ${principalId} AND oi.parse_status = 2)`
|
||
)
|
||
);
|
||
}
|
||
|
||
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<void>} 无
|
||
*/
|
||
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;
|
||
// 平台拉取的订单店铺由平台决定,前端据此禁用「设置店铺」
|
||
row.is_external = this._isExternalPrintOrder(row);
|
||
row.external_send_status_label = EXTERNAL_SEND_STATUS_LABELS[Number(row.external_send_status || 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;
|
||
}
|
||
|
||
// 货主名称(订单货主跟随店铺,列表按 id 批量补名称)
|
||
const subsidiaryIds = [
|
||
...new Set(list.map(row => Number(row.subsidiary_id)).filter(id => Number.isInteger(id) && id > 0)),
|
||
];
|
||
if (subsidiaryIds.length) {
|
||
const subsidiaries = await ctx.model.PrincipalSubsidiary.findAll({
|
||
where: { id: { [Op.in]: subsidiaryIds }, principal_id: principalId },
|
||
attributes: [ 'id', 'name' ],
|
||
});
|
||
const nameById = new Map(subsidiaries.map(item => [ Number(item.id), item.name ]));
|
||
for (const row of list) row.subsidiary_name = nameById.get(Number(row.subsidiary_id)) || '';
|
||
} else {
|
||
for (const row of list) row.subsidiary_name = '';
|
||
}
|
||
|
||
// 仓库名称(状态表只存 warehouse_id + warehouse_code 快照,列表按 id 批量补名称,列表展示名称而非编码)
|
||
const warehouseIds = [
|
||
...new Set(list.map(row => Number(row.warehouse_id)).filter(id => Number.isInteger(id) && id > 0)),
|
||
];
|
||
if (warehouseIds.length) {
|
||
const warehouses = await ctx.model.Warehouse.findAll({
|
||
where: { id: { [Op.in]: warehouseIds }, principal_id: principalId },
|
||
attributes: [ 'id', 'code', 'name' ],
|
||
});
|
||
const warehouseById = new Map(warehouses.map(item => [ Number(item.id), item ]));
|
||
for (const row of list) {
|
||
const warehouse = warehouseById.get(Number(row.warehouse_id));
|
||
if (!warehouse) continue;
|
||
row.warehouse_name = warehouse.name;
|
||
row.warehouse_code = row.warehouse_code || warehouse.code;
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 明细行摘要:`商品名称 ×数量`,最多展示 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<Object>} { 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;
|
||
let shopSubsidiaryId = 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', 'type', 'subsidiary_id' ],
|
||
});
|
||
if (!shop) {
|
||
const err = new Error('店铺不存在或不属于当前主体');
|
||
err.status = 404;
|
||
throw err;
|
||
}
|
||
// 外部打单平台店铺的订单只能由平台拉取,手工建单不允许选择
|
||
if (Number(shop.type) === SHOP_TYPE_EXTERNAL) {
|
||
const err = new Error('外部打单平台店铺的订单由平台拉取,手工建单请选择其它店铺');
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
// 订单货主跟随店铺;所在公司权限只能为自己所属公司(货主)的店铺建单
|
||
shopSubsidiaryId = shop.subsidiary_id == null ? null : Number(shop.subsidiary_id);
|
||
const access = await this._scopeAccess(principalId);
|
||
if (!access.isGroup && !this._isOwnAccess(access, shopSubsidiaryId)) {
|
||
const err = new Error('只能为自己所属公司(货主)的店铺创建订单');
|
||
err.status = 403;
|
||
throw err;
|
||
}
|
||
} else {
|
||
const err = new Error('请选择店铺(手工订单必须指定店铺,平台拉取的店铺不可选)');
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
|
||
// 仓库:可空(审核前补齐即可),但填了必须是当前主体的仓库,并快照 warehouse_code
|
||
const fields = this._pickCreateFields(payload);
|
||
// 电商平台:手工单默认「淘宝」,可通过 source_platform_code(编码或中文名)显式指定
|
||
const manualPlatform = resolvePlatform(trimOrNull(payload.source_platform_code) || HANDMADE_DEFAULT_PLATFORM);
|
||
fields.source_platform_code = manualPlatform.code;
|
||
fields.source_platform_name = trimOrNull(payload.source_platform_name) || manualPlatform.name;
|
||
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', 'subsidiary_id' ],
|
||
});
|
||
if (!warehouse) {
|
||
const err = new Error('仓库不存在或不属于当前主体');
|
||
err.status = 404;
|
||
throw err;
|
||
}
|
||
// 仓库必须与店铺同货主,避免通过接口注入其它货主的仓库
|
||
if (shopSubsidiaryId !== null
|
||
&& warehouse.subsidiary_id != null
|
||
&& Number(warehouse.subsidiary_id) !== shopSubsidiaryId) {
|
||
const err = new Error('仓库不属于该店铺的货主,请选择同货主的仓库');
|
||
err.status = 400;
|
||
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;
|
||
}
|
||
// 明细商品/组合必须与店铺同货主,避免通过接口注入其它货主的商品
|
||
await this._assertItemsOwner(items, shopSubsidiaryId, principalId);
|
||
} 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,
|
||
subsidiary_id: shopSubsidiaryId,
|
||
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,
|
||
subsidiary_id: shopSubsidiaryId,
|
||
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;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 校验订单明细的商品/组合与订单货主一致(防止接口注入其它货主的商品)
|
||
* @param {Array} items 明细 [{ item_id / product_id / combo_product_id, ... }]
|
||
* @param {Number|null} subsidiaryId 订单货主ID
|
||
* @param {Number} principalId 主体ID
|
||
* @return {Promise<void>} 不通过时抛出 400
|
||
*/
|
||
async _assertItemsOwner(items, subsidiaryId, principalId) {
|
||
const { ctx } = this;
|
||
const Op = ctx.app.Sequelize.Op;
|
||
// 明细既有新建订单的 item_id,也有历史排单口径的 product_id,两者都按商品校验
|
||
const pickProductId = it => Number(it && (it.item_id != null && it.item_id !== '' ? it.item_id : it.product_id));
|
||
const productIds = [ ...new Set(items.map(pickProductId).filter(id => Number.isInteger(id) && id > 0)) ];
|
||
const comboIds = [ ...new Set(items.map(it => Number(it && it.combo_product_id)).filter(id => Number.isInteger(id) && id > 0)) ];
|
||
if (!productIds.length && !comboIds.length) return;
|
||
|
||
const [ products, combos ] = await Promise.all([
|
||
productIds.length
|
||
? ctx.model.Product.findAll({
|
||
where: { id: { [Op.in]: productIds }, principal_id: principalId },
|
||
attributes: [ 'id', 'subsidiary_id' ],
|
||
raw: true,
|
||
})
|
||
: [],
|
||
comboIds.length
|
||
? ctx.model.ComboProduct.findAll({
|
||
where: { id: { [Op.in]: comboIds }, principal_id: principalId },
|
||
attributes: [ 'id', 'subsidiary_id' ],
|
||
raw: true,
|
||
})
|
||
: [],
|
||
]);
|
||
|
||
if (products.length !== productIds.length || combos.length !== comboIds.length) {
|
||
const err = new Error('明细中存在无效商品(不存在或不属于当前主体)');
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
if (subsidiaryId === null || subsidiaryId === undefined) return;
|
||
const mismatch = [ ...products, ...combos ].find(
|
||
row => row.subsidiary_id != null && Number(row.subsidiary_id) !== Number(subsidiaryId)
|
||
);
|
||
if (mismatch) {
|
||
const err = new Error('明细商品不属于该订单的货主,请选择同货主的商品');
|
||
err.status = 400;
|
||
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<void>} 无
|
||
*/
|
||
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<Array>} 写入的明细
|
||
*/
|
||
async _replaceItems(orderId, principalId, items, transaction) {
|
||
const { ctx } = this;
|
||
// 平台订单(外部打单平台拉取)的明细带平台溯源信息(快照 / 店铺商品 / 平台商品 ID),
|
||
// 手工覆盖时前端不会回传这些字段,按行号沿用,否则再次绑定/解绑就还原不回平台原样数据
|
||
const existings = await ctx.model.OrderStatusItem.findAll({
|
||
where: { order_id: orderId, principal_id: principalId },
|
||
attributes: [
|
||
'order_line_no', 'platform_snapshot', 'shop_product_id', 'outer_item_id', 'outer_sku_id',
|
||
'product_id', 'combo_product_id', 'item_type', 'parse_status', 'parse_msg',
|
||
],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
const existingByLine = new Map(existings.map(row => [ String(row.order_line_no), row ]));
|
||
|
||
await ctx.model.OrderStatusItem.destroy({ where: { order_id: orderId, principal_id: principalId }, transaction });
|
||
const rows = items.map((item, idx) => {
|
||
const row = this._buildItemRow(item, { principalId, orderId, lineIndex: idx });
|
||
const source = existingByLine.get(String(row.order_line_no));
|
||
if (!source) return row;
|
||
if (!row.platform_snapshot && source.platform_snapshot) row.platform_snapshot = source.platform_snapshot;
|
||
for (const field of [ 'shop_product_id', 'outer_item_id', 'outer_sku_id', 'product_id', 'combo_product_id', 'parse_msg' ]) {
|
||
if (row[field] == null && source[field] != null) row[field] = source[field];
|
||
}
|
||
if (!Number(row.item_type)) row.item_type = Number(source.item_type) || 0;
|
||
if (!Number(row.parse_status)) row.parse_status = Number(source.parse_status) || 0;
|
||
return row;
|
||
});
|
||
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,
|
||
platform_snapshot: body.platform_snapshot && typeof body.platform_snapshot === 'object' ? body.platform_snapshot : null,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 批量审核:待审核 / 异常 → 待推送
|
||
*
|
||
* 与老发货单口径一致:
|
||
* - 必须已录入明细、且已选择店铺(推送时 shopNick 取店铺名称匹配快递策略)
|
||
* - **审核即锁定库存**(按明细 plan_qty 占用可用,不足则失败),锁定与状态流转同事务
|
||
* - 写入审核人(主体账号名称,推送为 operatorName)与审核时间,并清空上一轮推送痕迹
|
||
* - 多选时逐单独立事务:库存不足等失败只跳过该单,失败明细见 failures
|
||
* @param {Object} p { ids }
|
||
* @return {Promise<Object>} { 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<Object>} { 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);
|
||
await this._guardPlatformFinished(row, detail, principalId);
|
||
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;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 审核前守卫:外部打单订单若平台侧已发货/已终结,自动作废并拒绝审核
|
||
*
|
||
* 背景:订单可能在店管家先发货、OMS 隔天才审核;若照常审核会推送一张平台已完成、
|
||
* 仓库无法再取号的脏单。平台查询失败按放行处理(只告警),避免平台抖动卡住审核。
|
||
* @param {Object} row 订单索引行
|
||
* @param {Object} detail 订单明细(状态表行)
|
||
* @param {number} principalId 主体ID
|
||
* @return {Promise<void>} 无返回值(命中时抛 400)
|
||
*/
|
||
async _guardPlatformFinished(row, detail, principalId) {
|
||
const { ctx } = this;
|
||
if (String(process.env.DGJ_AUDIT_PLATFORM_CHECK || '1') === '0') return;
|
||
let check;
|
||
try {
|
||
check = await ctx.service.externalPrintOrder.checkPlatformFinished(detail, row, principalId);
|
||
} catch (err) {
|
||
ctx.logger.warn('[order-audit] %s 平台状态校验失败(放行审核):%s', row.order_no, err.message);
|
||
return;
|
||
}
|
||
if (!check || !check.finished) return;
|
||
|
||
const reason = `${check.reason},系统自动作废`;
|
||
try {
|
||
await this.voidOrder({ ids: [ Number(row.id) ], void_reason: reason, principalId });
|
||
} catch (err) {
|
||
ctx.logger.warn('[order-audit] %s 自动作废失败:%s', row.order_no, err.message);
|
||
}
|
||
|
||
const ex = new Error(`订单 ${row.order_no} ${check.reason},不能审核(已自动作废)`);
|
||
ex.status = 400;
|
||
throw ex;
|
||
}
|
||
|
||
/**
|
||
* 手工标记推送结果(待推送 → 委外中 / 异常):无外部仓库时的流转入口,也可用于修正外部实际结果
|
||
* @param {Object} p { ids, outcome: 'success'|'failed', remark }
|
||
* @return {Promise<Object>} 流转结果
|
||
*/
|
||
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<Object>} 流转结果
|
||
*/
|
||
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<Object>} 流转结果
|
||
*/
|
||
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<Object>} 流转结果
|
||
*/
|
||
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<Object>} { 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<Object>} 流转结果
|
||
*/
|
||
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, principalId }
|
||
* @return {Promise<Object>} 流转结果
|
||
*/
|
||
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('订单作废释放锁定库存'),
|
||
// 无登录态的内部任务(如平台已发货自动作废)需显式传主体
|
||
principalId: p.principalId,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 恢复:已取消 / 已作废 → 待审核
|
||
*
|
||
* 与老发货单一致:**曾推送过的单据恢复时换号**(WMS 侧单号唯一,取消/作废后原号仍被占用),
|
||
* 并清空审核 / 推送痕迹与作废原因(重回待审核,重试计数归零)
|
||
* @param {Object} p { ids, principalId }
|
||
* @return {Promise<Object>} { 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,
|
||
// 无登录态的内部任务(如店铺重新启用后批量恢复)需显式传主体
|
||
principalId: p.principalId,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 单据级流转(逐单独立事务,支持换号 / 清痕迹)
|
||
* @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] 是否清空作废痕迹
|
||
* @param {Number} [p.principalId] 主体ID(无登录态的内部任务显式传入)
|
||
* @return {Promise<Object>} { count, status, status_label, items }
|
||
*/
|
||
async _singleFlow(p) {
|
||
const { ctx } = this;
|
||
const principalId = p.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<Object>} 流转结果
|
||
*/
|
||
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<Object>} { 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);
|
||
// 平台拉取的订单不允许改店铺(前端据此禁用店铺下拉)
|
||
plain.is_external = this._isExternalPrintOrder(plain);
|
||
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.subsidiary_id) {
|
||
const subsidiary = await ctx.model.PrincipalSubsidiary.findByPk(plain.subsidiary_id, { attributes: [ 'id', 'name' ] });
|
||
plain.subsidiary_name = subsidiary ? subsidiary.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;
|
||
}
|
||
// 越界保护:明细需按订单的货主范围校验
|
||
await this._loadIndexRows([ orderId ], principalId);
|
||
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;
|
||
}
|
||
// 明细商品必须与订单货主一致
|
||
await this._assertItemsOwner(items, row.subsidiary_id, principalId);
|
||
|
||
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<Object>} { 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;
|
||
// 货主由店铺推导,不接受接口直接写入(防止绕过店铺改归属)
|
||
delete body.subsidiary_id;
|
||
const patch = this._pickCreateFields(body);
|
||
|
||
// 电商平台变更:名称按系统预设同步(前端只提交编码),避免编码与名称不一致
|
||
if (body.source_platform_code !== undefined) {
|
||
const platform = resolvePlatform(trimOrNull(body.source_platform_code) || HANDMADE_DEFAULT_PLATFORM);
|
||
patch.source_platform_code = platform.code;
|
||
patch.source_platform_name = trimOrNull(body.source_platform_name) || platform.name;
|
||
}
|
||
|
||
// 店铺变更:校验归属 + 刷新 shop_nick 快照(推送时靠 shopNick 匹配快递策略)
|
||
// 先于仓库 / 明细校验处理,换店铺后订单货主跟随新店铺,后续校验用生效货主
|
||
let effectiveSubsidiaryId = row.subsidiary_id == null ? null : Number(row.subsidiary_id);
|
||
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', 'subsidiary_id' ],
|
||
});
|
||
if (!shop) {
|
||
const err = new Error('店铺不存在或不属于当前主体');
|
||
err.status = 404;
|
||
throw err;
|
||
}
|
||
const nextSubsidiaryId = shop.subsidiary_id == null ? null : Number(shop.subsidiary_id);
|
||
// 换店铺时订单货主跟随新店铺;所在公司权限只能换到自己所属公司的店铺
|
||
if (nextSubsidiaryId !== effectiveSubsidiaryId) {
|
||
const access = await this._scopeAccess(principalId);
|
||
if (!access.isGroup && !this._isOwnAccess(access, nextSubsidiaryId)) {
|
||
const err = new Error('只能选择自己所属公司(货主)的店铺');
|
||
err.status = 403;
|
||
throw err;
|
||
}
|
||
patch.subsidiary_id = nextSubsidiaryId;
|
||
effectiveSubsidiaryId = nextSubsidiaryId;
|
||
}
|
||
patch.shop_nick = shop.name;
|
||
}
|
||
}
|
||
|
||
// 仓库变更:校验归属 + 刷新 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', 'subsidiary_id' ],
|
||
});
|
||
if (!warehouse) {
|
||
const err = new Error('仓库不存在或不属于当前主体');
|
||
err.status = 404;
|
||
throw err;
|
||
}
|
||
// 仓库必须与订单货主一致,避免通过接口注入其它货主的仓库
|
||
if (effectiveSubsidiaryId !== null && warehouse.subsidiary_id != null
|
||
&& Number(warehouse.subsidiary_id) !== effectiveSubsidiaryId) {
|
||
const err = new Error('仓库不属于该订单的货主,请选择同货主的仓库');
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
patch.warehouse_code = warehouse.code;
|
||
}
|
||
}
|
||
|
||
// 明细随表单一并保存:先校验,避免单据头已改、明细报错造成半成功
|
||
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;
|
||
}
|
||
// 明细商品必须与生效货主一致(换店铺后按新货主校验)
|
||
await this._assertItemsOwner(items, effectiveSubsidiaryId, principalId);
|
||
}
|
||
|
||
// 店铺由平台决定:平台拉取的订单不允许通过编辑改店铺
|
||
const current = await this._model(row.current_status).findByPk(row.id);
|
||
if (body.shop_id !== undefined && this._isExternalPrintOrder(current)) {
|
||
const nextShopId = body.shop_id === null || body.shop_id === '' ? null : Number(body.shop_id);
|
||
if (nextShopId !== Number(current.shop_id)) {
|
||
const err = new Error('该订单由外部打单平台拉取,店铺不可修改');
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
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 } });
|
||
|
||
// 货主变更要同步索引表(越权校验与列表都依赖 order_index.subsidiary_id)
|
||
if (patch.subsidiary_id !== undefined) {
|
||
await ctx.model.OrderIndex.update(
|
||
{ subsidiary_id: patch.subsidiary_id },
|
||
{ 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<Object>} { 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<Object>} { updated, target_warehouse }
|
||
*/
|
||
async changeWarehouse(p = {}) {
|
||
return this._changeOwnerField({
|
||
ids: p.ids,
|
||
value: p.warehouse_id,
|
||
actionLabel: '切换仓库',
|
||
allowedFrom: [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION, ORDER_STATUS.QUEUED ],
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 批量修改待审核订单快递(系统快递或自定义快递,同步刷新物流编码与名称快照)
|
||
* @param {Object} p { ids, logistics_code }
|
||
* @return {Promise<Object>} { updated, target }
|
||
*/
|
||
async changeLogistics(p = {}) {
|
||
const { ctx } = this;
|
||
const Op = ctx.app.Sequelize.Op;
|
||
const principalId = ctx.state.principalId;
|
||
const idList = this._normalizeIds(p.ids);
|
||
const code = String(p.logistics_code == null ? '' : p.logistics_code).trim();
|
||
if (!code) {
|
||
const err = new Error('logistics_code 为必填项');
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
|
||
const indexRows = await this._loadIndexRows(idList, principalId);
|
||
const invalid = indexRows.filter(row => row.current_status !== ORDER_STATUS.PENDING);
|
||
if (invalid.length) {
|
||
const err = new Error(
|
||
`「修改快递」仅适用于待审核的订单,当前有 ${invalid.length} 条状态不符(如 ${invalid[0].order_no})`
|
||
);
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
|
||
// 优先命中自定义快递编码(订单保存自定义 code/name,推送奇门时原样下发),
|
||
// 未命中再按系统快递公司字典解析
|
||
let target = await ctx.model.CustomExpressCode.findOne({
|
||
where: { code, status: 1 },
|
||
attributes: [ 'code', 'name' ],
|
||
});
|
||
if (!target) {
|
||
const company = await ctx.model.ExpressCompany.findOne({
|
||
where: { code, status: 1 },
|
||
attributes: [ 'code', 'name' ],
|
||
});
|
||
if (company) target = { code: company.code, name: company.name };
|
||
}
|
||
if (!target) {
|
||
const err = new Error('快递编码不存在或未启用(系统快递 / 自定义快递)');
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
|
||
const ids = indexRows.map(row => Number(row.id));
|
||
const transaction = await ctx.model.transaction();
|
||
let updated = 0;
|
||
try {
|
||
const [ count ] = await this._model(ORDER_STATUS.PENDING).update(
|
||
{ logistics_code: target.code, logistics_name: target.name },
|
||
{ where: { principal_id: principalId, id: { [Op.in]: ids } }, transaction }
|
||
);
|
||
updated = Number(count) || 0;
|
||
if (updated !== ids.length) {
|
||
const err = new Error('待审核订单更新数量与所选数量不一致,请刷新后重试');
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
await transaction.commit();
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
throw err;
|
||
}
|
||
|
||
return { updated, target: { code: target.code, name: target.name } };
|
||
}
|
||
|
||
/**
|
||
* 判断订单是否由外部打单平台拉取(其店铺由平台决定,不允许人工改店铺)
|
||
* @param {Object} row 状态表记录(含 extend_props)
|
||
* @return {boolean} 是否平台拉取订单
|
||
*/
|
||
_isExternalPrintOrder(row) {
|
||
const props = row && row.extend_props;
|
||
return !!(props && typeof props === 'object' && props.source === 'external_print');
|
||
}
|
||
|
||
/**
|
||
* 批量切换发货仓库(按状态分组更新,同步刷新仓库编码快照)
|
||
* @param {Object} p 参数
|
||
* @param {Array} p.ids 订单 id
|
||
* @param {Number} p.value 目标仓库 id
|
||
* @param {String} p.actionLabel 动作名(用于报错文案)
|
||
* @param {Array} p.allowedFrom 允许的来源状态
|
||
* @return {Promise<Object>} { updated, target, scope }
|
||
*/
|
||
async _changeOwnerField({ ids, 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('warehouse_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;
|
||
}
|
||
|
||
const targets = indexRows;
|
||
const warehouse = await ctx.model.Warehouse.findOne({
|
||
where: { id: targetId, principal_id: principalId },
|
||
attributes: [ 'id', 'code', 'name', 'subsidiary_id' ],
|
||
});
|
||
if (!warehouse) {
|
||
const err = new Error('仓库不存在或不属于当前主体');
|
||
err.status = 404;
|
||
throw err;
|
||
}
|
||
// 仓库必须与订单货主一致,避免通过接口注入其它货主的仓库
|
||
const mismatch = indexRows.find(row => row.subsidiary_id != null
|
||
&& warehouse.subsidiary_id != null
|
||
&& Number(warehouse.subsidiary_id) !== Number(row.subsidiary_id));
|
||
if (mismatch) {
|
||
const err = new Error(`仓库不属于订单 ${mismatch.order_no} 的货主,请选择同货主的仓库`);
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
const patch = { warehouse_id: targetId, warehouse_code: warehouse.code };
|
||
const target = { id: Number(warehouse.id), code: warehouse.code, name: warehouse.name };
|
||
|
||
let updated = 0;
|
||
for (const status of new Set(targets.map(row => row.current_status))) {
|
||
const groupIds = targets.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: targets.map(row => Number(row.id)) } };
|
||
}
|
||
|
||
/**
|
||
* 按当前明细重算订单头的商品摘要(product_info)与明细统计(item_total / item_kind / item_amount)
|
||
*
|
||
* 明细被重新解析(绑定/解绑、组合商品拆分为最小单位)后调用,保证列表展示与明细口径一致。
|
||
* @param {number} orderId 订单ID
|
||
* @param {number} [principalId] 主体ID(默认取上下文;定时任务里需显式传入)
|
||
* @param {Object} [transaction] 事务
|
||
* @return {Promise<void>} 无返回值
|
||
*/
|
||
async refreshItemSummary(orderId, principalId, transaction) {
|
||
const { ctx } = this;
|
||
const pid = Number(principalId || ctx.state.principalId);
|
||
if (!Number.isInteger(pid) || pid <= 0) return;
|
||
|
||
const [ index ] = await ctx.model.OrderIndex.findAll({
|
||
where: { id: orderId, principal_id: pid },
|
||
attributes: [ 'current_status' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
if (!index) return;
|
||
|
||
const items = await ctx.model.OrderStatusItem.findAll({
|
||
where: { order_id: orderId, principal_id: pid },
|
||
attributes: [ 'item_code', 'item_name', 'plan_qty', 'actual_price', 'order_line_no', 'id' ],
|
||
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
let itemTotal = 0;
|
||
let itemAmount = 0;
|
||
const productInfo = items.map(line => {
|
||
const qty = Number(line.plan_qty) || 0;
|
||
const price = line.actual_price == null ? 0 : Number(line.actual_price);
|
||
itemTotal += qty;
|
||
itemAmount += qty * price;
|
||
return {
|
||
item_code: line.item_code,
|
||
item_name: line.item_name,
|
||
quantity: qty,
|
||
price: line.actual_price == null ? null : price,
|
||
};
|
||
});
|
||
|
||
await this._model(index.current_status).update(
|
||
{
|
||
product_info: productInfo.length ? productInfo : null,
|
||
item_total: Number(itemTotal.toFixed(3)),
|
||
item_kind: items.length,
|
||
item_amount: Number(itemAmount.toFixed(2)),
|
||
},
|
||
{ where: { id: orderId, principal_id: pid }, transaction }
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 归档到历史:指定订单 → 历史表;未指定则归档当前主体下创建时间超期的订单
|
||
* @param {Object} p { ids, months }
|
||
* @return {Promise<Object>} 流转结果
|
||
*/
|
||
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<Object>} { 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<Object>} 筛选数据源
|
||
*/
|
||
async filters() {
|
||
const { ctx } = this;
|
||
const principalId = ctx.state.principalId;
|
||
// 所在公司权限:店铺/仓库下拉只给自己所属公司(货主)的数据
|
||
const access = await this._scopeAccess(principalId);
|
||
const ownScope = () => ({ [ctx.app.Sequelize.Op.in]: access.ownIds });
|
||
const shopWhere = { principal_id: principalId };
|
||
if (!access.isGroup) shopWhere.subsidiary_id = ownScope();
|
||
const shops = await ctx.model.Shop.findAll({
|
||
where: shopWhere,
|
||
attributes: [ 'id', 'code', 'name', 'type', 'subsidiary_id' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
limit: 500,
|
||
});
|
||
const warehouseWhere = { principal_id: principalId };
|
||
if (!access.isGroup) warehouseWhere.subsidiary_id = ownScope();
|
||
const warehouses = await ctx.model.Warehouse.findAll({
|
||
where: warehouseWhere,
|
||
attributes: [ 'id', 'code', 'name', 'subsidiary_id' ],
|
||
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,
|
||
platforms: await this._platformOptions(principalId),
|
||
shops: shops.map(shop => ({
|
||
id: Number(shop.id),
|
||
code: shop.code,
|
||
name: shop.name,
|
||
type: Number(shop.type) || 1,
|
||
subsidiary_id: shop.subsidiary_id == null ? null : Number(shop.subsidiary_id),
|
||
})),
|
||
warehouses: warehouses.map(warehouse => ({
|
||
id: Number(warehouse.id),
|
||
code: warehouse.code,
|
||
name: warehouse.name,
|
||
subsidiary_id: warehouse.subsidiary_id == null ? null : Number(warehouse.subsidiary_id),
|
||
})),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 电商平台筛选项:系统预设编码 ∪ 当前主体订单里实际出现过的编码
|
||
*
|
||
* 预设保证「新平台/尚未拉单的平台」也能筛;实际出现的编码保证店管家新增平台类型
|
||
* (未收录进预设、落成其它编码)时不会在筛选里「查不到」。
|
||
* 只统计活动状态表(不含历史表),避免归档数据把每次筛选都扫一遍。
|
||
* @param {Number} principalId 主体ID
|
||
* @return {Promise<Array<{code: string, name: string, count: number, preset: boolean}>>} 平台选项
|
||
*/
|
||
async _platformOptions(principalId) {
|
||
const { ctx } = this;
|
||
const pid = Number(principalId);
|
||
const counts = new Map();
|
||
|
||
const unions = ORDER_ACTIVE_STATUSES
|
||
.map(status => ORDER_TABLE_BY_STATUS[status])
|
||
.filter(Boolean)
|
||
.map(table => `SELECT source_platform_code FROM ${table} WHERE principal_id = ${pid} AND source_platform_code IS NOT NULL`);
|
||
if (unions.length) {
|
||
try {
|
||
const sql = `SELECT source_platform_code AS code, COUNT(*) AS n FROM (${unions.join(' UNION ALL ')}) t GROUP BY 1`;
|
||
const rows = await ctx.model.query(sql, { type: ctx.app.Sequelize.QueryTypes.SELECT });
|
||
for (const row of rows || []) {
|
||
const code = String(row.code || '').trim().toUpperCase();
|
||
if (code) counts.set(code, (counts.get(code) || 0) + (Number(row.n) || 0));
|
||
}
|
||
} catch (err) {
|
||
ctx.logger.warn('[orderStatus] 统计订单平台分布失败:%s', err.message);
|
||
}
|
||
}
|
||
|
||
const presetCodes = new Set(PLATFORM_PRESETS.map(item => item.code));
|
||
const list = PLATFORM_PRESETS.map(item => ({
|
||
code: item.code,
|
||
name: item.name,
|
||
count: counts.get(item.code) || 0,
|
||
preset: true,
|
||
}));
|
||
for (const [ code, count ] of counts) {
|
||
if (presetCodes.has(code)) continue;
|
||
list.push({ code, name: platformNameOf(code), count, preset: false });
|
||
}
|
||
// 用过的平台排前面(同等条件下预设顺序不变)
|
||
return list.sort((a, b) => (b.count - a.count) || (Number(b.preset) - Number(a.preset)));
|
||
}
|
||
}
|
||
|
||
module.exports = OrderStatusService;
|