liufumingren b10f8f7583 feat(order): 新增 order.cancelB2b 接口,取消 B2B 出库流转回正常订单
- systems/order_b2b.js cancelOrdersB2b:
  1) 仅限待处理表(current 分表)中 is_b2b=Y 的订单,事务内 SELECT ... FOR UPDATE
     后逐行校验:待处理(step!=0)/是 B2B(is_b2b=Y)/未打印(print_status!=fin)/
     未锁定(lock_status=none)/未拦截(intercept_status=none)/B2B 面单未打印
     (wms_order_b2b.is_print!=Y),不符合条件跳过(skipped_reasons 返回原因),
     不存在订单计入 not_found_order_ids
  2) 事务内:订单 is_b2b 置回 N + B2B 作业明细软删除(deleted_at);提交后写
     操作日志 ORDER_B2B_CANCEL(失败不影响主流程)
  3) 单次上限 200,仓库隔离
- systemMethods/order/index.js cancelB2b:ids/order_ids/orderIds 数组与
  id/order_id/orderId 单值兼容,空/超限 400;白名单三处加 cancelB2b
- 验证:临时集成测试 3/3 PASS(转 B2B→取消链路:is_b2b 置回 N+明细软删除
  +日志、已打印 B2B 面单跳过分流、400 边界,测后数据还原);ESLint 0 error
2026-10-09 00:26:36 +08:00

