feat(order.pendingOrder): 新增 allocateSubOrderNumber 子单号异步分配接口与进度查询

This commit is contained in:
liufumingren 2026-07-27 17:46:26 +08:00
parent f9fbf96ce5
commit d11ed3b2a2
3 changed files with 603 additions and 3 deletions

View File

@ -53,6 +53,18 @@ const SYNC_ORDER_IDS_PROGRESS_MAP = Object.freeze({
unknown: 0,
});
const ALLOCATE_SUB_ORDER_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_sub_order:request:';
const ALLOCATE_SUB_ORDER_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2;
const ALLOCATE_SUB_ORDER_PROGRESS_MAP = Object.freeze({
submitted: 5,
running: 50,
success: 100,
partial: 80,
failed: 100,
not_found: 0,
unknown: 0,
});
/**
* 中国行政区划反向查询表。
*
@ -528,9 +540,9 @@ class PendingOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -5917,6 +5929,405 @@ class PendingOrderService extends OrderBaseService {
}
}
// ========== allocateSubOrderNumber 子单号分配 ==========
/**
* 分配子单号(异步任务模式)。
*
* 为指定订单按 business_key(从 2 开始)逐个子单号分配运单号。
* 将所有 business_key 全量传入 createWaybillCodePipeline,
* 由 pipeline 内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引
* 保证并发安全:已分配(status=1)自动跳过,未分配 INSERT status=0 占位后分配。
*
* @param {Object} data 请求体。
* @param {number|string} data.order_id 订单ID(必填)。
* @param {number} data.sub_order_count 子单号数量(必填,>=1)。
* @return {Promise<Object>} 统一 success 包装,立即返回 task_id。
*/
async allocateSubOrderNumber(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
// 1. 参数校验
const orderId = Number(requestData.order_id);
if (!Number.isInteger(orderId) || orderId <= 0) {
throw new Error('order_id 必须为正整数');
}
const subOrderCount = Number(requestData.sub_order_count);
if (!Number.isInteger(subOrderCount) || subOrderCount < 1) {
throw new Error('sub_order_count 必须为正整数且 >= 1');
}
// 2. 查询订单并校验状态(待处理:step in [1,2,3] 且 outbound_status != 'padding')
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere([ orderId ], warehouseId);
const order = await model.findOne({
where,
attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name' ],
raw: true,
});
if (!order) {
throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`);
}
const allowedSteps = new Set([ 1, 2, 3 ]);
if (!allowedSteps.has(order.step)) {
throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理状态(step 1/2/3)的订单分配子单号`);
}
if (order.outbound_status === PENDING_OUTBOUND_STATUS) {
throw new Error(`订单 ${orderId} 已标记待出库,不允许分配子单号`);
}
// 3. 计算 business_key 列表(从 2 开始)
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel) {
throw new Error('OrderExpress 模型未加载');
}
const businessKeys = [];
for (let i = 0; i < subOrderCount; i++) {
businessKeys.push(2 + i);
}
// 4. 预查已有的已分配运单号(status=1),仅用于初始 details 展示与全部跳过优化
const { Op } = this.app.Sequelize;
const existingCompleted = await orderExpressModel.findAll({
where: {
order_id: orderId,
warehouse_id: Number(order.warehouse_id) || warehouseId,
status: 1,
business_key: { [Op.in]: businessKeys },
},
attributes: [ 'business_key', 'waybill_code' ],
raw: true,
});
const completedBusinessKeyMap = new Map();
if (Array.isArray(existingCompleted)) {
for (const row of existingCompleted) {
completedBusinessKeyMap.set(Number(row.business_key), String(row.waybill_code || '').trim());
}
}
// 5. 生成任务ID,立即返回
const taskId = `sub_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
const taskPayload = {
task_id: taskId,
order_id: orderId,
status: 'submitted',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.submitted,
message: '子单号分配任务已提交',
result: {
total_count: businessKeys.length,
skip_count: completedBusinessKeyMap.size,
pending_count: businessKeys.length - completedBusinessKeyMap.size,
business_keys: businessKeys,
skipped_business_keys: businessKeys.filter(bk => completedBusinessKeyMap.has(bk)),
pending_business_keys: businessKeys.filter(bk => !completedBusinessKeyMap.has(bk)),
details: businessKeys.map(bk => ({
business_key: bk,
status: completedBusinessKeyMap.has(bk) ? 'skipped' : 'pending',
waybill_code: completedBusinessKeyMap.get(bk) || null,
})),
},
error: '',
};
await this.setAllocateSubOrderTaskProgress(taskId, taskPayload);
// 6. 如果全部已分配,跳过 pipeline 直接完成
if (completedBusinessKeyMap.size === businessKeys.length) {
await this.setAllocateSubOrderTaskProgress(taskId, {
...taskPayload,
status: 'success',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.success,
message: '子单号分配完成(全部已分配,无待处理项)',
});
return this.success('ok', {
...taskPayload,
status: 'success',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.success,
message: '子单号分配完成(全部已分配,无待处理项)',
update_time: Date.now(),
});
}
// 7. 后台异步执行分配(全量 business_key 传入 pipeline,由其内部事务保证去重与并发安全)
const orderWarehouseId = Number(order.warehouse_id) || warehouseId;
setImmediate(async () => {
try {
await this.setAllocateSubOrderTaskProgress(taskId, {
...taskPayload,
status: 'running',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.running,
message: '子单号分配处理中',
});
// 全量传入(含已分配的),pipeline 内部 createWaybillCode 事务会跳过 status=1 的记录
const ordersForPipeline = businessKeys.map(bk => ({
order_id: orderId,
business_key: bk,
sys_platform_code: order.sys_platform_code,
logistics_code: order.logistics_code,
sys_platform_name: order.sys_platform_name,
logistics_name: order.logistics_name,
store_id: order.store_id,
}));
const pipelineResult = await this.service.systems.express.createWaybillCodePipeline(
ordersForPipeline,
{ awaitTasks: true }
);
// 回查最终分配结果
const updatedDetails = await this.buildSubOrderDetails(orderId, orderWarehouseId, businessKeys);
const successCount = updatedDetails.filter(d => d.status === 'allocated' || d.status === 'skipped').length;
const isPartial = successCount < businessKeys.length;
await this.setAllocateSubOrderTaskProgress(taskId, {
...taskPayload,
status: isPartial ? 'partial' : 'success',
progress: isPartial ? ALLOCATE_SUB_ORDER_PROGRESS_MAP.partial : ALLOCATE_SUB_ORDER_PROGRESS_MAP.success,
message: isPartial
? `子单号分配部分完成(${successCount}/${businessKeys.length})`
: '子单号分配完成',
result: {
...taskPayload.result,
pipeline_result: pipelineResult,
details: updatedDetails,
},
});
} catch (error) {
const errorMessage = error && error.message ? error.message : String(error);
await this.setAllocateSubOrderTaskProgress(taskId, {
...taskPayload,
status: 'failed',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.failed,
message: '子单号分配失败',
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 查询子单号分配任务进度。
*
* 可按 task_id 或 business_key 查询。
* 若传入 business_key,返回该 business_key 对应的分配详情。
*
* @param {Object} data 请求体。
* @param {string} data.task_id 任务ID。
* @param {string} data.taskId 任务ID(驼峰写法)。
* @param {number} [data.business_key] 子单号业务ID(可选,按业务ID过滤)。
* @param {number} [data.businessKey] 子单号业务ID(可选,驼峰写法)。
* @return {Promise<Object>} 统一 success 包装。
*/
async allocateSubOrderNumberProgress(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const taskId = String(requestData.task_id || requestData.taskId || '').trim();
const businessKey = Number(requestData.business_key || requestData.businessKey);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.not_found,
message: '任务不存在',
result: null,
error: '',
update_time: Date.now(),
});
}
const cachedTask = await this.getAllocateSubOrderTaskProgress(taskId);
if (!cachedTask) {
return this.success('ok', {
task_id: taskId,
status: 'not_found',
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.not_found,
message: '任务不存在',
result: null,
error: '',
update_time: Date.now(),
});
}
// 如果传入了 business_key,过滤出该业务ID对应的详情
let filteredResult = cachedTask.result;
if (Number.isInteger(businessKey) && businessKey > 0 && cachedTask.result) {
const details = Array.isArray(cachedTask.result.details) ? cachedTask.result.details : [];
const matchedDetail = details.find(d => Number(d.business_key) === businessKey);
filteredResult = {
...cachedTask.result,
filtered_business_key: businessKey,
matched_detail: matchedDetail || null,
};
}
return this.success('ok', {
...cachedTask,
result: filteredResult,
update_time: cachedTask.update_time || Date.now(),
});
}
// ========== allocateSubOrderNumber 缓存工具方法 ==========
/**
* 获取子单号分配任务缓存键。
*
* @param {string} taskId 任务ID。
* @return {string} 缓存键。
*/
getAllocateSubOrderTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${ALLOCATE_SUB_ORDER_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入子单号分配任务进度。
*
* @param {string} taskId 任务ID。
* @param {Object} payload 任务状态与结果。
* @return {Promise<void>}
*/
async setAllocateSubOrderTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getAllocateSubOrderTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const progressPayload = {
task_id: String(taskId || '').trim(),
order_id: safePayload.order_id || null,
status: String(safePayload.status || 'unknown').trim(),
progress: Number(safePayload.progress || 0),
message: String(safePayload.message || ''),
result: safePayload.result || null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_SUB_ORDER_TASK_CACHE_TTL_SECONDS);
} catch (error) {
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入任务进度缓存失败: %s', error && error.message ? error.message : error);
}
}
/**
* 读取子单号分配任务进度。
*
* @param {string} taskId 任务ID。
* @return {Promise<Object|null>} 任务缓存结果。
*/
async getAllocateSubOrderTaskProgress(taskId = '') {
const cacheKey = this.getAllocateSubOrderTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 读取任务进度缓存失败: %s', error && error.message ? error.message : error);
return null;
}
}
/**
* 回查子单号分配结果详情(pipeline 执行后调用)。
*
* 根据 order_express 表最终状态判断每个 business_key 的结果:
* - status=1 且 waybill_code 非空 → allocated(本次分配成功或之前已分配)
* - status=0 → pipeline 占位但 API 未完成 → failed
* - 无记录 → failed(pipeline 未处理到)
*
* @param {number} orderId 订单ID。
* @param {number} warehouseId 仓库ID。
* @param {number[]} businessKeys 全部 business_key 列表。
* @return {Promise<Array<Object>>} 每个 business_key 的分配详情。
*/
async buildSubOrderDetails(orderId, warehouseId, businessKeys) {
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel) {
return businessKeys.map(bk => ({
business_key: bk,
status: 'unknown',
waybill_code: null,
note: 'OrderExpress 模型未加载',
}));
}
const { Op } = this.app.Sequelize;
const allRecords = await orderExpressModel.findAll({
where: {
order_id: orderId,
warehouse_id: warehouseId,
business_key: { [Op.in]: businessKeys },
},
attributes: [ 'business_key', 'waybill_code', 'status' ],
raw: true,
});
const recordMap = new Map();
if (Array.isArray(allRecords)) {
for (const row of allRecords) {
// 同一 business_key 可能有多条(status 不同),优先取 status=1 的
const existing = recordMap.get(Number(row.business_key));
if (!existing || Number(row.status) === 1) {
recordMap.set(Number(row.business_key), row);
}
}
}
return businessKeys.map(bk => {
const record = recordMap.get(bk);
if (record && Number(record.status) === 1 && String(record.waybill_code || '').trim()) {
return {
business_key: bk,
status: 'allocated',
waybill_code: String(record.waybill_code || '').trim(),
note: '子单号分配成功',
};
}
if (record && Number(record.status) === 0) {
return {
business_key: bk,
status: 'failed',
waybill_code: null,
note: '运单占位已创建但 API 未返回运单号(status=0)',
};
}
return {
business_key: bk,
status: 'failed',
waybill_code: null,
note: '未找到分配的运单记录',
};
});
}
}
module.exports = PendingOrderService;

View File

@ -1,4 +1,25 @@
[
{
"version": "2026.07.27-system-02",
"date": "2026-07-27",
"type": "added",
"summary": "新增 order.pendingOrder.allocateSubOrderNumber:待处理订单分配子单号(异步任务),business_key 从 2 开始递增,跳过已分配运单号;新增 allocateSubOrderNumberProgress 按 task_id/business_key 查询进度",
"methods": [
"order.pendingOrder.allocateSubOrderNumber",
"order.pendingOrder.allocateSubOrderNumberProgress"
],
"notes": [
"新增 allocateSubOrderNumber:入参 order_id + sub_order_count,按 business_key 2..(2+count-1) 全量传入 createWaybillCodePipeline。",
"并发安全:全量传入 pipeline,由其内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引保证并发去重。",
"pipeline 内部 createWaybillCode 事务:status=1 已分配→跳过;status=0 占位中→复用;无记录→INSERT status=0 占位。",
"异步任务模式:请求立即返回 task_id(sub_ 前缀),后台 setImmediate 执行,进度通过 Redis 缓存追踪。",
"新增 allocateSubOrderNumberProgress:支持 task_id 查整体进度,business_key 可选参数过滤单个业务ID的详情。",
"进度状态 submitted→running→success/partial/failed,progress 对应 5/50/80/100。",
"result.details 数组记录每个 business_key 的 status(skipped/allocated/failed/pending)与 waybill_code。",
"buildSubOrderDetails 回查最终状态:status=1+waybill→allocated,status=0→failed,无记录→failed。"
],
"module": "order.pendingOrder"
},
{
"version": "2026.07.27-system-01",
"date": "2026-07-27",

View File

@ -25847,6 +25847,174 @@
}
]
},
{
"method": "order.pendingOrder.allocateSubOrderNumber",
"description": "分配子单号(异步任务模式)。为指定订单按 business_key(从 2 开始)全量传入 createWaybillCodePipeline,由其内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引保证并发安全:已分配(status=1)自动跳过,未分配 INSERT status=0 占位后分配。请求立即返回 task_id(sub_ 前缀),后续通过 allocateSubOrderNumberProgress 按 task_id 或 business_key 查询进度与结果。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "order_id",
"type": "number",
"required": true,
"source": "body",
"description": "订单 ID,必须为正整数"
},
{
"name": "sub_order_count",
"type": "number",
"required": true,
"source": "body",
"description": "子单号数量,>= 1。business_key 从 2 开始递增,如 count=1 则创建 business_key=2,count=3 则创建 2/3/4"
}
],
"response": [
{
"name": "task_id",
"type": "string",
"required": true,
"description": "任务 ID(sub_ 前缀),用于查询进度"
},
{
"name": "order_id",
"type": "number",
"required": true,
"description": "订单 ID"
},
{
"name": "status",
"type": "string",
"required": true,
"description": "任务状态:submitted/running/success/partial/failed"
},
{
"name": "progress",
"type": "number",
"required": true,
"description": "进度百分比:5/50/80/100"
},
{
"name": "message",
"type": "string",
"required": true,
"description": "任务状态说明"
},
{
"name": "result",
"type": "object",
"required": true,
"description": "分配结果摘要,含 total_count/skip_count/pending_count/business_keys/skipped_business_keys/pending_business_keys/details 等字段"
}
],
"errors": [
{
"code": 400,
"message": "order_id 必须为正整数"
},
{
"code": 400,
"message": "sub_order_count 必须为正整数且 >= 1"
},
{
"code": 400,
"message": "订单不存在或不属于当前仓库"
},
{
"code": 400,
"message": "订单当前步骤不在允许范围,仅允许待处理状态(step 1/2/3)的订单分配子单号"
},
{
"code": 400,
"message": "订单已标记待出库,不允许分配子单号"
},
{
"code": 500,
"message": "内部错误:OrderExpress 模型未加载或运单分配链路异常"
}
]
},
{
"method": "order.pendingOrder.allocateSubOrderNumberProgress",
"description": "查询子单号分配任务进度。可按 task_id 查询整体进度,也可传入 business_key 进一步过滤该业务ID对应的分配详情与最终结果。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "task_id",
"type": "string",
"required": true,
"source": "body",
"description": "任务 ID(返回的 task_id),支持 task_id 或 taskId 两种写法"
},
{
"name": "business_key",
"type": "number",
"required": false,
"source": "body",
"description": "子单号业务ID(可选),传入后返回该 business_key 对应的分配详情。支持 business_key 或 businessKey 两种写法"
}
],
"response": [
{
"name": "task_id",
"type": "string",
"required": true,
"description": "任务 ID"
},
{
"name": "order_id",
"type": "number",
"required": true,
"description": "订单 ID"
},
{
"name": "status",
"type": "string",
"required": true,
"description": "任务状态:submitted/running/success/partial/failed/not_found"
},
{
"name": "progress",
"type": "number",
"required": true,
"description": "进度百分比"
},
{
"name": "message",
"type": "string",
"required": true,
"description": "任务状态说明"
},
{
"name": "result",
"type": "object",
"required": true,
"description": "分配结果。若传了 business_key,额外返回 filtered_business_key 与 matched_detail"
}
],
"errors": [
{
"code": 500,
"message": "查询缓存异常"
}
]
},
{
"method": "order.bindExpressPackageMaterialByWaybill",
"description": "按运单号绑定包材。仅需传入运单号与包材ID,系统自动根据运单号反查对应订单运单记录并绑定包材,无需传入订单ID。",