348 lines
11 KiB
JavaScript
348 lines
11 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../main');
|
||
|
||
class OpenapiOrderService extends MainService {
|
||
/**
|
||
* 通过 app_key 解析仓库与货主信息。
|
||
* 查询 ApiApp 并关联 StoreWarehouse 以获取 storeId、warehouseId。
|
||
* @param {string} appKey 开放接口 app_key。
|
||
* @return {Promise<Object>} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。
|
||
*/
|
||
async resolveAppInfo(appKey) {
|
||
const { ctx, app } = this;
|
||
const normalizedAppKey = String(appKey || '').trim();
|
||
if (!normalizedAppKey) {
|
||
throw new Error('app_key 缺失');
|
||
}
|
||
|
||
const appConfig = await ctx.model.ApiApp.findOne({
|
||
attributes: [
|
||
'id',
|
||
'warehouse_id',
|
||
[ app.Sequelize.col('contract.store_id'), 'store_id' ],
|
||
],
|
||
where: {
|
||
self_app_key: normalizedAppKey,
|
||
is_enabled: 1,
|
||
},
|
||
include: [
|
||
{
|
||
model: ctx.model.StoreWarehouse,
|
||
as: 'contract',
|
||
attributes: [],
|
||
required: false,
|
||
},
|
||
],
|
||
raw: true,
|
||
});
|
||
|
||
if (!appConfig || !appConfig.warehouse_id) {
|
||
throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`);
|
||
}
|
||
|
||
return {
|
||
storeId: appConfig.store_id || null,
|
||
warehouseId: appConfig.warehouse_id,
|
||
appKey: normalizedAppKey,
|
||
customerId: null,
|
||
warehouseCode: '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 取消发货单。
|
||
* 当前仅支持出库单类型(JYCK/HHCK/BFCK → ORDER),非出库单类型返回不支持。
|
||
* @param {Object} payload 调用参数。
|
||
* @param {Object} payload.body 请求体数据,包含 orderCode、orderType。
|
||
* @param {Object} payload.query 请求 query 数据,包含 app_key。
|
||
* @return {Promise<Object>} 取消结果,成功时返回成功消息,失败时返回错误信息。
|
||
*/
|
||
async cancel(payload = {}) {
|
||
const { ctx } = this;
|
||
const { body = {}, query = {} } = payload;
|
||
const { orderCode } = body;
|
||
const orderType = String(body.orderType || 'JYCK').trim().toUpperCase();
|
||
|
||
// 出库单类型映射:JYCK / HHCK / BFCK → ORDER
|
||
const ORDER_TYPES = [ 'JYCK', 'HHCK', 'BFCK' ];
|
||
if (!ORDER_TYPES.includes(orderType)) {
|
||
return this.fail('暂不支持该订单类型的取消操作');
|
||
}
|
||
|
||
const normalizedOrderCode = String(orderCode || '').trim();
|
||
if (!normalizedOrderCode) {
|
||
return this.fail('orderCode 参数缺失');
|
||
}
|
||
|
||
try {
|
||
const info = await this.resolveAppInfo(query.app_key);
|
||
|
||
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId);
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
const existingOrder = await DeliveryModel.findOne({
|
||
where: {
|
||
delivery_order_code: normalizedOrderCode,
|
||
warehouse_id: info.warehouseId,
|
||
store_id: info.storeId,
|
||
},
|
||
transaction,
|
||
lock: transaction.LOCK.UPDATE,
|
||
});
|
||
|
||
if (!existingOrder) {
|
||
await transaction.rollback();
|
||
return this.fail('未找到对应的订单');
|
||
}
|
||
|
||
const pickStatus = String(existingOrder.pick_status || 'none').trim();
|
||
const printStatus = String(existingOrder.print_status || 'none').trim();
|
||
|
||
if (pickStatus !== 'none' || printStatus !== 'none') {
|
||
await existingOrder.update({
|
||
intercept_status: 'intercepting',
|
||
updated_at: new Date(),
|
||
}, {
|
||
transaction,
|
||
});
|
||
|
||
await transaction.commit();
|
||
return this.fail('取消失败,已通知拦截执行');
|
||
}
|
||
|
||
await existingOrder.update({
|
||
status: 'cancel',
|
||
outbound_status: 'fin',
|
||
step: 4,
|
||
updated_at: new Date(),
|
||
}, {
|
||
transaction,
|
||
});
|
||
|
||
// 释放储位分配锁定库存
|
||
await this.releaseStockLockForCancel({
|
||
orderId: existingOrder.id,
|
||
warehouseId: info.warehouseId,
|
||
transaction,
|
||
});
|
||
|
||
await transaction.commit();
|
||
|
||
// 写入取消操作日志(不影响主流程)
|
||
try {
|
||
if (this.ctx.model && this.ctx.model.OperationLog) {
|
||
const appKey = String(query.app_key || '').trim();
|
||
await this.ctx.model.OperationLog.create({
|
||
business_type: 'order',
|
||
business_id: String(existingOrder.id),
|
||
operation_code: 'ORDER_CANCEL',
|
||
operator_id: null,
|
||
operator_name: appKey ? `openapi:${appKey}` : 'openapi',
|
||
external_log_type: 'NONE',
|
||
warehouse_id: info.warehouseId || null,
|
||
platform_code: appKey || 'SYSTEM',
|
||
message: 'OpenAPI 取消订单',
|
||
});
|
||
}
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[OpenapiOrderCancel] 写入取消操作日志失败,不影响主流程', logErr);
|
||
}
|
||
|
||
// 取消成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程)
|
||
try {
|
||
const callbackService = this.ctx.service.openapi && this.ctx.service.openapi.callback;
|
||
if (callbackService && typeof callbackService.sendByAppKey === 'function') {
|
||
const appKey = String(query.app_key || '').trim();
|
||
if (appKey) {
|
||
callbackService.sendByAppKey({
|
||
appKey,
|
||
event: 'order_cancelled',
|
||
data: {
|
||
orderCode,
|
||
status: 'cancelled',
|
||
},
|
||
}).catch(err => {
|
||
this.ctx.logger.warn('[OpenapiOrderCancel] 回调忽略失败: %s', err.message);
|
||
});
|
||
}
|
||
}
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[OpenapiOrderCancel] 触发回调异常,不影响主流程: %s', err.message);
|
||
}
|
||
|
||
return this.success('取消订单成功');
|
||
} catch (error) {
|
||
try {
|
||
await transaction.rollback();
|
||
} catch (rollbackError) {
|
||
ctx.logger.error(`取消订单回滚失败: ${rollbackError.message}`);
|
||
}
|
||
ctx.logger.error(`取消订单失败: ${error.message}`);
|
||
return this.fail(error.message || '取消订单失败');
|
||
}
|
||
} catch (error) {
|
||
return this.fail(`取消订单失败: ${error.message}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 取消订单时释放储位分配锁定库存。
|
||
* - 有 wms_picking 记录时:释放 wms_storage.locked_quantity 与 wms_stock_warehouse.locked_quantity,
|
||
* 并删除对应的 wms_picking 分配记录。
|
||
* - 无 wms_picking 记录时:从 wms_order_items 查询该订单的 stock_id 与 plan_qty,
|
||
* 只释放 wms_stock_warehouse.locked_quantity。
|
||
*
|
||
* @param {Object} options - 释放参数。
|
||
* @param {number} options.orderId - 订单ID。
|
||
* @param {number} options.warehouseId - 仓库ID。
|
||
* @param {Object} options.transaction - 数据库事务对象。
|
||
* @return {Promise<void>}
|
||
*/
|
||
async releaseStockLockForCancel({ orderId, warehouseId, transaction } = {}) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
|
||
if (!orderId || !warehouseId) {
|
||
return;
|
||
}
|
||
|
||
const pickingModel = ctx.model.Picking;
|
||
const storageModel = ctx.model.Storage;
|
||
const stockModel = ctx.model.StockWarehouse;
|
||
|
||
if (!pickingModel || !storageModel || !stockModel) {
|
||
ctx.logger.warn('[openapi order.cancel releaseStockLockForCancel] 模型不可用,跳过库存释放');
|
||
return;
|
||
}
|
||
|
||
// 查找该订单的有效分配记录
|
||
const pickingRows = await pickingModel.findAll({
|
||
where: {
|
||
order_id: orderId,
|
||
status: { [Op.ne]: 'cancel' },
|
||
},
|
||
transaction,
|
||
lock: transaction.LOCK.UPDATE,
|
||
raw: true,
|
||
});
|
||
|
||
if (!Array.isArray(pickingRows) || pickingRows.length === 0) {
|
||
// 无储位分配记录:从订单明细获取锁定信息,只释放 stock_warehouse 锁
|
||
const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||
if (!orderItemsModel) {
|
||
ctx.logger.warn('[openapi order.cancel releaseStockLockForCancel] OrderItems 模型不可用,跳过库存释放');
|
||
return;
|
||
}
|
||
|
||
const orderItems = await orderItemsModel.findAll({
|
||
where: { order_id: orderId },
|
||
attributes: [ 'stock_id', 'plan_qty' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
for (const item of orderItems) {
|
||
const stockId = Number(item.stock_id || 0);
|
||
const qty = Number(item.plan_qty || 0);
|
||
if (stockId <= 0 || qty <= 0) continue;
|
||
|
||
await stockModel.update(
|
||
{
|
||
locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`),
|
||
updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||
},
|
||
{
|
||
where: { id: stockId, locked_quantity: { [Op.gte]: qty } },
|
||
transaction,
|
||
}
|
||
);
|
||
}
|
||
return;
|
||
}
|
||
|
||
// 按 storage_id 汇总释放数量
|
||
const storageQuantityMap = new Map();
|
||
for (const row of pickingRows) {
|
||
const storageId = Number(row.storage_id || 0);
|
||
const quantity = Number(row.quantity || 0);
|
||
if (storageId > 0 && quantity > 0) {
|
||
storageQuantityMap.set(storageId, (storageQuantityMap.get(storageId) || 0) + quantity);
|
||
}
|
||
}
|
||
|
||
if (storageQuantityMap.size === 0) {
|
||
return;
|
||
}
|
||
|
||
// 查出关联的 wms_storage 记录,获取 stock_id
|
||
const storageIds = Array.from(storageQuantityMap.keys());
|
||
const storageRows = await storageModel.findAll({
|
||
where: {
|
||
id: { [Op.in]: storageIds },
|
||
},
|
||
transaction,
|
||
lock: transaction.LOCK.UPDATE,
|
||
raw: true,
|
||
});
|
||
|
||
const storageMap = new Map();
|
||
for (const row of storageRows) {
|
||
storageMap.set(Number(row.id), row);
|
||
}
|
||
|
||
// 依次释放 wms_storage 与 wms_stock_warehouse 锁定数量
|
||
for (const [ storageId, quantity ] of storageQuantityMap.entries()) {
|
||
const storageRow = storageMap.get(storageId);
|
||
if (!storageRow) {
|
||
ctx.logger.warn(`[openapi order.cancel] 库存记录不存在,跳过: storageId=${storageId}`);
|
||
continue;
|
||
}
|
||
|
||
const stockId = Number(storageRow.stock_id || 0);
|
||
if (stockId <= 0) {
|
||
ctx.logger.warn(`[openapi order.cancel] 库存记录缺少 stock_id,跳过: storageId=${storageId}`);
|
||
continue;
|
||
}
|
||
|
||
// 释放 wms_storage.locked_quantity
|
||
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction });
|
||
|
||
// 释放 wms_stock_warehouse.locked_quantity
|
||
const decrementResult = await stockModel.update(
|
||
{
|
||
locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`),
|
||
updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||
},
|
||
{
|
||
where: {
|
||
id: stockId,
|
||
locked_quantity: { [Op.gte]: Number(quantity) },
|
||
},
|
||
transaction,
|
||
}
|
||
);
|
||
|
||
if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) {
|
||
throw new Error(`库存主记录锁定数量不足,无法释放: stockId=${stockId}, quantity=${quantity}`);
|
||
}
|
||
}
|
||
|
||
// 删除已释放的分配记录
|
||
const pickingIds = pickingRows
|
||
.map(row => Number(row.id || 0))
|
||
.filter(id => id > 0);
|
||
|
||
if (pickingIds.length > 0) {
|
||
await pickingModel.destroy({
|
||
where: {
|
||
id: { [Op.in]: pickingIds },
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = OpenapiOrderService;
|