feat(stock.transaction): 新增 UNLOCK 类型,取消锁定时写入 UNLOCK 而非 OUTBOUND

- stock_transaction 枚举新增 UNLOCK(取消锁定)

- stock_store 取消锁定时写 UNLOCK 流水

- 迁移: 20260711160000-add-unlock-to-wms-stock-transaction
This commit is contained in:
liufumingren 2026-07-27 03:45:54 +08:00
parent aedd815e17
commit 7ff7285222
3 changed files with 288 additions and 67 deletions

View File

@ -11,9 +11,9 @@ module.exports = app => {
comment: '主键ID',
},
transaction_type: {
type: ENUM('INBOUND', 'OUTBOUND', 'LOCK'),
type: ENUM('INBOUND', 'OUTBOUND', 'LOCK', 'UNLOCK'),
allowNull: false,
comment: '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定',
comment: '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定 UNLOCK取消锁定',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,

View File

@ -151,8 +151,8 @@ class stockStoreService extends Service {
width: parseFloat(stockData.width) || 0,
height: parseFloat(stockData.height) || 0,
volume: parseFloat(stockData.volume) || 0,
grossWeight: parseFloat(stockData.gross_weight) || 0,
netWeight: parseFloat(stockData.net_weight) || 0,
grossWeight: parseFloat(stockData.gross_weight) || 0, // 单位 g,Qimen 接口输出
netWeight: parseFloat(stockData.net_weight) || 0, // 单位 g,Qimen 接口输出
// 分类信息
categoryId: stockData.category_id || 0,
@ -732,9 +732,9 @@ class stockStoreService extends Service {
// 写入流水(除非显式跳过)
const skipLog = meta.skipTransactionLog === true;
if (!skipLog && ctx.service && ctx.service.systems && ctx.service.systems.stockTransaction) {
// 锁定操作使用 LOCK 类型,释放操作使用 OUTBOUND
// 锁定操作使用 LOCK 类型,释放操作(如取消订单)使用 UNLOCK
await ctx.service.systems.stockTransaction.create({
transaction_type: isLocking ? 'LOCK' : 'OUTBOUND',
transaction_type: isLocking ? 'LOCK' : 'UNLOCK',
warehouse_id: stockRecord.warehouse_id,
store_id: stockRecord.store_id,
stock_id: stockId,
@ -1589,7 +1589,7 @@ class stockStoreService extends Service {
* @param {string} sortParams.sortOrder - 排序方式,默认'DESC'
* @return {Promise<Object>} 返回查询结果
*/
async getWarehouseStock(where, pageParams = {}, sortParams = {}) {
async getWarehouseStock(where, pageParams = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) {
const {
ctx,
app,
@ -1601,6 +1601,15 @@ class stockStoreService extends Service {
Op,
} = Sequelize;
// 仓库ID:优先使用外部传入,否则取当前用户上下文
const warehouseId = Number.isFinite(externalWarehouseId) && externalWarehouseId > 0
? externalWarehouseId
: ctx.user.store_id;
// 货主ID:外部传入时按货主维度查询(不限定仓库)
const storeId = Number.isFinite(externalStoreId) && externalStoreId > 0
? externalStoreId
: 0;
try {
// 设置默认参数
const {
@ -1631,16 +1640,30 @@ class stockStoreService extends Service {
where: {},
};
// 添加默认条件
queryOptions.where[Op.and] = [{
warehouse_id: ctx.user.store_id,
},
{
is_valid: 'Y',
},
{
deleted_at: null,
},
];
if (storeId > 0) {
// 按货主维度查询(不限定仓库)
queryOptions.where[Op.and] = [{
store_id: storeId,
},
{
is_valid: 'Y',
},
{
deleted_at: null,
},
];
} else {
queryOptions.where[Op.and] = [{
warehouse_id: warehouseId,
},
{
is_valid: 'Y',
},
{
deleted_at: null,
},
];
}
barcodeQueryOptions.where[Op.and] = [];
prohibitedQueryOptions.where[Op.and] = [];
storeOutStockQueryOptions.where[Op.and] = [];
@ -1675,6 +1698,9 @@ class stockStoreService extends Service {
bucket: 'storeOutStock',
field: 'stock_id',
},
keyword: {
bucket: 'keyword',
},
},
});
@ -1691,12 +1717,6 @@ class stockStoreService extends Service {
hasPrevious: false,
hasNext: false,
},
summary: {
total_quantity: 0,
total_locked: 0,
total_available: 0,
total_items: 0,
},
},
message: `筛选条件解析失败: ${parsed.reason}`,
};
@ -1726,6 +1746,22 @@ class stockStoreService extends Service {
boundItemValue = rawConditionsByField.has_bound_item.value;
}
// keyword 快捷搜索:模糊匹配商品编码/名称/货物编码
const keywordInput = rawConditionsByField.keyword || null;
const keywordValue = keywordInput && typeof keywordInput === 'object'
? keywordInput.value
: keywordInput;
if (keywordValue !== undefined && keywordValue !== null && String(keywordValue).trim() !== '') {
const kw = `%${String(keywordValue).trim()}%`;
queryOptions.where[Op.and].push({
[Op.or]: [
{ item_code: { [Op.like]: kw } },
{ item_name: { [Op.like]: kw } },
{ goods_code: { [Op.like]: kw } },
],
});
}
if (dynamicConditions.length > 0) {
queryOptions.where[Op.and].push({
[Op.and]: dynamicConditions,
@ -1838,12 +1874,6 @@ class stockStoreService extends Service {
hasPrevious: false,
hasNext: false,
},
summary: {
total_quantity: 0,
total_locked: 0,
total_available: 0,
total_items: 0,
},
},
message: '查询成功',
};
@ -1861,12 +1891,16 @@ class stockStoreService extends Service {
// 处理排序
const validSortFields = [
'id', 'item_code', 'item_name', 'quantity', 'locked_quantity',
'tag_price', 'retail_price', 'create_at', 'update_at',
'tag_price', 'retail_price', 'create_at', 'update_at', 'available_quantity',
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at';
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
queryOptions.order.push([ actualSortField, actualSortOrder ]);
if (actualSortField === 'available_quantity') {
queryOptions.order.push([ Sequelize.literal('(quantity - locked_quantity)'), actualSortOrder ]);
} else {
queryOptions.order.push([ actualSortField, actualSortOrder ]);
}
// 计算分页偏移量
const offset = (page - 1) * pageSize;
@ -1881,12 +1915,41 @@ class stockStoreService extends Service {
);
// 构建 include 数组
const includes = [
ctx.model.StoreWarehouse.buildStoreStockInclude({
warehouseId: ctx.user.store_id,
let storeStockInclude;
if (storeId > 0) {
// 按货主维度查询:确保 store_warehouse 关联同时匹配 store_id 和 warehouse_id,避免一对多导致行重复
storeStockInclude = {
model: ctx.model.StoreWarehouse,
as: 'store_stock',
attributes: [ 'warehouse_remask' ],
where: {
store_id: storeId,
warehouse_use_status: 1,
[Op.and]: Sequelize.where(
Sequelize.col('stock_warehouse.warehouse_id'),
'=',
Sequelize.col('store_stock.warehouse_id')
),
},
required: false,
include: [{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ 'company_name' ],
required: false,
}],
};
} else {
storeStockInclude = ctx.model.StoreWarehouse.buildStoreStockInclude({
warehouseId,
required: true,
attributes: [ 'store_remask' ],
}),
});
}
const includes = [
storeStockInclude,
{
...prohibitedQueryOptions,
model: ctx.model.ProhibitedType,
@ -1968,21 +2031,23 @@ class stockStoreService extends Service {
barcodeMap.get(sid).push(bc);
}
// 按 business_id 分组图片(有图片即认为 is_images=Y)
const imageStockIdSet = new Set();
// 按 stock_id 分组图片
const imageMap = new Map();
for (const row of imageRows) {
const sid = Number(row.business_id);
const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || '';
if (url) {
imageStockIdSet.add(sid);
if (!url) continue;
if (!imageMap.has(sid)) {
imageMap.set(sid, []);
}
imageMap.get(sid).push(url);
}
for (const item of data) {
const sid = item.id;
stockDetailsMap.set(sid, {
barcodes: barcodeMap.get(sid) || [],
images: [],
images: imageMap.get(sid) || [],
});
}
}
@ -1997,8 +2062,18 @@ class stockStoreService extends Service {
const stockDetail = stockDetailsMap.get(item.id);
const itemBarcodes = stockDetail ? stockDetail.barcodes : [];
const itemImages = stockDetail ? stockDetail.images : [];
// 货主维度:仓库备注兜底仓库主体名
let warehouseRemask = '';
if (storeId > 0) {
warehouseRemask = (item['store_stock.warehouse_remask'] || '')
|| (item['store_stock.warehouse.company_name'] || '');
delete item['store_stock.warehouse_remask'];
delete item['store_stock.warehouse'];
delete item['store_stock.warehouse.company_name'];
}
return {
...item,
...(storeId > 0 ? { warehouse_remask: warehouseRemask } : {}),
barcodes: itemBarcodes,
images: itemImages,
available_quantity: availableQuantity,
@ -2011,20 +2086,6 @@ class stockStoreService extends Service {
};
});
// 添加汇总信息
const summary = {
total_quantity: data.reduce((sum, item) => sum + item.quantity, 0),
total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0),
total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item
.locked_quantity), 0),
total_items: data.length,
// 如果有条码查询,添加匹配统计
...(hasBarcodeCondition && {
barcode_matched_count: matchedStockIds.length,
barcode_search_value: parsedBarcodeInput ? parsedBarcodeInput.value : null,
}),
};
return {
code: 200,
data: {
@ -2037,7 +2098,6 @@ class stockStoreService extends Service {
hasPrevious,
hasNext,
},
summary,
queryInfo: {
conditions: normalizedWhere,
sortField: actualSortField,
@ -2062,12 +2122,6 @@ class stockStoreService extends Service {
hasPrevious: false,
hasNext: false,
},
summary: {
total_quantity: 0,
total_locked: 0,
total_available: 0,
total_items: 0,
},
},
message: `查询失败: ${error.message}`,
};
@ -2197,6 +2251,131 @@ class stockStoreService extends Service {
});
}
/**
* 导出外仓商品列表。
* 说明:复用 getWarehouseStock 的外部货主维度筛选语义,分页拉取全量数据后生成 Excel 并上传。
* @param {Object} where 筛选条件
* @param {Object} sortParams 排序参数
* @param {string} [sortParams.sortField] 排序字段
* @param {string} [sortParams.sortOrder] 排序方向(ASC|DESC)
* @param {number} [externalWarehouseId=0] 外部仓库ID(0 表示按货主维度查)
* @param {number} [externalStoreId=0] 外部货主ID
* @return {Promise<Object>} 导出上传结果(含 url/fileKey 等)
*/
async exportExternalWarehouseStock(where = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) {
const { ctx } = this;
const warehouseId = externalWarehouseId > 0 ? externalWarehouseId : (ctx.user && ctx.user.store_id ? ctx.user.store_id : 'common');
const pageSize = 500;
let page = 1;
let hasNext = true;
const rows = [];
while (hasNext) {
const pageResult = await this.getWarehouseStock(where, {
page,
pageSize,
}, sortParams, externalWarehouseId, externalStoreId);
if (!pageResult || pageResult.code !== 200) {
throw new Error(pageResult && pageResult.message ? pageResult.message : '导出外仓商品失败');
}
const list = pageResult.data && Array.isArray(pageResult.data.list) ? pageResult.data.list : [];
// 收集可能的 storeIds,用于回退查询 store_remask(优先取 item.store_id,其次 item['store_warehouse.store_id'])
const storeIds = [];
for (const item of list) {
const sid = item.store_id || item['store_warehouse.store_id'];
if (sid && !storeIds.includes(Number(sid))) {
storeIds.push(Number(sid));
}
}
// 查询 StoreWarehouse 获取 store_remask(如果可用)
const storeMap = new Map();
try {
if (storeIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) {
const { Op } = ctx.app.Sequelize;
const storeWhere = { store_id: { [Op.in]: storeIds } };
if (externalWarehouseId > 0) {
storeWhere.warehouse_id = externalWarehouseId;
}
const storeRows = await ctx.model.StoreWarehouse.findAll({
attributes: [ 'store_id', 'store_remask' ],
where: storeWhere,
raw: true,
});
for (const r of storeRows || []) {
storeMap.set(Number(r.store_id), r.store_remask);
}
}
} catch (e) {
ctx && ctx.logger && ctx.logger.warn && ctx.logger.warn('[exportExternalWarehouseStock] 查询 StoreWarehouse 失败', e && e.message);
}
for (const item of list) {
const storeId = Number(item.store_id || item['store_warehouse.store_id'] || 0);
const storeRemask = item.store_remask || item['store_warehouse.store_remask'] || storeMap.get(storeId) || '';
rows.push({
id: item.id,
item_code: item.item_code,
goods_code: item.goods_code || '',
item_name: item.item_name,
brand_name: item.brand_name || '',
sku_property: item.sku_property || '',
stock_unit: item.stock_unit || '',
tag_price: item.tag_price || '',
retail_price: item.retail_price || '',
gross_weight: item.gross_weight || '',
store_remask: storeRemask,
barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '',
quantity: item.quantity,
locked_quantity: item.locked_quantity,
available_quantity: item.available_quantity,
lock_rate_display: item.lock_rate_display,
create_at_display: item.create_at_display,
update_at_display: item.update_at_display,
});
}
hasNext = Boolean(pageResult.data && pageResult.data.pagination && pageResult.data.pagination.hasNext);
page += 1;
}
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${String(now.getMilliseconds()).padStart(3, '0')}`;
return await ctx.service.systems.excel.generateAndUpload({
filename: `外仓商品导出_${dateToken}.xlsx`,
dir: `exports/stock/warehouse/${warehouseId}`,
category: 'document',
sheets: [{
name: '外仓商品',
columns: [
{ header: 'SKU', key: 'id' },
{ header: '商品编码', key: 'item_code' },
{ header: '货物编码', key: 'goods_code' },
{ header: '商品名称', key: 'item_name' },
{ header: '品牌', key: 'brand_name' },
{ header: '规格', key: 'sku_property' },
{ header: '库存单位', key: 'stock_unit' },
{ header: '标价', key: 'tag_price' },
{ header: '零售价', key: 'retail_price' },
{ header: '毛重', key: 'gross_weight' },
{ header: '货主', key: 'store_remask' },
{ header: '条码', key: 'barcodes' },
{ header: '库存', key: 'quantity' },
{ header: '锁定库存', key: 'locked_quantity' },
{ header: '可用库存', key: 'available_quantity' },
{ header: '锁定率', key: 'lock_rate_display' },
{ header: '创建时间', key: 'create_at_display' },
{ header: '更新时间', key: 'update_at_display' },
],
rows,
}],
});
}
/**
* 构建Sequelize查询条件
* @param {string} fieldKey - 字段键名
@ -2394,10 +2573,10 @@ class stockStoreService extends Service {
};
} else if (method === 'gross_weight') {
// 毛重应该是数字
const updateValue = parseFloat(value);
if (isNaN(updateValue) || updateValue < 0) {
return { message: '毛重必须是有效的正数', code: 405 };
// 毛重必须为正整数(单位 g)
const updateValue = parseInt(value, 10);
if (isNaN(updateValue) || updateValue < 0 || !Number.isInteger(Number(value))) {
return { message: '毛重必须是有效的正整数(单位 g)', code: 405 };
}
updateData = {
gross_weight: updateValue,
@ -2555,7 +2734,8 @@ class stockStoreService extends Service {
const {
stock_id = null, store_id = null, page = 1, pageSize = 20, item_code = '', item_name = '',
} = data || {};
const warehouseId = ctx.user.store_id;
// 优先使用 systemMethods 层校验后传入的 warehouse_id
const warehouseId = Number(data._warehouseId || 0) || ctx.user.store_id;
let barcodes = [];
let warehouseStock = null;
let total = 0;
@ -2649,12 +2829,26 @@ class stockStoreService extends Service {
}),
]);
}
// 批量查询奇门应用名称
const appKeys = [...new Set(barcodes.map(item => item.app_key).filter(Boolean))];
const qimenAppMap = new Map();
if (appKeys.length > 0) {
const qimenApps = await ctx.model.QimenApp.findAll({
where: { app_key: appKeys },
attributes: [ 'app_key', 'name' ],
raw: true,
});
for (const app of qimenApps) {
qimenAppMap.set(app.app_key, app.name || '');
}
}
const results = barcodes.map(item => {
return {
app_key: item.app_key,
create_from: item.create_from === 'qimen' ? '奇门' : 'API',
id: item.id,
app_name: item.app_key,
app_name: qimenAppMap.get(item.app_key) || item.app_key,
item_code: item.item_code,
stock_id: item['warehouse_stock.id'],
hasBind: !!item.stock_id,

View File

@ -0,0 +1,27 @@
'use strict';
/**
* 为 wms_stock_transaction.transaction_type ENUM 增加 UNLOCK。
* UNLOCK:库存释放流水(如取消订单释放创建锁)。
*/
module.exports = {
async up(queryInterface) {
const { sequelize } = queryInterface;
await sequelize.query(`
ALTER TABLE wms_stock_transaction
MODIFY COLUMN transaction_type ENUM(
'INBOUND', 'OUTBOUND', 'LOCK', 'UNLOCK'
) NOT NULL COMMENT '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定 UNLOCK解锁'
`);
},
async down(queryInterface) {
const { sequelize } = queryInterface;
await sequelize.query(`
ALTER TABLE wms_stock_transaction
MODIFY COLUMN transaction_type ENUM(
'INBOUND', 'OUTBOUND', 'LOCK'
) NOT NULL COMMENT '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定'
`);
},
};