WMS_MAIN/app/service/systems/operation_log.js
liufumingren 0a6e82e00a feat(order): B2B 订单作业链路(列表/转换/取消/波次排除/作业明细表重构)
- 新增 order.pendingOrder2b.list / order.deliveryOrder2b.list:复用待处理与配送列表条件,
  强制 is_b2b='Y'(fixedWhere 以 AND 追加,请求 where 无法覆盖),并带出 wms_order_b2b
  作业明细字段(total_box_count/pickup_plate_number/prep_remark/prep_duration_seconds/
  prep_at/is_picked_up/picked_up_at/created_at),无明细行时输出空值占位
- B2B 列表 where 支持按作业明细字段筛选:先按 warehouse_id + order_id 查副表取 order_id,
  再以 id IN (...) 回填;该筛选仅这两个接口开放,不影响普通订单列表
- 其余订单列表(order/reviewOrder/pendingOrder/outboundOrder/expectionOrder/entrustOrder/
  deliveryOrder/deliveryExpectionOrder/archiveOrder 及 waveStrategyFallbackOrderList)
  统一追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不再混入普通列表
- order.convertToB2b 收紧准入:status!=cancel、step in [1,2,3]、未拣货、未复核、未锁定、
  未拦截、未 B2B(打印状态不限制);已在波次中的订单转换后在同一事务内从波次摘除
  (含库内抓取订单),波次存在进行中拣货任务则跳过
- order.cancelB2b 放开打印限制,作业明细由软删除改为物理删除
- 波次抓取全链路排除 B2B:补上自动加团 appendOrderToWave / countCandidateGroupOrders
  两处遗漏;抽出 detachOrdersFromWavesInTransaction 供 batchRemoveOrders 与转 B2B 复用
- wms_order_delivery 分表新增 is_b2b 列表索引(current/dispatch,等值列前置 + 排序列),
  由订单工厂结构漂移同步自动补建
- 迁移 20261115180000-refactor-wms-order-b2b:新增 prep_at;移除 is_print/updated_at/
  deleted_at/delivery_order_code/store_id;唯一键改 uk_warehouse_order(warehouse_id, order_id);
  迁移前清理历史软删除行与重复行(开发库与生产库均已执行)
- operation_log 兜底用 changeSummary 写入 message,修复转/取消 B2B 日志操作说明为空
- 同步 methods/system.json 与变更记录 0.3.351~0.3.360

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-17 01:30:08 +08:00

355 lines
12 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.