704 lines
25 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const OrderBaseService = require('./base');
const ORDER_EXPORT_TASK_CACHE_KEY_PREFIX = 'order_export_task_';
const ORDER_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
class OrderIndexService extends OrderBaseService {
/**
* 初始化订单系统方法的免登录、免权限、免日志和免鉴权配置。
* @param {Egg.Context} ctx 上下文对象。
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill,convertToB2b,cancelB2b';
const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill,convertToB2b,cancelB2b';
const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress,bindExpressPackageMaterialByWaybill,convertToB2b,cancelB2b';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 订单转 B2B 订单。
*
* 仅限待处理表中未打印、未锁定、未拦截的订单;不符合条件跳过。
* 事务内:订单表 is_b2b 置 Y + 写入 wms_order_b2b 作业明细,提交后写操作日志。
*
* @param {Object} data 请求体。
* @param {Array<number|string>|number|string} [data.ids] 订单ID集合(优先)。
* @param {Array<number|string>|number|string} [data.order_ids] 订单ID集合别名。
* @param {Array<number|string>|number|string} [data.orderIds] 订单ID集合别名。
* @param {number|string} [data.id] 订单ID单值别名。
* @param {number|string} [data.order_id] 订单ID单值别名。
* @param {number|string} [data.orderId] 订单ID单值别名。
* @return {Promise<Object>} 统一成功包装响应(data 含 converted/skipped/not_found 分流结果)。
*/
async convertToB2b(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const rawIds = requestData.ids !== undefined ? requestData.ids
: requestData.order_ids !== undefined ? requestData.order_ids
: requestData.orderIds !== undefined ? requestData.orderIds
: requestData.id !== undefined ? requestData.id
: requestData.order_id !== undefined ? requestData.order_id
: requestData.orderId;
const orderIds = [ ...new Set(
(Array.isArray(rawIds) ? rawIds : [ rawIds ])
.map(item => Number(item))
.filter(item => Number.isInteger(item) && item > 0)
) ];
if (orderIds.length === 0) {
return this.fail('订单ID不能为空', {}, 400);
}
if (orderIds.length > 200) {
return this.fail('单次最多转换 200 个订单', {}, 400);
}
const warehouseId = this.getWarehouseId();
const operator = this.getOrderLogOperator();
const result = await this.service.systems.orderB2b.convertOrdersToB2b({
warehouseId,
orderIds,
operator,
});
return this.success('ok', result);
}
/**
* 取消 B2B 出库:订单流转回正常订单。
*
* 仅限待处理表中 is_b2b=Y 且未打印、未锁定、未拦截、B2B 面单未打印的订单;
* 不符合条件跳过。事务内:订单表 is_b2b 置回 N + B2B 作业明细软删除,
* 提交后写操作日志。
*
* @param {Object} data 请求体。
* @param {Array<number|string>|number|string} [data.ids] 订单ID集合(优先)。
* @param {Array<number|string>|number|string} [data.order_ids] 订单ID集合别名。
* @param {Array<number|string>|number|string} [data.orderIds] 订单ID集合别名。
* @param {number|string} [data.id] 订单ID单值别名。
* @param {number|string} [data.order_id] 订单ID单值别名。
* @param {number|string} [data.orderId] 订单ID单值别名。
* @return {Promise<Object>} 统一成功包装响应(data 含 canceled/skipped/not_found 分流结果)。
*/
async cancelB2b(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const rawIds = requestData.ids !== undefined ? requestData.ids
: requestData.order_ids !== undefined ? requestData.order_ids
: requestData.orderIds !== undefined ? requestData.orderIds
: requestData.id !== undefined ? requestData.id
: requestData.order_id !== undefined ? requestData.order_id
: requestData.orderId;
const orderIds = [ ...new Set(
(Array.isArray(rawIds) ? rawIds : [ rawIds ])
.map(item => Number(item))
.filter(item => Number.isInteger(item) && item > 0)
) ];
if (orderIds.length === 0) {
return this.fail('订单ID不能为空', {}, 400);
}
if (orderIds.length > 200) {
return this.fail('单次最多取消 200 个订单', {}, 400);
}
const warehouseId = this.getWarehouseId();
const operator = this.getOrderLogOperator();
const result = await this.service.systems.orderB2b.cancelOrdersB2b({
warehouseId,
orderIds,
operator,
});
return this.success('ok', result);
}
/**
* 提交订单导出任务。
*
* 入参支持 table_type/module 组合;where 与 sort 语义与订单列表保持一致。
* 方法层负责任务入队与进度缓存,导出由 systems.orderExport 异步执行。
*
* @param {Object} data 请求体。
* @param {string} [data.table_type] 导出表类型(current/history/dispatch/outsourced,兼容模块别名)。
* @param {string} [data.tableType] 导出表类型(驼峰写法)。
* @param {string} [data.module] 订单模块名(可选)。
* @param {string} [data.module_name] 订单模块名(下划线写法)。
* @param {string} [data.export_mode] 导出模式:waybill(默认,按运单展开)或 item(按商品明细展开)。
* @param {string} [data.exportMode] 导出模式(驼峰写法)。
* @param {Array<string>} [data.export_columns] 导出表头字段白名单(中文表头数组),不传或空数组输出全部列;非法表头会报错。
* @param {Array<string>} [data.exportColumns] 导出表头字段白名单(驼峰写法)。
* @param {Object} [data.where] 查询条件。
* @param {Object} [data.sort] 排序参数。
* @return {Promise<Object>} 统一成功包装响应。
*/
async export(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const {
table_type: tableTypeSnake,
tableType: tableTypeCamel,
module: moduleName,
module_name: moduleNameSnake,
export_mode: exportModeSnake,
exportMode: exportModeCamel,
export_columns: exportColumnsSnake,
exportColumns: exportColumnsCamel,
where,
sort,
} = requestData;
const taskId = this.generateExportTaskId();
const tableType = tableTypeSnake || tableTypeCamel || 'current';
const module = moduleName || moduleNameSnake || '';
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: 0,
current_count: 0,
total_count: 0,
message: '导出任务已提交',
result: null,
error: '',
};
await this.setExportTaskProgress(taskId, taskPayload);
setImmediate(async () => {
try {
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'running',
progress: 5,
current_count: 0,
total_count: 0,
message: '导出任务执行中',
result: null,
error: '',
});
const exportMode = exportModeSnake || exportModeCamel || '';
const exportColumns = Array.isArray(exportColumnsSnake)
? exportColumnsSnake
: (Array.isArray(exportColumnsCamel) ? exportColumnsCamel : []);
const result = await this.service.systems.orderExport.exportOrders({
tableType,
moduleName: module,
export_mode: exportMode,
export_columns: exportColumns,
where: this.isPlainObject(where) ? { ...where } : {},
sort: this.isPlainObject(sort) ? { ...sort } : {},
onProgress: async progress => {
const safeProgress = this.isPlainObject(progress) ? progress : {};
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: safeProgress.status || 'running',
progress: safeProgress.progress,
current_count: safeProgress.currentCount,
total_count: safeProgress.totalCount,
message: safeProgress.message || '导出任务执行中',
result: safeProgress.result || null,
error: '',
});
},
});
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'success',
progress: 100,
current_count: result.current_count || 0,
total_count: result.total_count || 0,
message: '导出任务完成',
result,
error: '',
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'failed',
progress: 100,
message: '导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 查询订单导出任务进度。
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @return {Promise<Object>} 统一成功包装响应。
*/
async exportTaskProgress(data = {}) {
const taskId = this.normalizeExportTaskId(data);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const cachedTask = await this.getExportTaskProgress(taskId);
if (!cachedTask) {
return this.success('ok', {
task_id: taskId,
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
const downloadUrl = String(
safeResult.url
|| safeResult.cndUrl
|| safeResult.cdnUrl
|| safeResult.cosUrl
|| safeResult.fileKey
|| ''
);
return this.success('ok', {
task_id: taskId,
...cachedTask,
download_url: downloadUrl,
});
}
/**
* 生成订单导出任务ID。
* @return {string} 任务ID。
*/
generateExportTaskId() {
const warehouseId = this.ctx?.user?.store_id || 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `order_export_${warehouseId}_${timestamp}_${randomToken}`;
}
/**
* 规范导出任务ID。
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID。
* @param {string} [data.taskId] 任务ID。
* @return {string} 规范后的任务ID。
*/
normalizeExportTaskId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
}
/**
* 获取订单导出任务缓存键。
* @param {string} taskId 任务ID。
* @return {string} 缓存键。
*/
getExportTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${ORDER_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入订单导出任务进度缓存。
* @param {string} taskId 任务ID。
* @param {Object} payload 任务状态。
* @return {Promise<void>} 无返回值。
*/
async setExportTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const normalizeCount = value => {
const numericValue = Number(value);
return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0;
};
const progressPayload = {
task_id: String(taskId || '').trim(),
status: String(safePayload.status || 'submitted').trim() || 'submitted',
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
current_count: normalizeCount(safePayload.current_count),
total_count: normalizeCount(safePayload.total_count),
message: String(safePayload.message || ''),
result: safePayload.result ?? null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, ORDER_EXPORT_TASK_CACHE_TTL_SECONDS);
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[order.export] 写入导出任务缓存失败: ${errorMessage}`);
}
}
/**
* 读取订单导出任务进度缓存。
* @param {string} taskId 任务ID。
* @return {Promise<Object|null>} 任务缓存。
*/
async getExportTaskProgress(taskId = '') {
const cacheKey = this.getExportTaskCacheKey(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) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[order.export] 读取导出任务缓存失败: ${errorMessage}`);
return null;
}
}
/**
* 订单工作台总列表入口。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async list(data = {}) {
return await this.listByModule('order', data);
}
/**
* 手动出库入口。
* @param {Object} data 请求体。
* @return {Promise<Object>} 迁移结果。
*/
async manualOutboundOrder(data = {}) {
return await this.ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery(data);
}
/**
* 获取订单工作台 8 个标签页的角标计数。
* 其中配送、异常与归档相关标签页直接返回 99+。
* @return {Promise<Object>} 角标展示值对象。
*/
async badgeCount() {
const warehouseId = this.getWarehouseId();
if (warehouseId === null || warehouseId === undefined || warehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
const cacheKey = this.getBadgeCountCacheKey(warehouseId);
const cachedBadgeCount = await this.app.getCacheAsync(cacheKey);
if (cachedBadgeCount && typeof cachedBadgeCount === 'object') {
return cachedBadgeCount;
}
const [ reviewOrder, pendingOrder, outboundOrder, expectionOrder, entrustOrder ] = await Promise.all([
this.getBadgeCountByModule('reviewOrder', warehouseId),
this.getBadgeCountByModule('pendingOrder', warehouseId),
this.getBadgeCountByModule('outboundOrder', warehouseId),
this.getBadgeCountByModule('expectionOrder', warehouseId),
this.getBadgeCountByModule('entrustOrder', warehouseId),
]);
const badgeCount = {
reviewOrder,
pendingOrder,
outboundOrder,
expectionOrder,
entrustOrder,
deliveryOrder: '99+',
deliveryExpectionOrder: '99+',
archiveOrder: '99+',
};
await this.app.setCacheAsync(cacheKey, badgeCount, 30);
return badgeCount;
}
/**
* 查询订单操作日志。
* @param {Object} data 请求体。
* @param {string|number} data.id 订单ID。
* @param {number} [data.page] 页码。
* @param {number} [data.pageSize] 每页数量。
* @return {Promise<Object>} 统一 success 包装的分页结果。
*/
async queryOrderLogs(data = {}) {
const { ctx, service } = this;
const requestData = data && typeof data === 'object' ? data : {};
const { id, page, pageSize } = requestData;
try {
const result = await service.systems.operationLog.queryOrderLogs({
id,
page,
pageSize,
warehouseId: ctx.user.store_id,
});
return this.success('ok', {
data: result,
code: 200,
});
} catch (e) {
return this.success(e.message, {
code: 200,
});
}
}
/**
* 查询订单日志列表(不分页,返回全部)。
*
* 仅接受 order_id 及常见别名(id、orderId),
* 仓库范围固定使用当前登录用户 store_id,避免越仓读取。
*
* @param {Object} data 请求体。
* @param {string|number} [data.order_id] 订单ID。
* @param {string|number} [data.id] 订单ID别名。
* @param {string|number} [data.orderId] 订单ID别名。
* @return {Promise<Object>} 统一 success/fail 结构。
*/
async queryOrderLogList(data = {}) {
const { service } = this;
const requestData = this.isPlainObject(data) ? data : {};
const {
order_id: orderId,
id,
orderId: orderIdAlias,
} = requestData;
const rawOrderId = orderId ?? id ?? orderIdAlias;
if (rawOrderId === undefined || rawOrderId === null || String(rawOrderId).trim() === '') {
return this.fail('order_id 参数不能为空', {}, 400);
}
const normalizedOrderId = Number(String(rawOrderId).trim());
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
return this.fail('order_id 参数不合法', {}, 400);
}
const warehouseId = this.getWarehouseId();
if (warehouseId === null || warehouseId === undefined || warehouseId === '') {
return this.fail('缺少当前用户仓库上下文 store_id', {}, 400);
}
const logs = await service.systems.operationLog.queryAllOrderLogs({
id: normalizedOrderId,
warehouseId,
});
return this.success('ok', {
list: logs,
total: logs.length,
code: 200,
});
}
/**
* 更新订单运单的称重重量。
*
* 规则:
* - 单运单订单:忽略传入 waybill_code,直接更新唯一记录。
* - 多运单订单:必须传入 waybill_code 且匹配到订单下记录。
* - 团购波次(wave_type = 1):将同一重量批量设置到该波次下所有订单的运单上。
* - 运单号模式(order_id = 0):从运单号反查,必传 waybill_code。团购时按 wave_no + business_key 批量设置。
*
* @param {Object} data 请求体。
* @param {string} [data.waybill_code] 运单号,多运单场景或运单号模式必填。
* @param {number|string} data.order_id 订单ID,传 0 时切换为运单号模式。
* @param {number|string} data.weighing_weight 称重重量(g)。
* @return {Promise<Object>} 统一成功/失败结构。
* 订单模式单订单:{data: {order_id, waybill_code, weighing_weight}};
* 订单模式团购批量:{data: {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name}};
* 运单号模式单运单:{data: {order_id, waybill_code, weighing_weight}};
* 运单号模式团购批量:{data: {wave_id, wave_no, business_key, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name}}。
*/
async updateExpressWeighingWeight(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const {
waybill_code: waybillCode = '',
order_id: orderId,
weighing_weight: weighingWeight,
} = requestData;
try {
let result;
if (Number(orderId) === 0) {
// 运单号模式:从运单号反查订单与波次
result = await this.service.systems.orderExpress.updateWeighingWeightByWaybill({
waybillCode,
weighingWeight,
});
} else {
// 订单模式
result = await this.service.systems.orderExpress.updateWeighingWeight({
orderId,
waybillCode,
weighingWeight,
});
}
return this.success('ok', {
data: result,
code: 200,
});
} catch (error) {
const errorCode = Number(error && error.code);
const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 400;
return this.fail(error && error.message ? error.message : '更新称重重量失败', {
data: null,
}, statusCode);
}
}
/**
* 按订单号与运单号绑定包材。
*
* @param {Object} data 请求体。
* @param {string} data.waybill_code 运单号。
* @param {number|string} data.order_id 订单ID。
* @param {string} data.package_material_code 包材编码。
* @return {Promise<Object>} 统一成功/失败结构。
*/
async bindExpressPackageMaterial(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const {
waybill_code: waybillCode = '',
order_id: orderId,
package_material_code: packageMaterialCode = '',
} = requestData;
try {
const result = await this.service.systems.orderExpress.bindExpressPackageMaterial({
orderId,
waybillCode,
packageMaterialCode,
});
return this.success('ok', {
data: result,
code: 200,
});
} catch (error) {
const errorCode = Number(error && error.code);
const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 500;
return this.fail(error && error.message ? error.message : '绑定包材失败', {
data: null,
}, statusCode);
}
}
/**
* 根据运单号绑定包材。
*
* method 层仅负责参数解构、systems 转发与统一返回结构。
* 无需传入订单ID,仅凭运单号即可完成包材绑定。
*
* 支持团购波次自动感知:
* - 非团购订单:仅绑定当前运单的包材。
* - 团购波次(wave_type=1):自动将同一波次下、相同快递业务键(business_key)的
* 所有运单批量绑定相同的包材,实现一键补齐。
*
* @param {Object} data 请求体。
* @param {string} data.waybill_code 运单号。
* @param {number|string} data.package_material_id 包材ID。
* @return {Promise<Object>} 统一成功/失败结构。
* 单条绑定:data 含 {order_id, waybill_code, package_material_id, package_material_name_snapshot, package_material_code};
* 团购批量绑定:data 含 {wave_id, wave_no, business_key, order_id, waybill_code, package_material_id, package_material_code, package_material_name_snapshot, bind_count, bound_waybills, store_name, sys_logistics_name}。
*/
async bindExpressPackageMaterialByWaybill(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const {
waybill_code: waybillCode = '',
package_material_id: packageMaterialId = '',
} = requestData;
try {
const result = await this.service.systems.orderExpress.bindExpressPackageMaterialByWaybill({
waybillCode,
packageMaterialId,
});
return this.success('ok', {
data: result,
code: 200,
});
} catch (error) {
const errorCode = Number(error && error.code);
const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 500;
return this.fail(error && error.message ? error.message : '绑定包材失败', {
data: null,
}, statusCode);
}
}
/**
* 根据运单号拉取复核数据。
*
* method 层仅负责参数解构、systems 转发与统一返回结构。
*
* @param {Object} data 请求体。
* @param {string} data.waybill_code 运单号。
* @return {Promise<Object>} 统一成功/失败结构。
*/
async pullReviewDataByWaybill(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const {
waybill_code: waybillCode = '',
} = requestData;
try {
const result = await this.service.systems.orderReview.pullReviewDataByWaybill({
waybillCode,
});
return this.success('ok', {
data: result,
code: 200,
});
} catch (error) {
const errorCode = Number(error && error.code);
const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 500;
return this.fail(error && error.message ? error.message : '拉取复核数据失败', {
data: null,
}, statusCode);
}
}
}
module.exports = OrderIndexService;