- 奇门 stockout.create 调用方把「编码+名称」拼接串同时放入 itemId/itemCode/itemName, itemCode 降级精确匹配成功并解析出 stock_id 后,item_id 仍落报文原值(非数字), 写入 BIGINT 列触发 MySQL 严格模式 1366 Incorrect integer value 建单失败 - 对齐 entry_order 建单口径:item_id 统一写实际匹配到的 StockStore 主键 id(纯数字) - 验证:test/temp_test_stockout_itemid_normalize.js 5/5 PASS(非数字 itemId 降级匹配 建单成功 + 数字主键回归);生产日志核实:2026-10-08 10:09 奇门请求 app_key=23204092,stock_id 解析正确仅 item_id 落库报错 - 文档同步:methods/qimen.json 0.3.10 -> 0.3.11,stockout.create 补充 item_id 归一化 notes + changes 变更记录
561 lines
22 KiB
JavaScript
561 lines
22 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../main');
|
||
|
||
/**
|
||
* 非订单出库单(stockout)领域服务。
|
||
*
|
||
* 抽离原 `qimenMethods/stockout.js` 的核心实现,供奇门(stockout.create/query)
|
||
* 与开放 API(openapi stockout.create/query)薄适配层共用:
|
||
* - 落库 `wms_order_stockout` 主表 + `wms_order_stockout_items` 明细表;
|
||
* - 创建时按明细计划数量锁定库存(库存锁标记 `QM_STOCKOUT`,与取消/确认/转单释放口径一致)。
|
||
*
|
||
* 入参沿用奇门报文结构 `data.request.deliveryOrder` / `data.request.orderLines`,
|
||
* 上下文(storeId/warehouseId/warehouseCode/appKey/sourceType)由调用方通过
|
||
* `options` 显式传入,避免领域服务实例依赖 setInfo 状态。
|
||
*/
|
||
class StockoutOrderService extends MainService {
|
||
|
||
/**
|
||
* 解析出库单快递编码(独立于订单兜底链)。
|
||
*
|
||
* 口径:
|
||
* 1. 货主开启 enable_external_express_code 且传了 logisticsCode 时,按
|
||
* wms_express_setting 映射 → 系统快递列表匹配;
|
||
* 2. 未传 / 未开启 / 匹配不到 → 使用出库单兜底快递编码
|
||
* (stockout_default_express_code,默认 ZT 自提),不回退订单默认快递;
|
||
* 不走订单的快递策略漏斗(matchPolicy)。
|
||
* 解析失败仅告警不阻断建单(快递为空,可在确认前手工补填)。
|
||
*
|
||
* @param {Object} deliveryOrder 出库单头信息(奇门 deliveryOrder 节点)。
|
||
* @param {Object} context 上下文,需包含 storeId / warehouseId。
|
||
* @return {Promise<{ expressCode: string|null, expressName: string|null }>} 解析结果。
|
||
*/
|
||
async resolveStockoutExpress(deliveryOrder = {}, context = {}) {
|
||
const { ctx } = this;
|
||
const { storeId, warehouseId } = context;
|
||
|
||
let expressCode = null;
|
||
let expressName = null;
|
||
|
||
try {
|
||
const deliveryOrderService = ctx.service.systems.deliveryOrder;
|
||
const policyConfig = await deliveryOrderService.getStoreWarehousePolicyConfig(storeId, warehouseId);
|
||
const expressList = await ctx.service.systems.express.getExpressList();
|
||
const findExpress = code => {
|
||
const upperCode = String(code || '').trim().toUpperCase();
|
||
if (!upperCode || !Array.isArray(expressList)) {
|
||
return null;
|
||
}
|
||
return expressList.find(item => item
|
||
&& String(item.code || item.value || '').trim().toUpperCase() === upperCode) || null;
|
||
};
|
||
const externalCode = String(deliveryOrder.logisticsCode || '').trim();
|
||
const enableExternal = deliveryOrderService.normalizePolicyFlag(
|
||
policyConfig && policyConfig.enable_external_express_code
|
||
);
|
||
|
||
if (enableExternal && externalCode) {
|
||
// 1) wms_express_setting 外部编码映射 → 系统快递编码
|
||
const settingSnapshot = await deliveryOrderService.resolveExpressSettingSnapshot(externalCode, warehouseId);
|
||
if (settingSnapshot && settingSnapshot.expressCode) {
|
||
const sysCode = String(settingSnapshot.expressCode).trim();
|
||
const sysItem = findExpress(sysCode);
|
||
expressCode = sysCode;
|
||
expressName = sysItem
|
||
? String(sysItem.name || sysItem.label || sysCode).trim()
|
||
: String(settingSnapshot.name || sysCode).trim();
|
||
} else {
|
||
// 2) 系统快递列表直接匹配
|
||
const matched = findExpress(externalCode);
|
||
if (matched) {
|
||
expressCode = String(matched.code || matched.value || externalCode).trim();
|
||
expressName = String(matched.name || matched.label || expressCode).trim();
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!expressCode) {
|
||
// 兜底:出库单兜底快递编码(货主配置,默认 ZT 自提),不回退订单默认快递
|
||
const fallbackCode = String(policyConfig && policyConfig.stockout_default_express_code || '').trim() || 'ZT';
|
||
const fallbackItem = findExpress(fallbackCode);
|
||
expressCode = fallbackItem
|
||
? String(fallbackItem.code || fallbackItem.value || fallbackCode).trim()
|
||
: fallbackCode;
|
||
expressName = fallbackItem
|
||
? String(fallbackItem.name || fallbackItem.label || fallbackCode).trim()
|
||
: fallbackCode;
|
||
}
|
||
} catch (err) {
|
||
ctx.logger.warn(`[stockout.create] 快递编码解析失败,保持为空: ${err.message}`);
|
||
}
|
||
|
||
return { expressCode, expressName };
|
||
}
|
||
|
||
/**
|
||
* 创建出库单。
|
||
*
|
||
* 将请求的 deliveryOrder / orderLines 写入 `wms_order_stockout` 主表和
|
||
* `wms_order_stockout_items` 明细表,并库存锁定,整个过程在一个数据库事务内完成,
|
||
* 失败自动回滚。
|
||
*
|
||
* @param {Object} data 请求体,遵循奇门报文结构。
|
||
* @param {Object} data.request 请求数据。
|
||
* @param {Object} data.request.deliveryOrder 出库单头信息。
|
||
* @param {Object} data.request.orderLines 出库单明细。
|
||
* @param {Object|Object[]} data.request.orderLines.orderLine 明细行(单条为对象,多条为数组)。
|
||
* @param {Object} options 上下文与来源。
|
||
* @param {number} options.storeId 货主ID。
|
||
* @param {number} options.warehouseId 仓库ID。
|
||
* @param {string} [options.warehouseCode] 仓库编码。
|
||
* @param {string} [options.appKey] 开放接口 app_key(用于 StockStore 降级匹配)。
|
||
* @param {string} [options.sourceType='QM'] 来源类型(QM / API / WMS)。
|
||
* @return {Promise<Object>} 返回 success / fail 结果。
|
||
*/
|
||
async create(data, options = {}) {
|
||
const { app, ctx } = this;
|
||
const { storeId, warehouseId, warehouseCode, appKey } = options;
|
||
const sourceType = options.sourceType || 'QM';
|
||
const { deliveryOrder, orderLines } = data.request;
|
||
|
||
// 单条 orderLine 转为数组
|
||
let orderLine = orderLines && orderLines.orderLine;
|
||
if (orderLine && orderLine.orderLineNo) {
|
||
orderLine = [ orderLine ];
|
||
}
|
||
|
||
if (!orderLine || !Array.isArray(orderLine) || orderLine.length === 0) {
|
||
return this.fail('创建出库单失败,失败原因:\n没有有效的订单明细数据');
|
||
}
|
||
|
||
const totalOrderLines = deliveryOrder.totalOrderLines || orderLine.length;
|
||
|
||
// 快递编码解析
|
||
const { expressCode, expressName } = await this.resolveStockoutExpress(deliveryOrder, {
|
||
storeId,
|
||
warehouseId,
|
||
});
|
||
|
||
// 收件人信息解析(receiverInfo 13 个标准字段落库,供转订单与确认回传使用)
|
||
const receiver = deliveryOrder.receiverInfo && typeof deliveryOrder.receiverInfo === 'object'
|
||
? deliveryOrder.receiverInfo
|
||
: {};
|
||
const receiverFields = {
|
||
receiver_company: receiver.company,
|
||
receiver_name: receiver.name,
|
||
receiver_zip_code: receiver.zipCode,
|
||
receiver_tel: receiver.tel,
|
||
receiver_mobile: receiver.mobile,
|
||
receiver_email: receiver.email,
|
||
receiver_country_code: receiver.countryCode,
|
||
receiver_province: receiver.province,
|
||
receiver_city: receiver.city,
|
||
receiver_area: receiver.area,
|
||
receiver_town: receiver.town,
|
||
receiver_detail_address: receiver.detailAddress,
|
||
receiver_id: receiver.id,
|
||
};
|
||
for (const key of Object.keys(receiverFields)) {
|
||
const rawValue = receiverFields[key];
|
||
receiverFields[key] = rawValue === undefined || rawValue === null
|
||
? null
|
||
: String(rawValue).trim() || null;
|
||
}
|
||
|
||
// 第一步:校验所有商品是否在 StockStore 中存在,并收集有效明细
|
||
const errors = [];
|
||
const items = [];
|
||
for (let i = 0; i < orderLine.length; i++) {
|
||
const line = orderLine[i];
|
||
let wmsStock = await app.model.StockStore.findByPk(line.itemId);
|
||
// 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权
|
||
if (wmsStock && Number(wmsStock.store_id) !== Number(storeId)) {
|
||
wmsStock = null;
|
||
}
|
||
// 外部渠道 itemId 可能是平台商品标识或条码而非 WMS 主键,
|
||
// 主键查不到或跨货主时降级按 item_code + 仓库货主维度查找
|
||
if (!wmsStock && line.itemCode) {
|
||
const stockWhere = {
|
||
item_code: line.itemCode,
|
||
warehouse_id: warehouseId,
|
||
store_id: storeId,
|
||
};
|
||
if (appKey) {
|
||
stockWhere.app_key = appKey;
|
||
}
|
||
wmsStock = await app.model.StockStore.findOne({ where: stockWhere });
|
||
}
|
||
if (!wmsStock) {
|
||
errors.push(
|
||
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`
|
||
);
|
||
continue;
|
||
}
|
||
if (!wmsStock.stock_id) {
|
||
errors.push(
|
||
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》wms无对应关系\n请联系仓库关联创建商品`
|
||
);
|
||
continue;
|
||
}
|
||
const planQty = parseInt(line.planQty) || 0;
|
||
if (planQty <= 0) {
|
||
errors.push(
|
||
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n计划数量必须大于0`
|
||
);
|
||
continue;
|
||
}
|
||
items.push({
|
||
orderLineNo: line.orderLineNo,
|
||
ownerCode: line.ownerCode,
|
||
itemCode: line.itemCode,
|
||
// item_id 统一写入实际匹配到的 StockStore 主键 id(纯数字),
|
||
// 避免调用方把「编码+名称」等非数字值放进 itemId 时写入 BIGINT 列
|
||
// 触发 MySQL 严格模式报错(与 entry_order 建单口径一致)
|
||
itemId: wmsStock.id,
|
||
itemName: line.itemName,
|
||
planQty,
|
||
inventoryType: line.inventoryType,
|
||
stockId: wmsStock.stock_id,
|
||
});
|
||
}
|
||
|
||
if (errors.length > 0) {
|
||
return this.fail(`创建出库单失败,失败原因:\n${errors.join('\n')}`);
|
||
}
|
||
|
||
// 预取超卖配置,避免每次 lockItemStorages 在锁内回退查 DB
|
||
const oversellConfig = await ctx.service.systems.stockStore
|
||
.getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId);
|
||
|
||
// 第二步:在事务中写入主表 + 库存锁定 + 明细表
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
const order = await ctx.model.OrderStockout.create(
|
||
{
|
||
stockout_order_code: deliveryOrder.deliveryOrderCode,
|
||
order_type: deliveryOrder.orderType,
|
||
total_order_lines: totalOrderLines,
|
||
order_create_time: deliveryOrder.createTime
|
||
? new Date(deliveryOrder.createTime)
|
||
: null,
|
||
remark: deliveryOrder.remark || null,
|
||
express_code: expressCode,
|
||
express_name: expressName,
|
||
...receiverFields,
|
||
warehouse_id: warehouseId,
|
||
store_id: storeId,
|
||
qimen_owner_code: items[0].ownerCode,
|
||
qimen_warehouse_code: warehouseCode,
|
||
source_type: sourceType,
|
||
created_at: new Date(),
|
||
updated_at: new Date(),
|
||
},
|
||
{ transaction }
|
||
);
|
||
|
||
const orderId = order.id;
|
||
|
||
// 库存锁定:按 stockId 升序排序后逐个加锁,避免死锁
|
||
const sortedItems = [ ...items ].sort((a, b) => a.stockId - b.stockId);
|
||
for (const item of sortedItems) {
|
||
const lockResult = await ctx.service.systems.stockStore.lockItemStorages(
|
||
item.stockId,
|
||
item.planQty,
|
||
transaction,
|
||
oversellConfig,
|
||
{ orderType: 'QM_STOCKOUT', orderNo: deliveryOrder.deliveryOrderCode, orderId }
|
||
);
|
||
if (!lockResult.success) {
|
||
throw new Error(
|
||
`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》\n库存锁定失败: ${lockResult.error}`
|
||
);
|
||
}
|
||
}
|
||
|
||
// 批量创建明细
|
||
const now = new Date();
|
||
const itemRecords = items.map(item => ({
|
||
order_id: orderId,
|
||
order_line_no: item.orderLineNo,
|
||
owner_code: item.ownerCode,
|
||
item_code: item.itemCode,
|
||
item_id: item.itemId,
|
||
item_name: item.itemName,
|
||
plan_qty: item.planQty,
|
||
inventory_type: item.inventoryType,
|
||
stock_id: item.stockId,
|
||
created_at: now,
|
||
updated_at: now,
|
||
}));
|
||
|
||
await ctx.model.OrderStockoutItems.bulkCreate(itemRecords, {
|
||
transaction,
|
||
validate: true,
|
||
});
|
||
|
||
await transaction.commit();
|
||
|
||
return this.success('出库单创建成功', {
|
||
stockoutOrderId: order.id,
|
||
stockoutOrderCode: order.stockout_order_code,
|
||
});
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
ctx.logger.error('[stockout.create] 事务写入失败:', err);
|
||
return this.fail(`创建出库单失败,失败原因:\n${err.message}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 查询出库单。
|
||
*
|
||
* 根据 deliveryOrderCode 查 `wms_order_stockout` 主表,
|
||
* 然后关联查 `wms_order_stockout_items` 明细,返回标准结构。
|
||
*
|
||
* @param {Object} data 请求体,遵循奇门报文结构。
|
||
* @param {Object} data.request 请求数据。
|
||
* @param {Object} data.request.deliveryOrder 出库单查询条件。
|
||
* @param {string} data.request.deliveryOrder.deliveryOrderCode 出库单号。
|
||
* @return {Promise<Object>} 返回 success / fail 结果。
|
||
*/
|
||
async query(data) {
|
||
const { app, ctx } = this;
|
||
const { deliveryOrderCode } = data.request.deliveryOrder;
|
||
|
||
// 查主表
|
||
const order = await ctx.model.OrderStockout.findOne({
|
||
where: { stockout_order_code: deliveryOrderCode },
|
||
});
|
||
if (!order) {
|
||
return this.fail('未找到出库单');
|
||
}
|
||
|
||
// 查明细
|
||
const items = await ctx.model.OrderStockoutItems.findAll({
|
||
where: { order_id: order.id },
|
||
order: [[ 'order_line_no', 'ASC' ]],
|
||
});
|
||
|
||
return this.success('成功', {
|
||
totalLines: items.length,
|
||
deliveryOrder: {
|
||
deliveryOrderCode: order.stockout_order_code,
|
||
deliveryOrderId: order.id,
|
||
warehouseCode: order.qimen_warehouse_code,
|
||
orderType: order.order_type,
|
||
status: order.order_status,
|
||
createTime: order.order_create_time ? app.formatDate(order.order_create_time) : null,
|
||
remark: order.remark || '',
|
||
},
|
||
orderLines: {
|
||
orderLine: items.map(item => ({
|
||
orderLineNo: item.order_line_no,
|
||
ownerCode: item.owner_code,
|
||
itemCode: item.item_code,
|
||
itemId: item.item_id,
|
||
itemName: item.item_name,
|
||
planQty: item.plan_qty,
|
||
inventoryType: item.inventory_type,
|
||
})),
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 取消出库单(奇门 / openapi / systemMethods 共用)。
|
||
*
|
||
* 定位方式:优先按 stockoutOrderCode,其次按 id;上下文(storeId / warehouseId /
|
||
* operatorLabel)一律由 options 显式传入,不读取 ctx.user。仅 CREATED / PENDING
|
||
* 状态允许取消:事务内(行锁)释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK
|
||
* 流水),状态置 CANCELLED 并写操作日志;已 CANCELLED 幂等返回成功;
|
||
* COMPLETED / TRANSFERRED 等其他状态拒绝取消。
|
||
* 取消成功后不需要向奇门 / 开放平台回传任何事件。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {string} [data.stockoutOrderCode] 出库单号(优先)。
|
||
* @param {number} [data.id] 出库单ID。
|
||
* @param {Object} options 上下文。
|
||
* @param {number|null} [options.storeId] 货主ID(有值时参与定位条件)。
|
||
* @param {number} options.warehouseId 仓库ID。
|
||
* @param {string} [options.operatorLabel] 操作人标识(写入操作日志,如 qimen:xxx / openapi:xxx)。
|
||
* @return {Promise<Object>} 统一成功/失败包装响应,成功时返回 id / stockout_order_code / order_status。
|
||
*/
|
||
async cancel(data = {}, options = {}) {
|
||
const { ctx } = this;
|
||
const { storeId, warehouseId, operatorLabel } = options;
|
||
const stockoutOrderCode = String(data.stockoutOrderCode || '').trim();
|
||
const id = Number(data.id || 0);
|
||
const normalizedWarehouseId = Number(warehouseId) || 0;
|
||
|
||
if (normalizedWarehouseId <= 0) {
|
||
return this.fail('缺少仓库上下文');
|
||
}
|
||
|
||
if (!stockoutOrderCode && !(id > 0)) {
|
||
return this.fail('出库单号不能为空');
|
||
}
|
||
|
||
// 定位条件:仓库 + 货主(有值时)+ 软删除过滤;单号优先,否则按 ID
|
||
const where = {
|
||
warehouse_id: normalizedWarehouseId,
|
||
deleted_at: null,
|
||
};
|
||
if (storeId !== undefined && storeId !== null && storeId !== '') {
|
||
where.store_id = Number(storeId);
|
||
}
|
||
if (stockoutOrderCode) {
|
||
where.stockout_order_code = stockoutOrderCode;
|
||
} else {
|
||
where.id = id;
|
||
}
|
||
|
||
const transaction = await ctx.model.transaction();
|
||
let order;
|
||
try {
|
||
// 行锁防并发取消 / 确认 / 转单
|
||
order = await ctx.model.OrderStockout.findOne({
|
||
where,
|
||
transaction,
|
||
lock: transaction.LOCK.UPDATE,
|
||
});
|
||
if (!order) {
|
||
await transaction.rollback();
|
||
return this.fail('未找到对应的出库单');
|
||
}
|
||
|
||
// 幂等:已取消直接返回成功,不重复释放库存
|
||
if (String(order.order_status || '').trim() === 'CANCELLED') {
|
||
await transaction.rollback();
|
||
return this.success('取消出库单成功', {
|
||
id: order.id,
|
||
stockout_order_code: order.stockout_order_code,
|
||
order_status: 'CANCELLED',
|
||
});
|
||
}
|
||
|
||
// 状态守卫:仅 CREATED / PENDING 允许取消(与 storage.stockout.cancel 同口径)
|
||
if (!order.canCancel || !order.canCancel()) {
|
||
await transaction.rollback();
|
||
return this.fail(`出库单当前状态(${order.order_status})不允许取消`);
|
||
}
|
||
|
||
const items = await ctx.model.OrderStockoutItems.findAll({
|
||
where: { order_id: order.id },
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
// 释放创建时占用的库存锁定(口径与 storage.stockout.cancel 完全一致)
|
||
let releasedQty = 0;
|
||
for (const item of items) {
|
||
const qty = Number(item.plan_qty) || 0;
|
||
if (qty <= 0) continue;
|
||
const releaseResult = await ctx.service.systems.stockStore.lockItemStorages(
|
||
item.stock_id,
|
||
-qty,
|
||
transaction,
|
||
null,
|
||
{
|
||
orderType: 'QM_STOCKOUT',
|
||
orderNo: order.stockout_order_code,
|
||
orderId: order.id,
|
||
remark: '出库单取消释放锁定',
|
||
}
|
||
);
|
||
if (!releaseResult.success) {
|
||
// 已释放过(锁定不足)视为幂等成功,避免阻断重试
|
||
const alreadyReleased = String(releaseResult.error || '').includes('释放数量超过已锁定库存');
|
||
if (alreadyReleased) {
|
||
ctx.logger.warn(`[stockout.cancel] 库存${item.stock_id}锁定已释放,跳过: ${releaseResult.error}`);
|
||
continue;
|
||
}
|
||
throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`);
|
||
}
|
||
releasedQty += qty;
|
||
}
|
||
|
||
await ctx.model.OrderStockout.update(
|
||
{ order_status: 'CANCELLED', sync_message: '已取消', updated_at: new Date() },
|
||
{ where: { id: order.id }, transaction }
|
||
);
|
||
|
||
await this._writeStockoutOperationLog(
|
||
order,
|
||
'STOCKOUT_CANCEL',
|
||
`出库单已取消,释放锁定库存 ${releasedQty}`,
|
||
{
|
||
transaction,
|
||
warehouseId: normalizedWarehouseId,
|
||
operator: { id: null, name: operatorLabel || 'system' },
|
||
}
|
||
);
|
||
|
||
await transaction.commit();
|
||
} catch (err) {
|
||
try {
|
||
await transaction.rollback();
|
||
} catch (rollbackErr) {
|
||
ctx.logger.error('[stockout.cancel] 事务回滚失败:', rollbackErr);
|
||
}
|
||
ctx.logger.error(`[stockout.cancel] 取消失败: ${err.message}`);
|
||
return this.fail(`取消失败:${err.message}`);
|
||
}
|
||
|
||
ctx.logger.info(`[stockout.cancel] 取消完成: ${order.stockout_order_code}`);
|
||
return this.success('取消出库单成功', {
|
||
id: order.id,
|
||
stockout_order_code: order.stockout_order_code,
|
||
order_status: 'CANCELLED',
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 写 wms_operation_log 操作日志(businessType=stockout),失败仅告警不影响主流程。
|
||
*
|
||
* 与 systemMethods/storage/stockout 历史日志口径一致;操作人 / 仓库信息由
|
||
* options 显式传入,不读取 ctx.user(供奇门 / openapi 等无登录用户上下文渠道复用)。
|
||
*
|
||
* @param {Object} order 出库单实例或行。
|
||
* @param {string} operationCode 操作编码(如 STOCKOUT_CANCEL)。
|
||
* @param {string} message 日志内容。
|
||
* @param {Object} [options={}] 选项。
|
||
* @param {Object} [options.transaction] 数据库事务对象。
|
||
* @param {number|null} [options.warehouseId] 仓库ID,缺省回退出库单自身 warehouse_id。
|
||
* @param {Object} [options.operator={}] 操作人信息,含 id / name。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async _writeStockoutOperationLog(order, operationCode, message, options = {}) {
|
||
const { ctx } = this;
|
||
const opLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||
if (!opLogService || typeof opLogService.createOperationLogs !== 'function') {
|
||
ctx.logger.warn('[stockout] 操作日志服务不可用,跳过记录');
|
||
return;
|
||
}
|
||
const operator = options.operator || {};
|
||
try {
|
||
await opLogService.createOperationLogs([
|
||
{
|
||
businessType: 'stockout',
|
||
businessId: order.id,
|
||
operationCode,
|
||
operator: {
|
||
id: operator.id ?? null,
|
||
name: String(operator.name || 'system'),
|
||
},
|
||
extras: {
|
||
warehouseId: options.warehouseId ?? order.warehouse_id ?? null,
|
||
message,
|
||
externalLogType: 'NONE',
|
||
},
|
||
},
|
||
], { transaction: options.transaction });
|
||
} catch (err) {
|
||
ctx.logger.warn(`[stockout] 写操作日志失败: ${err.message}`);
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
module.exports = StockoutOrderService;
|