// app/service/systems/operation_log.js
'use strict';
const Service = require('egg').Service;
const OPERATION_LOG_ATTRIBUTES = [
'id',
'operation_code',
'operator_name',
'created_at',
'external_log_type',
'external_log_id',
'platform_code',
'message',
];
class operationLogService extends Service {
/**
* 将单条日志参数转换为数据库字段。
* @param {Object} params 日志参数。
* @param {string} params.businessType 业务类型。
* @param {string|number} params.businessId 业务ID。
* @param {string} params.operationCode 操作编码。
* @param {Object} [params.operator={}] 操作人信息。
* @param {string} [params.changeSummary=''] 变更描述(extras.message 缺省时作为日志说明落库)。
* @param {Object} [params.extras={}] 扩展字段。
* @param {Object|null} [params.beforeChanges=null] 操作前快照。
* @return {Object} 可直接落库的日志数据。
*/
buildOperationLogData(params = {}) {
const { ctx } = this;
const {
businessType,
businessId,
operationCode,
operator = {},
beforeChanges = null,
changeSummary = '',
extras = {},
} = params;
return {
business_type: businessType,
business_id: String(businessId),
operation_code: operationCode,
// 使用 nullish 合并符,确保当 operator.id 为 0 时仍然保留 0
operator_id: operator?.id ?? null,
operator_name: operator?.name ?? null,
external_log_type: extras.externalLogType || 'NONE',
external_log_id: extras.externalLogId ?? null,
warehouse_id: extras.warehouseId ?? null,
before_changes: beforeChanges,
platform_code: ctx.user?.platform_code || 'SYSTEM',
// 日志说明:优先 extras.message;调用方只传 changeSummary 时回退使用,避免前端"操作说明"为空
message: extras.message || changeSummary || null,
};
}
/**
* 规范并校验日志查询入参,强制要求业务ID与仓库ID。
* @param {Object} query 查询参数。
* @param {string} businessType 业务类型。
* @return {{ where: Object, id: string|number, warehouseId: string|number }} 查询条件。
*/
buildBusinessLogWhere(query = {}, businessType) {
const requestQuery = query && typeof query === 'object' ? query : {};
const {
id,
warehouseId,
} = requestQuery;
if (!id) {
throw new Error('id不能为空');
}
if (!warehouseId) {
throw new Error('仓库id不能为空');
}
return {
where: {
business_type: businessType,
business_id: id,
warehouse_id: warehouseId,
},
id,
warehouseId,
};
}
/**
* 将日志模型结果格式化为接口输出结构。
* @param {Object[]} rows 日志行数据。
* @return {Object[]} 格式化后的日志列表。
*/
formatOperationLogRows(rows = []) {
const { app } = this;
return rows.map(item => {
const itemTmp = JSON.parse(JSON.stringify(item));
itemTmp.operation_name = app.getOperationCodeName(item.operation_code);
itemTmp.platform_name = app.getPlatformName(item.platform_code);
itemTmp.created_at = app.formatDate(itemTmp.created_at);
return itemTmp;
});
}
/**
* 通用操作日志记录方法
* @param {Object} params 日志参数
* @param {string} params.businessType 业务类型: product, order, stock, wave, express, storage
* @param {string} params.businessId 业务ID
* @param {string} params.operationCode 操作编码
* @param {Object} params.operator 操作人信息
* @param {string} params.operator.id 操作人ID
* @param {string} params.operator.name 操作人名称
* @param {string} params.operationAction 操作动作: CREATE, UPDATE, DELETE, OTHER
* @param {string} params.changeSummary 变更描述
* @param {Object} params.keyChanges 关键变更字段
* @param {Object} params.extras 额外参数
* @param {string} params.extras.externalLogType 外部日志类型
* @param {number} params.extras.externalLogId 外部日志ID
* @param {number} params.extras.warehouseId 仓库ID
* @param {string} params.extras.message 日志信息
* @param {Object} [params.transaction] 事务对象(可选)
*
*/
async createOperationLog(params = {}) {
const { ctx } = this;
const {
businessType,
businessId,
transaction,
} = params;
try {
const logData = this.buildOperationLogData(params);
const createOptions = {};
if (transaction) {
createOptions.transaction = transaction;
}
const result = await ctx.model.OperationLog.create(logData, createOptions);
ctx.logger.info(`[OperationLog] 记录操作日志成功,ID: ${result.id}, Business: ${businessType}/${businessId}`);
return result;
} catch (error) {
ctx.logger.error(`[OperationLog] 记录操作日志失败: ${error.message}`, error);
// 生产环境建议添加降级处理,如写入文件或发送到监控系统
return null;
}
}
/**
* 批量写入操作日志,优先使用 bulkCreate,失败时自动降级单条写入。
* @param {Array<Object>} paramsList 日志参数数组。
* @param {Object} [options={}] 写入选项。
* @param {Object} [options.transaction] 事务对象(可选)。
* @return {Promise<Array<Object|null>>} 写入结果数组。
*/
async createOperationLogs(paramsList = [], options = {}) {
const { ctx } = this;
const requestOptions = options && typeof options === 'object' ? options : {};
const transaction = requestOptions.transaction;
const normalizedParamsList = Array.isArray(paramsList) ? paramsList.filter(Boolean) : [];
if (normalizedParamsList.length === 0) {
return [];
}
const operationLogModel = ctx.model && ctx.model.OperationLog;
if (!operationLogModel || typeof operationLogModel.bulkCreate !== 'function') {
ctx.logger.warn('[OperationLog] OperationLog.bulkCreate 不可用,降级单条写入');
return await Promise.all(normalizedParamsList.map(item => this.createOperationLog({
...item,
transaction: item && item.transaction ? item.transaction : transaction,
})));
}
try {
const rows = normalizedParamsList.map(item => this.buildOperationLogData(item));
const bulkCreateOptions = {};
if (transaction) {
bulkCreateOptions.transaction = transaction;
}
return await operationLogModel.bulkCreate(rows, bulkCreateOptions);
} catch (error) {
ctx.logger.error(`[OperationLog] 批量记录操作日志失败,降级单条写入: ${error.message}`, error);
return await Promise.all(normalizedParamsList.map(item => this.createOperationLog({
...item,
transaction: item && item.transaction ? item.transaction : transaction,
})));
}
}
/**
* 按业务类型查询操作日志分页数据。
* @param {Object} query 查询参数。
* @param {string|number} query.id 业务ID。
* @param {string|number} query.warehouseId 仓库ID。
* @param {number} [query.page=1] 页码。
* @param {number} [query.pageSize=20] 每页数量。
* @param {string} businessType 业务类型。
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
*/
async queryLogsByBusinessType(query = {}, businessType) {
const { ctx } = this;
const requestQuery = query && typeof query === 'object' ? query : {};
const {
page = 1,
pageSize = 20,
} = requestQuery;
const { where } = this.buildBusinessLogWhere(requestQuery, businessType);
const currentPage = Number.parseInt(page, 10) || 1;
const currentPageSize = Number.parseInt(pageSize, 10) || 20;
const offset = (currentPage - 1) * currentPageSize;
const result = await ctx.model.OperationLog.findAndCountAll({
where,
order: [[ 'created_at', 'DESC' ]],
offset,
attributes: OPERATION_LOG_ATTRIBUTES,
limit: currentPageSize,
});
const rows = Array.isArray(result.rows) ? result.rows : [];
return {
list: this.formatOperationLogRows(rows),
pagination: {
page: currentPage,
pageSize: currentPageSize,
total: result.count,
totalPages: Math.ceil(result.count / currentPageSize),
},
};
}
/**
* 查询库存操作日志。
* @param {Object} query 查询参数。
* @param {string|number} query.id 库存业务ID。
* @param {string|number} query.warehouseId 仓库ID。
* @param {number} [query.page=1] 页码。
* @param {number} [query.pageSize=20] 每页数量。
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
*/
async queryStockLogs(query = {}) {
return await this.queryLogsByBusinessType(query, 'stock');
}
/**
* 查询订单操作日志。
* @param {Object} query 查询参数。
* @param {string|number} query.id 订单ID。
* @param {string|number} query.warehouseId 仓库ID。
* @param {number} [query.page=1] 页码。
* @param {number} [query.pageSize=20] 每页数量。
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
*/
async queryOrderLogs(query = {}) {
return await this.queryLogsByBusinessType(query, 'order');
}
/**
* 查询订单操作日志(不分页,返回全部)。
* @param {Object} query 查询参数。
* @param {string|number} query.id 订单ID。
* @param {string|number} query.warehouseId 仓库ID。
* @return {Promise<Object[]>} 日志列表。
*/
async queryAllOrderLogs(query = {}) {
return await this.queryAllLogsByBusinessType(query, 'order');
}
/**
* 按业务类型查询日志全量数据(不分页)。
* @param {Object} query 查询参数。
* @param {string|number} query.id 业务ID。
* @param {string|number} query.warehouseId 仓库ID。
* @param {string} businessType 业务类型。
* @return {Promise<Object[]>} 日志列表。
*/
async queryAllLogsByBusinessType(query = {}, businessType) {
const { ctx } = this;
const requestQuery = query && typeof query === 'object' ? query : {};
const { where } = this.buildBusinessLogWhere(requestQuery, businessType);
const rows = await ctx.model.OperationLog.findAll({
where,
order: [[ 'created_at', 'DESC' ]],
attributes: OPERATION_LOG_ATTRIBUTES,
raw: true,
});
const normalizedRows = Array.isArray(rows) ? rows : [];
return this.formatOperationLogRows(normalizedRows);
}
/**
* 查询收货单操作日志。
* @param {Object} query 查询参数。
* @param {string|number} query.id 收货单ID。
* @param {string|number} query.warehouseId 仓库ID。
* @param {number} [query.page=1] 页码。
* @param {number} [query.pageSize=20] 每页数量。
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
*/
async queryReceivingLogs(query = {}) {
return await this.queryLogsByBusinessType(query, 'receiving');
}
/**
* 查询入库单操作日志。
* @param {Object} query 查询参数。
* @param {string|number} query.id 入库单ID。
* @param {string|number} query.warehouseId 仓库ID。
* @param {number} [query.page=1] 页码。
* @param {number} [query.pageSize=20] 每页数量。
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
*/
async queryEntryOrderLogs(query = {}) {
return await this.queryLogsByBusinessType(query, 'entry_order');
}
/**
* 查询出库单操作日志。
* @param {Object} query 查询参数。
* @param {string|number} query.id 出库单ID。
* @param {string|number} query.warehouseId 仓库ID。
* @param {number} [query.page=1] 页码。
* @param {number} [query.pageSize=20] 每页数量。
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
*/
async queryStockoutLogs(query = {}) {
return await this.queryLogsByBusinessType(query, 'stockout');
}
async getMessageDetail(data) {
const { id, type } = data;
const { ctx } = this;
let LogModel = null;
switch (type) {
case 'QIMEN':
LogModel = ctx.model.QimenLog;
break;
default:
throw new Error(`不支持的日志类型: ${type}`);
}
const result = await LogModel.findOne({ where: { id } });
return result;
}
}
module.exports = operationLogService;