fix(stock.check): 上报强制 space_id 并按库位ID落库,修复作业挂到已删除分区的库位
- stock.check.report:space_id 必传(兼容 spaceId/location_id/locationId),校验仓库归属、分区有效、与 location 编码一致,缺失/非法/跨仓库/无头库位均返回 400;服务端不再按库位编码猜库位 - report:实盘数量上限 2147483647(原超限落库 Out of range 变 500);写库库位以 space_id 为准 - workData / workDataSpaceDetails / workDataDetail:space 视图行与 goods 视图 locations[] 补 space_id、location_id;space 视图记录库位归一(同编码不再出现幽灵行),明细按「库位+商品」索引、记录按「库位+商品」聚合 - 操作日志 STOCK_CHECK_REPORT:message 补库位编码/库位ID,before_changes 落库位与明细库位快照 - location.zone:createZone/updateZone 增加同仓库 zone_code 唯一校验(归档分区不占用编码,沿用规则编码),避免重复货架生成同编码库位 - 新增运维脚本(默认只读,--prod 指定生产):盘点库位一致性体检/订正(只改坏记录,两分支互斥)、作业记录指向已删除库位体检与 CSV 导出;无头库位引用统计改为分批 IN 查询,避免大表相关子查询导致生产连接重置 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
0e7545bd9a
commit
de2f66a2d1
@ -59,9 +59,9 @@ class StockCheckMethodService extends MainService {
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.title] 盘点名称/主题。
|
||||
* @param {string} [data.type] 盘点范围类型:all/store/goods/location。
|
||||
* @param {string} [data.type] 盘点范围类型:location/store/goods,缺省 location。
|
||||
* @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘;
|
||||
* 按库位盘点(all/location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
|
||||
* 按库位盘点(location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
|
||||
* @param {number} [data.store_id] 货主ID(按货主盘点时必填)。
|
||||
* @param {string} [data.remark] 备注。
|
||||
* 盘点日期固定为今天,前端不传。
|
||||
@ -151,7 +151,7 @@ class StockCheckMethodService extends MainService {
|
||||
* @param {Object} [data.pagination] 分页参数。
|
||||
* @param {Object} [data.where] 查询条件。
|
||||
* @param {string|Array<string>} [data.where.status] 状态筛选(单值或数组)。
|
||||
* @param {string|Array<string>} [data.where.type] 范围类型筛选(all/store/goods/location)。
|
||||
* @param {string|Array<string>} [data.where.type] 范围类型筛选(location/store/goods)。
|
||||
* @param {string|Array<string>} [data.where.mode] 盘点方式筛选(open/blind)。
|
||||
* @param {number} [data.where.store_id] 货主筛选。
|
||||
* @param {string} [data.where.keyword] 关键字(单号/标题模糊)。
|
||||
@ -334,7 +334,7 @@ class StockCheckMethodService extends MainService {
|
||||
/**
|
||||
* 拉取盘点作业数据(视图由任务类型与 is_goods 驱动)。
|
||||
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
|
||||
* 视图规则:任务范围为库位(type=location/all)时一律按库位视图返回(无视 view/is_goods);
|
||||
* 视图规则:任务范围为库位(type=location)时一律按库位视图返回(无视 view/is_goods);
|
||||
* 任务范围为商品(type=goods/store)时默认聚合库位视图(space),
|
||||
* 仅传入 is_goods=true 时按商品视图(goods)返回。
|
||||
* 分页:data.pagination.{page,pageSize}(与 stock.check.list 口径一致,
|
||||
@ -386,7 +386,7 @@ class StockCheckMethodService extends MainService {
|
||||
/**
|
||||
* 拉取盘点作业数据(space 视图分页版)。
|
||||
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
|
||||
* 行结构与 workData space 视图行一致(id=库位ID/space_code/custom_barcode/custom_name/goods,
|
||||
* 行结构与 workData space 视图行一致(id=库位ID/location_id 同义库位ID/space_code/custom_barcode/custom_name/goods,
|
||||
* goods 行含 detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/
|
||||
* record_ids,明盘另含 system_quantity/checked_quantity,status=checked/unchecked);
|
||||
* 传入 location_id 时只返回该库位行(total=1),不传时按分页返回全部库位行。
|
||||
@ -450,8 +450,10 @@ class StockCheckMethodService extends MainService {
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.id 盘点任务ID。
|
||||
* @param {number} data.detail_id 明细ID。
|
||||
* @param {string} [data.location] 库位编码(可空;库位明细行以明细库位为准)。
|
||||
* @param {number} data.quantity 实盘数量(>=0)。
|
||||
* @param {number} data.space_id 库位ID(wms_location_space.id,**必传**;兼容 spaceId / location_id / locationId 写法)。
|
||||
* 必须属于本仓库且所属分区有效;服务端以该 ID 为准落库,不再按库位编码猜库位。
|
||||
* @param {string} [data.location] 库位编码(可选,仅做一致性校验:与 space_id 对应库位编码不一致报 400)。
|
||||
* @param {number} data.quantity 实盘数量(>=0 且 <= 2147483647)。
|
||||
* @param {number} [data.stock_id] 商品库存ID(wms_stock_warehouse.id;库位明细行必填,或改传 barcode)。
|
||||
* @param {string} [data.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品,未命中记为未知商品)。
|
||||
* @param {string} [data.item_name] 未知商品名称(缺省为 barcode;已知商品忽略)。
|
||||
@ -472,7 +474,13 @@ class StockCheckMethodService extends MainService {
|
||||
barcode,
|
||||
item_name: itemName,
|
||||
is_empty: isEmpty,
|
||||
space_id: spaceIdSnake,
|
||||
spaceId: spaceIdCamel,
|
||||
location_id: locationIdSnake,
|
||||
locationId: locationIdCamel,
|
||||
} = data || {};
|
||||
const spaceId = [ spaceIdSnake, spaceIdCamel, locationIdSnake, locationIdCamel ]
|
||||
.find(value => value !== undefined && value !== null && value !== '');
|
||||
|
||||
return this._call(
|
||||
() => this.service.systems.stockCheck.report({
|
||||
@ -480,6 +488,7 @@ class StockCheckMethodService extends MainService {
|
||||
id,
|
||||
detailId,
|
||||
location,
|
||||
spaceId,
|
||||
quantity,
|
||||
stockId,
|
||||
barcode,
|
||||
@ -494,7 +503,7 @@ class StockCheckMethodService extends MainService {
|
||||
|
||||
/**
|
||||
* 标记库位为空(库位盘点模式专属)。
|
||||
* warehouse_id 由服务端从当前上下文自动注入;仅任务范围为库位(type=location/all)时允许,
|
||||
* warehouse_id 由服务端从当前上下文自动注入;仅任务范围为库位(type=location)时允许,
|
||||
* 非库位任务报 400;状态仅 approved/checking;明细必须属于本任务且为库位范围行。
|
||||
* 行为与 report(is_empty=true) 一致:写/更新空标记记录、清除该明细商品记录、重算汇总。
|
||||
*
|
||||
@ -594,7 +603,7 @@ class StockCheckMethodService extends MainService {
|
||||
/**
|
||||
* 重盘清除库位(按库位清除盘点信息,库位盘点模式专属)。
|
||||
* 传入任务ID与库位ID,清除该库位范围内明细的全部作业记录(含空库位标记),该库位回到未盘;
|
||||
* 仅任务范围为库位(type=location/all)且状态 approved/checking 时允许,非库位任务报 400。
|
||||
* 仅任务范围为库位(type=location)且状态 approved/checking 时允许,非库位任务报 400。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {number} data.id 盘点任务ID。
|
||||
|
||||
@ -376,9 +376,44 @@ class LocationZoneService extends Service {
|
||||
return count === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验分区编码在同仓库未占用(已归档分区不占用编码:paranoid 查询自动带 deleted_at IS NULL)。
|
||||
* 同仓库同 zone_code 并存会生成同 space_code 的库位行,导致盘点/库存按编码定位到多条库位。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {string} zoneCode 分区编码。
|
||||
* @param {number} [excludeZoneId] 排除的分区ID(更新场景排除自身)。
|
||||
* @return {Promise<void>} 校验不通过时抛出错误。
|
||||
*/
|
||||
async assertZoneCodeAvailable(warehouseId, zoneCode, excludeZoneId = 0) {
|
||||
const { ctx } = this;
|
||||
const code = String(zoneCode || '').trim();
|
||||
if (!code) {
|
||||
return;
|
||||
}
|
||||
if (!/^[A-Z0-9]{1,5}$/.test(code)) {
|
||||
throw new Error('编码必须是1-5位大写字母或数字');
|
||||
}
|
||||
const where = {
|
||||
warehouse_id: Number(warehouseId),
|
||||
zone_code: code,
|
||||
};
|
||||
if (Number(excludeZoneId) > 0) {
|
||||
where.id = { [ctx.app.Sequelize.Op.ne]: Number(excludeZoneId) };
|
||||
}
|
||||
const exists = await ctx.model.LocationZone.findOne({
|
||||
where,
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (exists) {
|
||||
throw new Error(`分区编码已存在:${code}(同仓库编码需唯一,归档分区不占用编码)`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建元素
|
||||
* @param {Object} data 元素数据
|
||||
* @param {Object} data 元素数据
|
||||
* @return {Promise<Object>} 创建的元素
|
||||
*/
|
||||
async createZone(data) {
|
||||
@ -398,6 +433,9 @@ class LocationZoneService extends Service {
|
||||
// 5. 处理编码(根据类型)
|
||||
const zoneCode = this.generateZoneCodeByType(data);
|
||||
|
||||
// 5.1 编码唯一性:同仓库未归档分区不得重复(否则会生成同编码库位,盘点按编码定位错乱)
|
||||
await this.assertZoneCodeAvailable(warehouse_id, zoneCode);
|
||||
|
||||
// 6. 创建分区
|
||||
const zone = await ctx.model.LocationZone.create({
|
||||
warehouse_id,
|
||||
@ -737,6 +775,17 @@ class LocationZoneService extends Service {
|
||||
|
||||
const updateData = { ...data };
|
||||
|
||||
// 编码变更需保证同仓库未归档分区内唯一(未变更则跳过)
|
||||
if (updateData.zone_code !== undefined && updateData.zone_code !== null) {
|
||||
const nextCode = String(updateData.zone_code).trim();
|
||||
if (nextCode && nextCode !== String(zone.zone_code || '').trim()) {
|
||||
await this.assertZoneCodeAvailable(zone.warehouse_id, nextCode, id);
|
||||
updateData.zone_code = nextCode;
|
||||
} else if (!nextCode) {
|
||||
delete updateData.zone_code;
|
||||
}
|
||||
}
|
||||
|
||||
if (data.is_active !== undefined) {
|
||||
const isActive = [ true, 1, '1', 'true' ].includes(data.is_active);
|
||||
const isInactive = [ false, 0, '0', 'false' ].includes(data.is_active);
|
||||
|
||||
@ -9,7 +9,7 @@ const ExcelJS = require('exceljs');
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/** 盘点范围类型枚举(wms_stock_check.type) */
|
||||
const STOCK_CHECK_TYPES = Object.freeze([ 'all', 'store', 'goods', 'location' ]);
|
||||
const STOCK_CHECK_TYPES = Object.freeze([ 'store', 'goods', 'location' ]);
|
||||
/** 盘点方式枚举(wms_stock_check.mode) */
|
||||
const STOCK_CHECK_MODES = Object.freeze([ 'open', 'blind' ]);
|
||||
/** 允许添加明细的主表状态 */
|
||||
@ -18,6 +18,11 @@ const ADD_DETAIL_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]);
|
||||
const STOCK_CHECK_ADD_LOCATION_DETAIL_MAX_IDS = 200;
|
||||
/** 允许盘点作业上报/完成的主表状态 */
|
||||
const REPORT_ALLOWED_STATUSES = Object.freeze([ 'approved', 'checking' ]);
|
||||
/**
|
||||
* 单次上报实盘数量上限(wms_stock_check_record.quantity 为 int(12) 有符号列,
|
||||
* 实际可存上限 2147483647;超限直接落库会抛 Out of range 变成 500)。
|
||||
*/
|
||||
const REPORT_MAX_QUANTITY = 2147483647;
|
||||
/** 允许提交审核的主表状态 */
|
||||
const SUBMIT_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]);
|
||||
/** 允许取消的主表状态 */
|
||||
@ -33,7 +38,6 @@ const VALID_SPACE_SQL = '(SELECT ls.id FROM wms_location_space ls '
|
||||
|
||||
/** 盘点范围类型中文标签 */
|
||||
const STOCK_CHECK_TYPE_LABELS = Object.freeze({
|
||||
all: '全盘',
|
||||
store: '按货主',
|
||||
goods: '按商品',
|
||||
location: '按库位',
|
||||
@ -158,7 +162,7 @@ class StockCheckService extends Service {
|
||||
id: row.id,
|
||||
check_no: row.check_no,
|
||||
title: row.title || '',
|
||||
type: row.type || 'all',
|
||||
type: row.type || 'location',
|
||||
mode: row.mode || 'open',
|
||||
store_id: row.store_id || null,
|
||||
status: row.status || 'created',
|
||||
@ -546,9 +550,9 @@ class StockCheckService extends Service {
|
||||
* @param {Object} params 创建参数。
|
||||
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
|
||||
* @param {string} [params.title] 盘点名称/主题。
|
||||
* @param {string} [params.type='all'] 盘点范围类型:all/store/goods/location。
|
||||
* @param {string} [params.type='location'] 盘点范围类型:location/store/goods。
|
||||
* @param {string} [params.mode='open'] 盘点方式:open=明盘/blind=盲盘;
|
||||
* 按库位盘点(all/location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
|
||||
* 按库位盘点(location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
|
||||
* @param {number} [params.storeId] 货主ID(按货主盘点时必填)。
|
||||
* @param {string} [params.remark] 备注。
|
||||
* 盘点日期固定为今天,前端不传。
|
||||
@ -575,7 +579,7 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError('无法获取当前仓库上下文');
|
||||
}
|
||||
|
||||
const normalizedType = type ? String(type).trim() : 'all';
|
||||
const normalizedType = type ? String(type).trim() : 'location';
|
||||
if (!STOCK_CHECK_TYPES.includes(normalizedType)) {
|
||||
throw this.createBusinessError(`盘点范围类型不合法,仅支持 ${STOCK_CHECK_TYPES.join('/')}`);
|
||||
}
|
||||
@ -584,9 +588,9 @@ class StockCheckService extends Service {
|
||||
if (!STOCK_CHECK_MODES.includes(normalizedMode)) {
|
||||
throw this.createBusinessError(`盘点方式不合法,仅支持 ${STOCK_CHECK_MODES.join('/')}`);
|
||||
}
|
||||
// 按库位盘点(all/location)一律盲盘,不管前端传入什么;
|
||||
// 按库位盘点一律盲盘,不管前端传入什么;
|
||||
// 按商品盘点(store/goods)按传入值(默认明盘)
|
||||
if (normalizedType === 'all' || normalizedType === 'location') {
|
||||
if (normalizedType === 'location') {
|
||||
normalizedMode = 'blind';
|
||||
}
|
||||
|
||||
@ -1046,10 +1050,9 @@ class StockCheckService extends Service {
|
||||
/**
|
||||
* 添加盘点明细(商品或库位,按任务盘点类型决定)。
|
||||
* 仅 created/rejected 状态允许;store/goods 类型按 stock_ids 添加商品行(商品必须属于
|
||||
* 任务货主);all/location 类型按 locations(库位编码,兼容旧调用)或 location_ids
|
||||
* 任务货主);location 类型按 locations(库位编码,兼容旧调用)或 location_ids
|
||||
* (库位ID,直接查库校验,不再解析编码)添加库位行,两者都传时 location_ids 优先、
|
||||
* locations 忽略;all 未传库位且未传库位ID时自动拉取全仓库启用库位;
|
||||
* 兼容历史任务:type=all 且已存在商品明细行(改造前创建)时继续按商品模式接受 stock_ids;
|
||||
* locations 忽略;location 未传库位且未传库位ID时自动拉取全仓库启用库位(原全盘语义);
|
||||
* 已存在的同盘点项跳过(幂等),重算主表 total_items。
|
||||
*
|
||||
* @param {Object} params 添加明细参数。
|
||||
@ -1080,26 +1083,16 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError(`当前状态(${check.status})不允许添加明细`);
|
||||
}
|
||||
|
||||
const checkType = String(check.type || 'all').trim();
|
||||
let isGoodsScope = checkType === 'store' || checkType === 'goods';
|
||||
let isLocationScope = checkType === 'all' || checkType === 'location';
|
||||
const checkType = String(check.type || 'location').trim();
|
||||
const isGoodsScope = checkType === 'store' || checkType === 'goods';
|
||||
const isLocationScope = checkType === 'location';
|
||||
if (!isGoodsScope && !isLocationScope) {
|
||||
throw this.createBusinessError(`盘点范围类型不合法(${checkType})`);
|
||||
}
|
||||
const numericStockIds = this._normalizeIdList(stockIds);
|
||||
const locationCodes = this._normalizeCodeList(locations);
|
||||
const numericLocationIds = this._normalizeIdList(locationIds);
|
||||
|
||||
// 兼容历史任务:改造前 type=all 的任务按商品添加明细(明细行 scope_type='goods')。
|
||||
// 这类任务已存在商品明细行时,继续按商品模式接受 stock_ids,避免旧调用被 400 拒绝;
|
||||
// 全新 type=all 任务(无任何商品明细行)维持新语义:按库位盘点,只能传 locations。
|
||||
if (checkType === 'all' && isLocationScope) {
|
||||
const goodsScopeCount = await ctx.model.StockCheckDetail.count({
|
||||
where: { check_id: checkId, scope_type: 'goods' },
|
||||
});
|
||||
if (goodsScopeCount > 0) {
|
||||
isGoodsScope = true;
|
||||
isLocationScope = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 按盘点类型校验入参维度(商品与库位互斥)
|
||||
if (isGoodsScope && locationCodes.length > 0) {
|
||||
throw this.createBusinessError('当前盘点类型按商品盘点,请传 stock_ids');
|
||||
@ -1143,8 +1136,9 @@ class StockCheckService extends Service {
|
||||
});
|
||||
} else {
|
||||
let codes = locationCodes;
|
||||
// 全盘:未显式传库位时自动拉取全仓库启用库位(排除无头库位:zone 必须存在且未删除)
|
||||
if (checkType === 'all' && codes.length === 0) {
|
||||
// 未显式传库位时自动拉取全仓库启用库位(原全盘语义);
|
||||
// 排除无头库位:zone 必须存在且未删除
|
||||
if (codes.length === 0) {
|
||||
const enabledSpaces = await ctx.model.LocationSpace.findAll({
|
||||
where: { warehouse_id: Number(warehouseId), is_enabled: true },
|
||||
attributes: [ 'space_code' ],
|
||||
@ -1164,9 +1158,6 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError('当前仓库没有启用库位,无法按全盘自动生成盘点范围');
|
||||
}
|
||||
}
|
||||
if (codes.length === 0) {
|
||||
throw this.createBusinessError('请至少选择一个库位');
|
||||
}
|
||||
await this._addLocationDetailRows({
|
||||
checkId,
|
||||
warehouseId,
|
||||
@ -1408,7 +1399,7 @@ class StockCheckService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成按库位盘点明细的待创建行(all/location 类型)。
|
||||
* 生成按库位盘点明细的待创建行(location 类型)。
|
||||
* 按 space_code 匹配 wms_location_space(warehouse_id + space_code),
|
||||
* 不存在的编码记入 invalidLocations;已存在同 check_id+location_code 的明细跳过(幂等)。
|
||||
*
|
||||
@ -1483,7 +1474,7 @@ class StockCheckService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成按库位盘点明细的待创建行(库位ID直查路径,all/location 类型)。
|
||||
* 生成按库位盘点明细的待创建行(库位ID直查路径,location 类型)。
|
||||
* 直接按 wms_location_space.id 查库校验(warehouse_id 仓库隔离),不经过 space_code 二次解析;
|
||||
* 查不到的 ID 记入 invalidLocationIds(不报错);库位编码为空(脏数据)或已存在
|
||||
* 同 check_id+location_code 的明细跳过(uk_check_location 唯一索引口径,幂等),
|
||||
@ -2354,14 +2345,72 @@ class StockCheckService extends Service {
|
||||
return stockRow ? matchedStockId : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按库位编码解析库位ID(仅命中分区存在且未删除的有效库位行)。
|
||||
* 同仓库同编码可能同时存在多条库位(历史重复库位、分区已删除的无头库位,
|
||||
* 唯一索引含 deleted_at 且 NULL 不去重),此处取稳定口径:
|
||||
* 优先该商品有启用库存的库位行,其次 ID 最小的有效行。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {string} locationCode 库位编码。
|
||||
* @param {number} [stockId] 商品库存ID(wms_stock_warehouse.id,用于优先命中库存所在库位)。
|
||||
* @return {Promise<number>} 库位ID,未命中返回 0。
|
||||
*/
|
||||
async _resolveLocationIdByCode(warehouseId, locationCode, stockId) {
|
||||
const { ctx } = this;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
const normalizedCode = String(locationCode || '').trim();
|
||||
if (!normalizedCode) {
|
||||
return 0;
|
||||
}
|
||||
const spaceRows = await ctx.model.LocationSpace.findAll({
|
||||
where: {
|
||||
warehouse_id: Number(warehouseId),
|
||||
space_code: normalizedCode,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
// 库位有效性:zone 必须存在且未删除(无头库位不参与匹配)
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
const candidateIds = (Array.isArray(spaceRows) ? spaceRows : [])
|
||||
.map(row => Number(row && row.id))
|
||||
.filter(id => Number.isInteger(id) && id > 0);
|
||||
if (candidateIds.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
if (candidateIds.length === 1 || !(Number(stockId) > 0)) {
|
||||
return candidateIds[0];
|
||||
}
|
||||
const storageRow = await ctx.model.Storage.findOne({
|
||||
where: {
|
||||
warehouse_id: Number(warehouseId),
|
||||
stock_id: Number(stockId),
|
||||
space_id: { [Op.in]: candidateIds },
|
||||
is_enabled: 1,
|
||||
},
|
||||
attributes: [ 'space_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const storageSpaceId = storageRow ? Number(storageRow.space_id) : 0;
|
||||
return storageSpaceId > 0 ? storageSpaceId : candidateIds[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 盘点作业上报(覆盖式)。
|
||||
* 仅 approved/checking 状态允许;商品明细行固定上报明细商品(入参商品不一致报错),
|
||||
* 库位明细行必须指定商品且商品必须属于本仓库,库位以明细库位为准(入参库位不一致报错);
|
||||
* 同明细 + 同商品 + 同库位编码重复上报时更新已有记录的
|
||||
* quantity/checker_id/checker_name/checked_at(保留原 location_id,若本次新匹配到 location_id 则回填),
|
||||
* 不再新增;未传库位归入"无库位"分组(location_code 存空串);
|
||||
* 库位编码匹配 wms_location_space.space_code 时回填 location_id;
|
||||
* 不再新增;未传库位编码时以 space_id 对应库位的编码落库;
|
||||
* **space_id 必传**(wms_location_space.id,须属于本仓库且分区有效),库位以该 ID 为准,
|
||||
* location 编码入参仅做一致性校验(不一致报 400),服务端不再按编码猜库位;
|
||||
* 主表 approved 自动转 checking;重算 checked_items / diff_items / detail_status。
|
||||
* 数据库层由唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证并发安全。
|
||||
*
|
||||
@ -2379,8 +2428,10 @@ class StockCheckService extends Service {
|
||||
* @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。
|
||||
* @param {number} params.id 盘点任务ID。
|
||||
* @param {number} params.detailId 明细ID。
|
||||
* @param {string} [params.location] 库位编码(可空;库位明细行以明细库位为准)。
|
||||
* @param {number} params.quantity 实盘数量(>=0)。
|
||||
* @param {string} [params.location] 库位编码(可选,仅做一致性校验;库位以 spaceId 为准)。
|
||||
* @param {number} params.spaceId 库位ID(wms_location_space.id,必传):必须属于本仓库且分区有效,
|
||||
* 缺失报 400「缺少库位ID(space_id)」;与 location 编码不一致或(库位明细行)与明细库位不一致同样 400。
|
||||
* @param {number} params.quantity 实盘数量(>=0 且 <= 2147483647)。
|
||||
* @param {number} [params.stockId] 商品库存ID(wms_stock_warehouse.id;库位明细行必填,或改传 barcode)。
|
||||
* @param {string} [params.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品,
|
||||
* 未命中记为未知商品)。
|
||||
@ -2395,7 +2446,7 @@ class StockCheckService extends Service {
|
||||
|
||||
/**
|
||||
* 标记库位为空(库位盘点模式专属,转调 report 的空库位标记口径)。
|
||||
* 仅任务范围为库位(type=location/all)时允许:非库位任务报 400;
|
||||
* 仅任务范围为库位(type=location)时允许:非库位任务报 400;
|
||||
* 状态仅 approved/checking;明细必须属于本任务且为库位范围行(scope_type=location)。
|
||||
* 行为与 report(is_empty=true) 完全一致:写/更新空标记记录(stock_id/barcode/item_name 为空、
|
||||
* quantity=0、is_empty=1)、清除该明细商品记录、主表 approved→checking、
|
||||
@ -2430,7 +2481,7 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError(`当前状态(${check.status})不允许盘点作业`);
|
||||
}
|
||||
const normalizedType = String(check.type || '').trim();
|
||||
if (normalizedType !== 'location' && normalizedType !== 'all') {
|
||||
if (normalizedType !== 'location') {
|
||||
throw this.createBusinessError('仅库位盘点任务支持空库位标记');
|
||||
}
|
||||
|
||||
@ -2445,11 +2496,20 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError('仅库位盘点明细支持空库位标记');
|
||||
}
|
||||
|
||||
// 转调 report 空库位标记口径(查重/互斥/汇总/日志统一)
|
||||
// 转调 report 空库位标记口径(查重/互斥/汇总/日志统一);
|
||||
// report 要求必传 space_id,这里按明细库位编码解析有效库位(明细库位可能指向无头库位)
|
||||
const resolvedSpaceId = await this._resolveLocationIdByCode(
|
||||
Number(warehouseId),
|
||||
String(detail.location_code || '').trim()
|
||||
);
|
||||
if (resolvedSpaceId <= 0) {
|
||||
throw this.createBusinessError('盘点明细库位无效(库位不存在或所属分区已删除)');
|
||||
}
|
||||
return this.report({
|
||||
warehouseId,
|
||||
id: checkId,
|
||||
detailId: detailRowId,
|
||||
spaceId: resolvedSpaceId,
|
||||
is_empty: true,
|
||||
checkerId,
|
||||
checkerName,
|
||||
@ -2462,6 +2522,7 @@ class StockCheckService extends Service {
|
||||
id,
|
||||
detailId,
|
||||
location,
|
||||
spaceId: spaceIdInput,
|
||||
quantity,
|
||||
stockId,
|
||||
barcode,
|
||||
@ -2496,6 +2557,9 @@ class StockCheckService extends Service {
|
||||
if (!normalizedIsEmpty && (!Number.isInteger(quantityValue) || quantityValue < 0)) {
|
||||
throw this.createBusinessError('实盘数量必须为不小于0的整数');
|
||||
}
|
||||
if (!normalizedIsEmpty && quantityValue > REPORT_MAX_QUANTITY) {
|
||||
throw this.createBusinessError(`实盘数量不能超过 ${REPORT_MAX_QUANTITY}`);
|
||||
}
|
||||
|
||||
const detail = await ctx.model.StockCheckDetail.findOne({
|
||||
where: { id: detailRowId, check_id: checkId, warehouse_id: Number(warehouseId) },
|
||||
@ -2518,6 +2582,36 @@ class StockCheckService extends Service {
|
||||
const inputItemName = itemName !== undefined && itemName !== null && String(itemName).trim() !== ''
|
||||
? String(itemName).trim()
|
||||
: '';
|
||||
// 必填库位ID(wms_location_space.id):必须属于本仓库且所属分区有效。
|
||||
// 不允许按编码猜库位(同仓库同编码可能有多条历史重复/无头库位),缺失即 400 由调用方补传
|
||||
const inputSpaceId = spaceIdInput !== undefined && spaceIdInput !== null && spaceIdInput !== ''
|
||||
? Number(spaceIdInput)
|
||||
: 0;
|
||||
if (!Number.isInteger(inputSpaceId) || inputSpaceId <= 0) {
|
||||
throw this.createBusinessError('缺少库位ID(space_id),请传取回数据中的 space_id');
|
||||
}
|
||||
const inputLocationRow = await ctx.model.LocationSpace.findOne({
|
||||
where: { id: inputSpaceId, warehouse_id: Number(warehouseId) },
|
||||
attributes: [ 'id', 'space_code' ],
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
raw: true,
|
||||
});
|
||||
if (!inputLocationRow) {
|
||||
throw this.createBusinessError('上报库位不存在、不属于当前仓库或所属分区已删除');
|
||||
}
|
||||
const inputLocationCode = String(inputLocationRow.space_code || '').trim();
|
||||
if (!inputLocationCode) {
|
||||
throw this.createBusinessError('上报库位的库位编码为空,无法上报');
|
||||
}
|
||||
// 入参库位编码(可选):仅做一致性校验,库位以 space_id 对应的库位行为准
|
||||
const inputLocationCodeParam = location !== undefined && location !== null && String(location).trim() !== ''
|
||||
? String(location).trim()
|
||||
: '';
|
||||
|
||||
let normalizedStockId = 0;
|
||||
let normalizedBarcode = null;
|
||||
@ -2552,39 +2646,25 @@ class StockCheckService extends Service {
|
||||
} else if (inputBarcode) {
|
||||
normalizedBarcode = inputBarcode;
|
||||
}
|
||||
// 库位编码匹配 wms_location_space.space_code 时回填 location_id;
|
||||
// 未传库位归一为空串("无库位"分组,配合 uk_detail_stock_location 唯一索引)
|
||||
locationCode = location !== undefined && location !== null && String(location).trim() !== ''
|
||||
? String(location).trim()
|
||||
: '';
|
||||
if (locationCode) {
|
||||
const space = await ctx.model.LocationSpace.findOne({
|
||||
where: {
|
||||
warehouse_id: Number(warehouseId),
|
||||
space_code: locationCode,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (space) {
|
||||
locationId = space.id;
|
||||
}
|
||||
// 库位以 space_id 对应的库位行为准(必填);location 编码仅做一致性校验
|
||||
if (inputLocationCodeParam && inputLocationCodeParam !== inputLocationCode) {
|
||||
throw this.createBusinessError('上报库位编码与库位ID不一致');
|
||||
}
|
||||
locationCode = inputLocationCode;
|
||||
locationId = Number(inputLocationRow.id);
|
||||
} else {
|
||||
// 库位行:以明细库位为准
|
||||
locationCode = String(detail.location_code || '').trim();
|
||||
if (!locationCode) {
|
||||
throw this.createBusinessError('盘点明细缺少库位信息');
|
||||
}
|
||||
const inputLocation = location !== undefined && location !== null && String(location).trim() !== ''
|
||||
? String(location).trim()
|
||||
: '';
|
||||
if (inputLocation && inputLocation !== locationCode) {
|
||||
if (inputLocationCodeParam && inputLocationCodeParam !== locationCode) {
|
||||
throw this.createBusinessError('上报库位与盘点明细库位不一致');
|
||||
}
|
||||
locationId = detail.location_id !== null && detail.location_id !== undefined
|
||||
? Number(detail.location_id)
|
||||
: null;
|
||||
if (inputLocationCode !== locationCode) {
|
||||
throw this.createBusinessError('上报库位与盘点明细库位不一致');
|
||||
}
|
||||
locationId = Number(inputLocationRow.id);
|
||||
|
||||
if (normalizedIsEmpty) {
|
||||
// 空库位标记:不要求商品,stock_id/barcode/item_name 均为空、quantity=0
|
||||
@ -2628,7 +2708,7 @@ class StockCheckService extends Service {
|
||||
|
||||
const now = new Date();
|
||||
|
||||
// 覆盖式上报:已知商品按同明细 + 同商品 + 同库位编码(未传库位为空串"无库位"分组)更新已有记录,
|
||||
// 覆盖式上报:已知商品按同明细 + 同商品 + 同库位编码(库位编码来自 space_id 对应库位)更新已有记录,
|
||||
// 依赖唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证并发安全;
|
||||
// 未知商品唯一索引不约束 NULL 行,按同明细 + 同条码 + 同库位编码在应用层查重;
|
||||
// 空库位标记按(detail_id + is_empty=1 + location_code)应用层查重覆盖更新
|
||||
@ -2761,6 +2841,8 @@ class StockCheckService extends Service {
|
||||
const summary = await this._recalcCheckSummary(checkId);
|
||||
|
||||
// 写入操作日志(失败不影响主流程)
|
||||
// message 补充库位编码/库位ID(原 message 只有明细与数量,事后无法定位是哪个库位被上报),
|
||||
// before_changes 落明细快照与本次上报字段,供追溯
|
||||
await ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'stock_check',
|
||||
businessId: checkId,
|
||||
@ -2769,6 +2851,24 @@ class StockCheckService extends Service {
|
||||
changeSummary: normalizedIsEmpty
|
||||
? `盘点作业上报:明细 ${detailRowId} 确认库位 ${locationCode || '未指定'} 为空`
|
||||
: `盘点作业上报:明细 ${detailRowId},库位 ${locationCode || '未指定'},实盘 ${quantityValue}${normalizedBarcode ? `,条码 ${normalizedBarcode}` : ''}(${mode === 'created' ? '新增' : '更新'})`,
|
||||
beforeChanges: {
|
||||
check_no: check.check_no,
|
||||
detail_id: detailRowId,
|
||||
scope_type: scopeType,
|
||||
stock_id: normalizedStockId > 0 ? normalizedStockId : null,
|
||||
location_code: locationCode || '',
|
||||
location_id: locationId !== null && locationId !== undefined ? Number(locationId) : null,
|
||||
detail_location_code: String(detail.location_code || '').trim() || null,
|
||||
detail_location_id: detail.location_id !== null && detail.location_id !== undefined
|
||||
? Number(detail.location_id)
|
||||
: null,
|
||||
quantity: quantityValue,
|
||||
barcode: normalizedBarcode,
|
||||
is_unknown_goods: isUnknownGoods,
|
||||
is_empty: normalizedIsEmpty,
|
||||
mode,
|
||||
record_id: Number(record && record.id) || null,
|
||||
},
|
||||
operator: {
|
||||
id: ctx.user?.employees_id || ctx.user?.id || '',
|
||||
name: ctx.user?.employees_name || '',
|
||||
@ -2778,14 +2878,15 @@ class StockCheckService extends Service {
|
||||
checkNo: check.check_no,
|
||||
detailId: detailRowId,
|
||||
locationCode,
|
||||
locationId: locationId !== null && locationId !== undefined ? Number(locationId) : null,
|
||||
quantity: quantityValue,
|
||||
barcode: normalizedBarcode,
|
||||
isUnknownGoods,
|
||||
is_empty: normalizedIsEmpty,
|
||||
mode,
|
||||
message: normalizedIsEmpty
|
||||
? `盘点作业上报:明细 ${detailRowId} 确认库位为空`
|
||||
: `盘点作业上报:明细 ${detailRowId} 实盘 ${quantityValue}`,
|
||||
? `盘点作业上报:明细 ${detailRowId} 确认库位 ${locationCode || '未指定'}${locationId ? `(#${locationId})` : ''} 为空`
|
||||
: `盘点作业上报:明细 ${detailRowId},库位 ${locationCode || '未指定'}${locationId ? `(#${locationId})` : ''},实盘 ${quantityValue}`,
|
||||
},
|
||||
});
|
||||
|
||||
@ -2914,7 +3015,7 @@ class StockCheckService extends Service {
|
||||
/**
|
||||
* 拉取盘点作业数据(视图由任务类型与 is_goods 驱动,view 入参已废弃忽略)。
|
||||
* 视图解析规则:
|
||||
* - 任务范围为库位(type=location/all):一律按库位视图(location)返回,无视 view/is_goods 入参;
|
||||
* - 任务范围为库位(type=location):一律按库位视图(location)返回,无视 view/is_goods 入参;
|
||||
* - 任务范围为商品(type=goods/store):默认聚合库位视图(space);仅 is_goods=true 时按商品视图(goods)返回。
|
||||
* 三视图行结构:
|
||||
* location=库位结构,以任务库位范围行(scope_type=location)为列表,
|
||||
@ -2974,7 +3075,7 @@ class StockCheckService extends Service {
|
||||
// 商品范围任务默认 space(聚合库位),仅 is_goods=true 时 goods 视图
|
||||
const normalizedType = String(check.type || '').trim();
|
||||
const goodsViewRequested = isGoods === true || isGoods === 'true' || isGoods === 1;
|
||||
const resolvedView = normalizedType === 'location' || normalizedType === 'all'
|
||||
const resolvedView = normalizedType === 'location'
|
||||
? 'location'
|
||||
: (goodsViewRequested ? 'goods' : 'space');
|
||||
|
||||
@ -3064,7 +3165,7 @@ class StockCheckService extends Service {
|
||||
|
||||
/**
|
||||
* 拉取盘点作业数据(space 视图分页版)。
|
||||
* 行结构与 workData space 视图行一致(id=库位ID/space_code/custom_barcode/custom_name/goods),
|
||||
* 行结构与 workData space 视图行一致(id=库位ID/location_id 同义库位ID/space_code/custom_barcode/custom_name/goods),
|
||||
* 商品任务(scope_type=goods)按库位聚合;传入 location_id 时只返回该库位行(total=1),
|
||||
* 不传时按分页返回全部库位行。
|
||||
*
|
||||
@ -3315,11 +3416,14 @@ class StockCheckService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
const rowLocationId = detailRow.location_id !== null && detailRow.location_id !== undefined
|
||||
? Number(detailRow.location_id)
|
||||
: null;
|
||||
return {
|
||||
detail_id: detailId,
|
||||
location_id: detailRow.location_id !== null && detailRow.location_id !== undefined
|
||||
? detailRow.location_id
|
||||
: null,
|
||||
location_id: rowLocationId,
|
||||
// space_id 为 location_id 的同义字段,供调用方直接回传 stock.check.report
|
||||
space_id: rowLocationId,
|
||||
location_code: locationCode,
|
||||
location_name: locationName,
|
||||
status: detailRecords.length > 0 ? 'checked' : 'unchecked',
|
||||
@ -3449,6 +3553,42 @@ class StockCheckService extends Service {
|
||||
}
|
||||
const spaceCodeByStockMap = new Map();
|
||||
const spaceQuantityByStockMap = new Map();
|
||||
// 库位编码 → 有效库位ID(同编码多条时取拣货顺序第一条):供 goods 视图 locations[] 回传 location_id,
|
||||
// 让调用方能直接把库位ID回传 stock.check.report(否则只有编码,服务端只能按编码猜库位)
|
||||
const spaceIdByCodeMap = new Map();
|
||||
for (const row of sortedSpaceRows) {
|
||||
const spaceCode = String(row.space_code || '').trim();
|
||||
if (spaceCode && !spaceIdByCodeMap.has(spaceCode)) {
|
||||
spaceIdByCodeMap.set(spaceCode, Number(row.id));
|
||||
}
|
||||
}
|
||||
// 已盘库位(当前库存已无该商品)补查有效库位ID,口径与 workData space 视图一致(zone 存在未删除)
|
||||
const uncoveredRecordCodes = [ ...new Set(records
|
||||
.map(record => String(record.location_code || '').trim())
|
||||
.filter(code => code && !spaceIdByCodeMap.has(code))) ];
|
||||
if (uncoveredRecordCodes.length > 0) {
|
||||
const uncoveredRows = await ctx.model.LocationSpace.findAll({
|
||||
where: {
|
||||
warehouse_id: Number(warehouseId),
|
||||
space_code: { [Op.in]: uncoveredRecordCodes },
|
||||
},
|
||||
attributes: [ 'id', 'space_code' ],
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
for (const row of uncoveredRows) {
|
||||
const spaceCode = String(row.space_code || '').trim();
|
||||
if (spaceCode && !spaceIdByCodeMap.has(spaceCode)) {
|
||||
spaceIdByCodeMap.set(spaceCode, Number(row.id));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [ stockId, spaceIds ] of stockSpaceIdsMap.entries()) {
|
||||
const spaceRowMap = new Map(sortedSpaceRows.map(row => [ Number(row.id), row ]));
|
||||
const orderedRows = spaceIds
|
||||
@ -3551,7 +3691,12 @@ class StockCheckService extends Service {
|
||||
}
|
||||
|
||||
const buildLocationItem = (code, group) => {
|
||||
const locationIdValue = (code && spaceIdByCodeMap.get(code)) || (group && group.location_id) || null;
|
||||
const locationItem = {
|
||||
// 库位ID(wms_location_space.id):优先有效库位行,其次作业记录回填值;
|
||||
// space_id 供调用方直接回传 stock.check.report(location_id 为兼容别名)
|
||||
location_id: locationIdValue,
|
||||
space_id: locationIdValue,
|
||||
location_code: code || null,
|
||||
checked_at: group ? group.checked_at : null,
|
||||
checker_name: group ? group.checker_name : null,
|
||||
@ -3596,13 +3741,15 @@ class StockCheckService extends Service {
|
||||
|
||||
/**
|
||||
* 构建 space 视图行:以任务商品(scope_type=goods 的 stock_id 集合)所在的库位为列表。
|
||||
* 库位集合取 wms_storage(warehouse_id + stock_id 在集合内 + is_enabled=1 且未删除,DISTINCT space_id),
|
||||
* 库位集合取 wms_storage(warehouse_id + stock_id 在集合内 + is_enabled=1 且未删除,DISTINCT space_id)
|
||||
* ∪ 作业记录库位(上报库位与明细库位编码一致时归并到明细固化 location_id,
|
||||
* 无头库位归并到同编码有效库位,避免同编码出现重复行),
|
||||
* 库位仅按拣货顺序排序:pick_sequence 升序(pick_priority/库位 id 不参与排序,
|
||||
* 同值保持库位查询顺序);
|
||||
* 行内 goods 为该库位下的任务商品:明盘含 system_quantity(wms_storage space+stock
|
||||
* SUM(available_quantity+locked_quantity))、locked_quantity(wms_storage space+stock SUM(locked_quantity))
|
||||
* 与 checked_quantity(该商品在该库位的实盘合计),盲盘不返回任何数量字段;
|
||||
* status 已盘口径:该 (detail_id, location_code) 存在作业记录;
|
||||
* status 已盘口径:该 (库位, 商品) 存在作业记录(兼容按明细 + 库位编码命中);
|
||||
* 未在 wms_storage 有库位的商品不入列表(无库位可聚)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
@ -3647,6 +3794,11 @@ class StockCheckService extends Service {
|
||||
.filter(storeId => Number.isInteger(storeId) && storeId > 0);
|
||||
const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId);
|
||||
const detailByStockId = new Map(detailRows.map(row => [ Number(row.stock_id), row ]));
|
||||
const detailById = new Map(detailRows.map(row => [ Number(row.id), row ]));
|
||||
// 明细按「库位 + 商品」索引:同一商品分布在多个库位时,库位行应取本库位对应的明细
|
||||
const detailByStockSpace = new Map(
|
||||
detailRows.map(row => [ `${Number(row.location_id)}_${Number(row.stock_id)}`, row ])
|
||||
);
|
||||
|
||||
// 任务商品所在库位:wms_storage(warehouse + stock_id 在集合 + 启用未删除)DISTINCT space_id,
|
||||
// 同时按 (space_id, stock_id) 汇总账面数量(口径=可用+锁定)与锁定数量
|
||||
@ -3667,12 +3819,101 @@ class StockCheckService extends Service {
|
||||
group: [ 'space_id', 'stock_id' ],
|
||||
raw: true,
|
||||
});
|
||||
// 记录库位归一:上报库位与明细库位编码一致时以明细固化库位为准,
|
||||
// 避免同仓库同编码存在多条库位(历史重复库位/无头库位)时同一编码在视图里出现两行
|
||||
const recordSpaceIdMap = new Map();
|
||||
for (const record of records) {
|
||||
const recordCode = String(record.location_code || '').trim();
|
||||
const recordDetail = detailById.get(Number(record.detail_id));
|
||||
const detailLocationCode = recordDetail ? String(recordDetail.location_code || '').trim() : '';
|
||||
const detailLocationId = recordDetail ? Number(recordDetail.location_id) || 0 : 0;
|
||||
const recordSpaceId = recordCode && detailLocationCode === recordCode && detailLocationId > 0
|
||||
? detailLocationId
|
||||
: Number(record.location_id) || 0;
|
||||
recordSpaceIdMap.set(Number(record.id), recordSpaceId);
|
||||
}
|
||||
|
||||
// 无头库位(分区不存在/已删除)不直接入视图:同仓库同编码多条库位时会出现自定义字段为空的幽灵行,
|
||||
// 统一归并到同编码的有效库位(优先该商品有启用库存的库位,其次 ID 最小)
|
||||
const recordSpaceIdList = [ ...new Set([ ...recordSpaceIdMap.values() ].filter(spaceId => spaceId > 0)) ];
|
||||
if (recordSpaceIdList.length > 0) {
|
||||
const validRecordSpaceRows = await ctx.model.LocationSpace.findAll({
|
||||
where: { id: { [Op.in]: recordSpaceIdList } },
|
||||
attributes: [ 'id' ],
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
raw: true,
|
||||
});
|
||||
const validRecordSpaceIdSet = new Set(validRecordSpaceRows.map(row => Number(row.id)));
|
||||
const invalidRecordSpaceIds = recordSpaceIdList.filter(spaceId => !validRecordSpaceIdSet.has(spaceId));
|
||||
if (invalidRecordSpaceIds.length > 0) {
|
||||
const invalidRows = await ctx.model.LocationSpace.findAll({
|
||||
where: { id: { [Op.in]: invalidRecordSpaceIds } },
|
||||
attributes: [ 'id', 'space_code' ],
|
||||
raw: true,
|
||||
});
|
||||
const invalidSpaceCodeMap = new Map(
|
||||
invalidRows.map(row => [ Number(row.id), String(row.space_code || '').trim() ])
|
||||
);
|
||||
const fallbackCodes = [ ...new Set([ ...invalidSpaceCodeMap.values() ].filter(Boolean)) ];
|
||||
const fallbackRows = fallbackCodes.length === 0 ? [] : await ctx.model.LocationSpace.findAll({
|
||||
where: {
|
||||
warehouse_id: Number(warehouseId),
|
||||
space_code: { [Op.in]: fallbackCodes },
|
||||
},
|
||||
attributes: [ 'id', 'space_code' ],
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
const fallbackIdsByCode = new Map();
|
||||
for (const row of fallbackRows) {
|
||||
const code = String(row.space_code || '').trim();
|
||||
if (!fallbackIdsByCode.has(code)) {
|
||||
fallbackIdsByCode.set(code, []);
|
||||
}
|
||||
fallbackIdsByCode.get(code).push(Number(row.id));
|
||||
}
|
||||
const storageKeySet = new Set(
|
||||
storageRows.map(row => `${Number(row.space_id)}_${Number(row.stock_id)}`)
|
||||
);
|
||||
for (const record of records) {
|
||||
const recordId = Number(record.id);
|
||||
const currentSpaceId = recordSpaceIdMap.get(recordId) || 0;
|
||||
if (!invalidRecordSpaceIds.includes(currentSpaceId)) {
|
||||
continue;
|
||||
}
|
||||
const code = invalidSpaceCodeMap.get(currentSpaceId)
|
||||
|| String(record.location_code || '').trim();
|
||||
const candidates = fallbackIdsByCode.get(code) || [];
|
||||
if (candidates.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const recordStockId = Number(record.stock_id) || 0;
|
||||
const stockHit = recordStockId > 0
|
||||
? candidates.find(spaceId => storageKeySet.has(`${spaceId}_${recordStockId}`))
|
||||
: 0;
|
||||
recordSpaceIdMap.set(recordId, stockHit || candidates[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 作业记录库位:优先已回填 location_id;未回填的按库位编码匹配 wms_location_space 补查,
|
||||
// 保证商品库存已无记录时(如盘点前库存已出空)space 视图仍能展示已盘库位行。
|
||||
// 保证商品库存已无记录时(如盘点前库存已出空)space 视图仍能展示已盘库位行
|
||||
// (编码一致时已在上面归并到明细固化库位)。
|
||||
const recordSpaceIds = [];
|
||||
const recordLocationCodes = [];
|
||||
for (const record of records) {
|
||||
const recordSpaceId = Number(record.location_id) || 0;
|
||||
const recordSpaceId = recordSpaceIdMap.get(Number(record.id)) || 0;
|
||||
if (recordSpaceId > 0) {
|
||||
if (!recordSpaceIds.includes(recordSpaceId)) {
|
||||
recordSpaceIds.push(recordSpaceId);
|
||||
@ -3759,10 +4000,12 @@ class StockCheckService extends Service {
|
||||
codeMatchedLocationRows.map(row => [ String(row.space_code || '').trim(), Number(row.id) ])
|
||||
);
|
||||
const recordsByDetailSpace = new Map();
|
||||
// 记录按「库位 + 商品」归集:跨明细上报(记录明细与库位不一致)时仍能命中对应库位行
|
||||
const recordsBySpaceStock = new Map();
|
||||
// 仅记录库位(当前库存无该商品)按库位归集记录,供 space 视图补行
|
||||
const recordsBySpace = new Map();
|
||||
for (const record of records) {
|
||||
let spaceId = Number(record.location_id) || 0;
|
||||
let spaceId = recordSpaceIdMap.get(Number(record.id)) || 0;
|
||||
if (!spaceId) {
|
||||
spaceId = codeToSpaceIdMap.get(String(record.location_code || '').trim()) || 0;
|
||||
}
|
||||
@ -3776,6 +4019,15 @@ class StockCheckService extends Service {
|
||||
}
|
||||
recordsByDetailSpace.get(detailSpaceKey).push(record);
|
||||
|
||||
const recordStockId = Number(record.stock_id) || 0;
|
||||
if (recordStockId > 0) {
|
||||
const spaceStockKey = `${spaceId}_${recordStockId}`;
|
||||
if (!recordsBySpaceStock.has(spaceStockKey)) {
|
||||
recordsBySpaceStock.set(spaceStockKey, []);
|
||||
}
|
||||
recordsBySpaceStock.get(spaceStockKey).push(record);
|
||||
}
|
||||
|
||||
if (!recordsBySpace.has(spaceId)) {
|
||||
recordsBySpace.set(spaceId, []);
|
||||
}
|
||||
@ -3800,7 +4052,7 @@ class StockCheckService extends Service {
|
||||
.sort((left, right) => Number(left.stock_id) - Number(right.stock_id))
|
||||
.map(storageRow => {
|
||||
const stockId = Number(storageRow.stock_id);
|
||||
const detailRow = detailByStockId.get(stockId);
|
||||
const detailRow = detailByStockSpace.get(`${spaceId}_${stockId}`) || detailByStockId.get(stockId);
|
||||
if (!detailRow) {
|
||||
return null;
|
||||
}
|
||||
@ -3808,7 +4060,8 @@ class StockCheckService extends Service {
|
||||
const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : [];
|
||||
const storeId = stockDetail.store_id != null ? Number(stockDetail.store_id) : null;
|
||||
const detailId = Number(detailRow.id);
|
||||
const locationRecords = recordsByDetailSpace.get(`${detailId}_${spaceId}`)
|
||||
const locationRecords = recordsBySpaceStock.get(`${spaceId}_${stockId}`)
|
||||
|| recordsByDetailSpace.get(`${detailId}_${spaceId}`)
|
||||
|| recordsByDetailLocation.get(`${detailId}_${spaceCode}`)
|
||||
|| [];
|
||||
// 作业照片与记录ID(供前端展示与编辑/移除记录)
|
||||
@ -3849,8 +4102,11 @@ class StockCheckService extends Service {
|
||||
.filter(item => item !== null);
|
||||
|
||||
return {
|
||||
// 库位字段对齐库位查询惯例(index.searchSpace:id/space_code/custom_barcode/custom_name)
|
||||
// 库位字段对齐库位查询惯例(index.searchSpace:id/space_code/custom_barcode/custom_name);
|
||||
// location_id / space_id 均为 id 的同义字段,上报 stock.check.report 时以 space_id 必传
|
||||
id: spaceId,
|
||||
location_id: spaceId,
|
||||
space_id: spaceId,
|
||||
space_code: spaceCode || null,
|
||||
custom_barcode: locationRow.custom_barcode != null && String(locationRow.custom_barcode).trim() !== ''
|
||||
? String(locationRow.custom_barcode).trim()
|
||||
@ -3982,7 +4238,7 @@ class StockCheckService extends Service {
|
||||
/**
|
||||
* 重盘清除库位(按库位清除盘点信息,库位盘点模式专属)。
|
||||
* 传入任务ID与库位ID,清除该库位范围内明细的全部作业记录(含空库位标记),
|
||||
* 该库位回到未盘状态;仅任务范围为库位(type=location/all)且状态 approved/checking 时允许;
|
||||
* 该库位回到未盘状态;仅任务范围为库位(type=location)且状态 approved/checking 时允许;
|
||||
* 删除后重算 checked_items/diff_items/detail_status,主表状态不回退;
|
||||
* 同时清理被删记录的图片引用(失败仅告警不影响主流程)。
|
||||
*
|
||||
@ -4015,7 +4271,7 @@ class StockCheckService extends Service {
|
||||
throw this.createBusinessError(`当前状态(${check.status})不允许清除库位盘点信息`);
|
||||
}
|
||||
const normalizedType = String(check.type || '').trim();
|
||||
if (normalizedType !== 'location' && normalizedType !== 'all') {
|
||||
if (normalizedType !== 'location') {
|
||||
throw this.createBusinessError('仅库位盘点任务支持重盘清除库位');
|
||||
}
|
||||
|
||||
@ -5091,10 +5347,23 @@ class StockCheckService extends Service {
|
||||
raw: true,
|
||||
});
|
||||
for (const spaceRow of spaceRows) {
|
||||
locationDisplayMap.set(String(spaceRow.space_code || '').trim(), {
|
||||
const code = String(spaceRow.space_code || '').trim();
|
||||
if (!code) {
|
||||
continue;
|
||||
}
|
||||
const candidate = {
|
||||
custom_name: String(spaceRow.custom_name || '').trim(),
|
||||
custom_barcode: String(spaceRow.custom_barcode || '').trim(),
|
||||
});
|
||||
};
|
||||
// 同仓库同编码可能有多条库位(历史重复/无头库位):优先保留有自定义名称的行,
|
||||
// 避免空值行后写覆盖,导致导出回退成库位编码
|
||||
const existing = locationDisplayMap.get(code);
|
||||
const shouldReplace = !existing
|
||||
|| (!existing.custom_name && candidate.custom_name)
|
||||
|| (!existing.custom_name && !candidate.custom_name && candidate.custom_barcode);
|
||||
if (shouldReplace) {
|
||||
locationDisplayMap.set(code, candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,4 +1,73 @@
|
||||
[
|
||||
{
|
||||
"version": "0.3.308",
|
||||
"date": "2026-10-27",
|
||||
"type": "updated",
|
||||
"summary": "库存盘点移除范围类型 all(与 location 语义重复):全盘能力(未传库位时自动拉取全仓库启用库位)并入 location,type 缺省值改为 location,create 传 all 返回 400;存量 type=all 任务由迁移收敛(商品行任务改 goods、库位行/空任务改 location 并归一盲盘)。",
|
||||
"methods": [
|
||||
"stock.check.create",
|
||||
"stock.check.list",
|
||||
"stock.check.addDetail",
|
||||
"stock.check.workData",
|
||||
"stock.check.markEmpty",
|
||||
"stock.check.recheckClearLocation"
|
||||
],
|
||||
"notes": [
|
||||
"动机:type=all 与 type=location 语义完全重复——两者都按库位盘点、明细都是 scope_type=location、mode 都被强制 blind;all 唯一的额外能力「添加明细时未传库位自动拉取全仓库启用库位」已合并进 location,all 因此下线。",
|
||||
"create:type 仅允许 store/goods/location,缺省由 all 改为 location;传 all 返回 400「盘点范围类型不合法,仅支持 store/goods/location」。mode 规则不变——location 一律盲盘(忽略传入),store/goods 按传入值(缺省明盘)。",
|
||||
"addDetail:type=location 未传 locations 且未传 location_ids 时自动拉取当前仓库全部启用且有效库位(排除无头库位)生成库位行(原 all 全盘语义);type=all 的历史任务不再走「已有商品明细行则按商品模式」兼容分支,直接返回 400「盘点范围类型不合法(all)」。",
|
||||
"存量数据:database/migrations/20261027010000-merge-stock-check-type-all-into-location.js 将明细含商品行(scope_type=goods,2026-09-30 改造前的全仓按商品口径)的 type=all 任务改为 type=goods(mode 保持原值),其余(明细为库位行或无明细的空任务)改为 type=location 并归一 mode=blind;wms_stock_check.type 列默认值改为 location、注释去掉 all。",
|
||||
"影响面:前端传 type=all 的创建调用将收到 400,需改为 location(需要全盘时创建 location 任务后调用 addDetail 不传库位即可)。workData/markEmpty/recheckClearLocation 等按库位判定的接口仍只认 type=location(历史 all 任务经迁移后即为 location)。",
|
||||
"测试:test/app/service/systems/stock_check.test.js 改为 location 口径——新增「type=all 创建报 400」「历史 type=all 任务添加明细报 400」用例;原「type=all 缺省库位自动全仓」用例改由 type=location 承接;移除 type=all 历史商品明细兼容用例。",
|
||||
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create/list/addDetail/workData/markEmpty/recheckClearLocation(type 语义、mode 规则、全盘自动范围、错误文案);根版本 0.3.307 → 0.3.308、updatedAt 2026-10-27;methods/changes/system.json 新增本条(插入数组首位);未改动其它分组。",
|
||||
"破坏性提示:type=all 不再是合法入参(400);依赖「all 缺省自动全仓」的调用改为 location 即可,行为一致。",
|
||||
"代码依据:app/service/systems/stock_check.js#create/#addDetail/#workData/#markEmpty/#recheckClearLocation、app/service/systemMethods/stock/check.js、app/model/stock_check.js、database/migrations/20261027010000-merge-stock-check-type-all-into-location.js。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.307",
|
||||
"date": "2026-10-25",
|
||||
"type": "updated",
|
||||
"summary": "库存盘点上报(stock.check.report)改为 space_id 必传:库位一律按库位ID落库、不再按编码猜库位(修复同仓库同编码重复库位导致作业记录挂到无头脏库位);实盘数量上限 2147483647 返回 400;取回接口补充 space_id/location_id 字段供回传;操作日志 message/before_changes 补充库位编码与库位ID。",
|
||||
"methods": [
|
||||
"stock.check.report",
|
||||
"stock.check.workData"
|
||||
],
|
||||
"notes": [
|
||||
"问题现象:生产盘点单 PD20261025000001 的 stock.check.workData space 视图出现 custom_name/custom_barcode 为 null 的库位行(如 E02-06-01-01)。根因:wms_location_space 存在大量同仓库同编码重复库位(uk_warehouse_space_code 含 deleted_at,NULL 不去重导致重复插入不受约束),其中大量库位所属 zone 已删除(无头库位);report 旧逻辑只按 warehouse_id + space_code 做 findOne,命中最小的历史行,导致作业记录挂到脏库位,space 视图再按记录库位补行时又未做分区有效性过滤。",
|
||||
"取回侧字段(本次补齐):workData/workDataSpaceDetails 的 space 视图行新增 space_id 与 location_id(与既有 id 同值);goods 视图 locations[] 新增 space_id 与 location_id(取分区有效库位行,同编码多条取拣货顺序第一条,已盘但无库存的库位按编码补查有效库位)。location 视图/recordList/result 的 location_id 保持不变。",
|
||||
"report 写库(本次修正为强制):space_id 必传(兼容 spaceId/location_id/locationId 写法,取回接口 rows[].space_id、rows[].id、locations[].space_id 可直接回传);服务端校验属于本仓库且 zone 存在未删除,缺失/非法返回 400「缺少库位ID(space_id)」,不存在/跨仓库/分区已删除返回 400;库位编码以 space_id 对应库位行为准,location 入参降级为可选一致性校验(不一致 400),服务端不再按编码匹配/猜库位;库位明细行还要求 space_id 对应编码等于明细库位编码。",
|
||||
"report 校验:实盘数量新增上限 2147483647(wms_stock_check_record.quantity 为 int(12)),超限返回 400「实盘数量不能超过 2147483647」;此前超限直接落库抛 Out of range 变 500(生产今日 10 次)。",
|
||||
"workData space 视图:记录库位归一(上报编码与明细编码一致归并到明细固化 location_id;记录指向无头库位时归并到同编码有效库位),库位商品明细改按「库位+商品」索引、作业记录改按「库位+商品」聚合,避免跨库位上报时同一编码出现两行或实盘数落到别的行。",
|
||||
"操作日志:STOCK_CHECK_REPORT 的 message 追加库位编码与库位ID;before_changes 落 check_no/detail_id/scope_type/stock_id/location_code/location_id/detail_location_code/detail_location_id/quantity/barcode/is_unknown_goods/is_empty/mode/record_id 快照(原 changeSummary 参数在 operationLog.buildOperationLogData 中未落库,日志里查不到库位信息)。",
|
||||
"问题定位依据(只读核查):生产 wms-api.log 中 244 条 stock.check.report 请求 body 键仅 id/detail_id/quantity/location/stock_id,无 space_id;detail 6151 于 2026-10-25 22:55:36 上报 location=E02-06-01-01(明细库位为 E02-06-02-01),落库 location_id=13768(zone 59 已删除);有效行为 22093(E1区02-06-01/00224214)。",
|
||||
"测试:test/app/service/systems/stock_check.test.js 升级为 space_id 必传口径——新增/改写用例覆盖「同编码重复库位不产生幽灵行」「space_id 必传与缺失/非法/跨仓库/无头/编码不一致 400」「数量超限 400 且不落库」「操作日志含库位信息」「space 视图行 space_id=id」「goods 视图 locations[] 含 space_id」,全量 244 通过。",
|
||||
"文档变更范围:methods/system.json 的 stock.check.report(space_id 必填参数、location 降级为一致性校验、quantity 上限)、stock.check.workData / stock.check.workDataSpaceDetails(space 视图行含 id/space_id/location_id、goods locations[] 含 space_id)+根版本 0.3.306 → 0.3.307、updatedAt 2026-10-25;methods/changes/system.json 新增本条(插入数组首位)。",
|
||||
"破坏性提示:旧调用方(未传 space_id)将收到 400「缺少库位ID(space_id)」,前端需改为回传取回接口返回的 space_id;「无库位上报」通道随之取消(历史 location_code='' 记录仍按既有口径展示/导出为空)。",
|
||||
"代码依据:app/service/systems/stock_check.js#_resolveLocationIdByCode/#report/#_buildSpaceWorkRows、app/service/systemMethods/stock/check.js#report。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.306",
|
||||
"date": "2026-10-25",
|
||||
"type": "added",
|
||||
"summary": "用户账号能力增强:user.getAccountInfo 返回新增 is_custom_password;新增 user.updateUsername(服务端重名校验并排除自己)与 user.changePassword(首次自定义密码可免旧密码,修改后置 is_custom_password=1,再次修改必须校验旧密码)。",
|
||||
"methods": [
|
||||
"user.getAccountInfo",
|
||||
"user.updateUsername",
|
||||
"user.changePassword"
|
||||
],
|
||||
"notes": [
|
||||
"user.getAccountInfo:返回字段白名单新增 is_custom_password(是否自定义密码:0-否,1-是),仍不返回 password_hash、salt、last_login_ip。",
|
||||
"user.updateUsername:新增方法,仅修改当前登录账号;username 必填,长度3-50且仅允许字母/数字/下划线;服务端查询 username 重名时排除自己(id != 当前账号),重名返回 409;用户名未变化直接返回成功;更新后清理用户缓存,并同步当前请求上下文 username。",
|
||||
"user.changePassword:新增方法,入参 new_password 必填(兼容 newPassword),old_password 兼容 oldPassword;is_custom_password=0 时旧密码可不传,is_custom_password=1 时必须传且校验通过;修改时重新生成 salt 与 password_hash,并将 is_custom_password 置为1;方法已加入 _noNeedLog,避免请求体中的明文密码写入操作日志。",
|
||||
"错误码:updateUsername 400(参数/格式)/401(未登录)/404(账号不存在)/409(用户名已存在);changePassword 400(新密码为空、请输入旧密码、旧密码错误)/401/404;数据库异常返回 code=0。",
|
||||
"数据库:依赖迁移 20261025135000-add-is-custom-password-to-wms-account.js(wms_account.is_custom_password TINYINT(1) NOT NULL DEFAULT 0),开发库与生产库均已执行。",
|
||||
"测试:test/app/service/systemMethods/user.getAccountInfo.test.js(5)、user.updateUsername.test.js(7)、user.changePassword.test.js(8),合计 20 通过。",
|
||||
"文档变更范围:methods/system.json 的 user.getAccountInfo(response 新增 is_custom_password)、user.updateUsername(新增)、user.changePassword(新增)+根版本 0.3.305 → 0.3.306、updatedAt 2026-10-25;方法文档已写入开发库 wms_api_method_doc 并重新导出;methods/changes/system.json 新增本条(插入数组首位)。",
|
||||
"代码依据:app/service/systemMethods/user.js#updateUsername/#changePassword、app/service/systems/auth/user.js#updateUsername/#changePassword、app/service/systems/auth/user.js#getAccountInfo。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.3.305",
|
||||
"date": "2026-10-25",
|
||||
@ -12486,5 +12555,23 @@
|
||||
"测试:test/app/service/systemMethods/order/wave.wavePickTaskList.test.js 补充 cart_code 操作符/默认模糊/顶层优先/keyword 覆盖用例,并修复原 mock 缺失 QueryTypes.SELECT 导致的既有用例失败。"
|
||||
],
|
||||
"module": "order"
|
||||
},
|
||||
{
|
||||
"version": "2026.10.26-index.getShopExpressList-productTypes",
|
||||
"date": "2026-10-26",
|
||||
"type": "updated",
|
||||
"summary": "index.getShopExpressList 返回的 list 每项新增 product_types 字段:[{ name, code }],按 sys_express_code 匹配 wms_express_product_type 得到,未匹配时为空数组;PDD 平台不补充该字段。",
|
||||
"methods": [
|
||||
"index.getShopExpressList"
|
||||
],
|
||||
"notes": [
|
||||
"适用范围:仅 PDD 以外的平台(CAINIAO/DY/KS/SPH/XHS/JD 等)补充 product_types,PDD 平台保持原有返回结构不变。",
|
||||
"匹配规则:list 项 sys_express_code 与 wms_express_product_type.express_code 比较(trim + 大写,不区分大小写),同一 express_code 下按 code 去重;name 为空时回退为 code。",
|
||||
"数据来源与缓存:复用系统快递服务 getExpressProductTypeList 的全量缓存(缓存键 express:product-type:list,TTL 1 小时),缓存失效由 upsertExpressProductTypeList 在新增/更新产品类型后清理,接口不再额外直连数据库。",
|
||||
"容错:产品类型读取异常时仅记录 warn 日志,list 各项目 product_types 返回空数组,不影响电子面单签约列表主流程。",
|
||||
"JD 平台在 sys_express_code 补偿映射完成后再补充 product_types,与最终返回的 sys_express_code 一致。",
|
||||
"代码变更:app/service/systemMethods/index.js 新增 buildExpressProductTypeMap 与 attachExpressProductTypes,getShopExpressList 在返回前按平台补充字段(PDD 跳过、不读取产品类型缓存);methods/system.json 同步 data.list 说明与 product_types 子字段文档。"
|
||||
],
|
||||
"module": "index"
|
||||
}
|
||||
]
|
||||
|
||||
File diff suppressed because one or more lines are too long
329
script/stock-check-location-consistency.cjs
Normal file
329
script/stock-check-location-consistency.cjs
Normal file
@ -0,0 +1,329 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 盘点库位一致性体检 / 订正脚本(wms_location_space 同编码重复 + 作业记录库位错挂)。
|
||||
*
|
||||
* 背景:uk_warehouse_space_code 为 (warehouse_id, space_code, deleted_at),MySQL 唯一索引不对
|
||||
* NULL 去重,同编码可重复插入;分区删除后库位行未被软删 → 出现「无头库位」(zone 不存在/已删除)
|
||||
* 与同编码多条并存。历史 stock.check.report 只按编码 findOne 猜库位,作业记录会挂到这些旧行上,
|
||||
* 导致 stock.check.workData space 视图出现 custom_name 为 null 的幽灵行。
|
||||
*
|
||||
* 用法:
|
||||
* node script/stock-check-location-consistency.cjs # 开发库体检(只读)
|
||||
* node script/stock-check-location-consistency.cjs --prod # 生产库体检(只读)
|
||||
* node script/stock-check-location-consistency.cjs --prod --apply-record # 订正作业记录 location_id
|
||||
* node script/stock-check-location-consistency.cjs --prod --sql-out=temp/fix-location.sql # 输出清理 SQL(不执行)
|
||||
*
|
||||
* 说明:
|
||||
* 1. 默认只读;只有显式 --apply-record 才写库,且仅处理「记录库位编码 == 明细库位编码」且
|
||||
* 明细库位分区有效的安全场景(跨库位上报需人工确认,只统计不修改)。
|
||||
* 2. 无头库位清理不直接执行:--sql-out 生成 SQL 文件(含引用计数过滤),人工审核后再跑。
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const PROJECT_ROOT = path.resolve(__dirname, '..');
|
||||
|
||||
/**
|
||||
* 解析命令行参数。
|
||||
* @return {Object} 选项。
|
||||
*/
|
||||
function parseArgs() {
|
||||
const args = process.argv.slice(2);
|
||||
const options = {
|
||||
prod: false,
|
||||
applyRecord: false,
|
||||
sqlOut: '',
|
||||
config: '',
|
||||
};
|
||||
for (const arg of args) {
|
||||
if (arg === '--prod') {
|
||||
options.prod = true;
|
||||
} else if (arg === '--apply-record') {
|
||||
options.applyRecord = true;
|
||||
} else if (arg.startsWith('--sql-out=')) {
|
||||
options.sqlOut = arg.slice('--sql-out='.length);
|
||||
} else if (arg.startsWith('--config=')) {
|
||||
options.config = arg.slice('--config='.length);
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取数据库连接配置。
|
||||
* @param {Object} options 命令行选项。
|
||||
* @return {Object} mysql2 连接参数。
|
||||
*/
|
||||
function resolveClient(options) {
|
||||
const configPath = options.config
|
||||
? path.resolve(PROJECT_ROOT, options.config)
|
||||
: path.resolve(PROJECT_ROOT, options.prod ? 'script/db-query-prod-config.js' : 'config/config.local.js');
|
||||
// eslint-disable-next-line global-require
|
||||
const configFactory = require(configPath);
|
||||
const config = typeof configFactory === 'function' ? configFactory({ name: 'wms-script' }) : configFactory;
|
||||
const client = config && config.mysql && config.mysql.clients && config.mysql.clients.wms;
|
||||
if (!client) {
|
||||
throw new Error(`未在 ${configPath} 找到 mysql.clients.wms 配置`);
|
||||
}
|
||||
return {
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: client.charset || 'utf8mb4',
|
||||
connectTimeout: 20000,
|
||||
enableKeepAlive: true,
|
||||
};
|
||||
}
|
||||
|
||||
/** 引用库位ID的业务表(列名 → 表名),用于判断无头库位是否仍被引用 */
|
||||
const SPACE_REFERENCE_COLUMNS = [
|
||||
[ 'wms_storage', 'space_id' ],
|
||||
[ 'wms_picking', 'space_id' ],
|
||||
[ 'wms_receiving_detail', 'space_id' ],
|
||||
[ 'wms_storage_transaction', 'space_id' ],
|
||||
[ 'wms_inbound_direct_log', 'space_id' ],
|
||||
[ 'wms_stock_check_detail', 'location_id' ],
|
||||
[ 'wms_stock_check_record', 'location_id' ],
|
||||
];
|
||||
|
||||
/** 分批查询的批大小(避免 IN 列表过长 / 单条大查询超时) */
|
||||
const IN_CHUNK_SIZE = 500;
|
||||
|
||||
/**
|
||||
* 数组分块。
|
||||
* @param {Array} list 源数组。
|
||||
* @param {number} size 每块大小。
|
||||
* @return {Array<Array>} 分块结果。
|
||||
*/
|
||||
function chunk(list, size) {
|
||||
const result = [];
|
||||
for (let i = 0; i < list.length; i += size) {
|
||||
result.push(list.slice(i, i + size));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 有效库位判定 SQL(分区存在且未删除) */
|
||||
const VALID_SPACE_SQL = '(SELECT ls.id FROM wms_location_space ls '
|
||||
+ 'JOIN wms_location_zone z ON z.id = ls.zone_id AND z.deleted_at IS NULL '
|
||||
+ 'WHERE ls.deleted_at IS NULL)';
|
||||
|
||||
/**
|
||||
* 记录当前库位不可用判定(为空 / 行不存在 / 已归档 / 所属分区不存在或已删除)。
|
||||
* 订正只允许改动这类「坏记录」,已经是有效库位的记录一律不动。
|
||||
*/
|
||||
const BROKEN_RECORD_LOCATION_SQL = '(r.location_id IS NULL OR NOT EXISTS ('
|
||||
+ 'SELECT 1 FROM wms_location_space cur '
|
||||
+ 'JOIN wms_location_zone cz ON cz.id = cur.zone_id AND cz.deleted_at IS NULL '
|
||||
+ 'WHERE cur.id = r.location_id AND cur.deleted_at IS NULL))';
|
||||
|
||||
/** 同编码订正目标表达式(明细固化库位,且分区有效) */
|
||||
const SAME_CODE_TARGET_JOIN = 'JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id '
|
||||
+ 'JOIN wms_location_space good ON good.id = d.location_id AND good.deleted_at IS NULL '
|
||||
+ 'JOIN wms_location_zone gz ON gz.id = good.zone_id AND gz.deleted_at IS NULL';
|
||||
|
||||
/** 跨编码订正目标(同仓库同编码、分区有效,取 id 最小);同时 JOIN 明细用于排除「编码本就等于明细编码」的记录 */
|
||||
const CROSS_CODE_TARGET_JOIN = 'JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id '
|
||||
+ 'JOIN ('
|
||||
+ 'SELECT ls.warehouse_id, ls.space_code, MIN(ls.id) target_id FROM wms_location_space ls '
|
||||
+ 'JOIN wms_location_zone z ON z.id = ls.zone_id AND z.deleted_at IS NULL '
|
||||
+ 'WHERE ls.deleted_at IS NULL GROUP BY ls.warehouse_id, ls.space_code'
|
||||
+ ') t ON t.warehouse_id = r.warehouse_id AND t.space_code = r.location_code';
|
||||
|
||||
/**
|
||||
* 主流程。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function main() {
|
||||
const options = parseArgs();
|
||||
// eslint-disable-next-line global-require
|
||||
const mysql = require(path.join(PROJECT_ROOT, 'node_modules/mysql2/promise'));
|
||||
const client = resolveClient(options);
|
||||
const connection = await mysql.createConnection(client);
|
||||
const summary = { target: `${client.host}:${client.port}/${client.database}`, applyRecord: options.applyRecord };
|
||||
|
||||
try {
|
||||
const [ warehouses ] = await connection.query(
|
||||
'SELECT warehouse_id, COUNT(*) space_cnt FROM wms_location_space WHERE deleted_at IS NULL GROUP BY warehouse_id'
|
||||
);
|
||||
summary.warehouseCount = warehouses.length;
|
||||
|
||||
// 1) 无头库位(分区不存在/已删除)ID 列表与总数
|
||||
const [ headlessIdRows ] = await connection.query(
|
||||
`SELECT ls.id FROM wms_location_space ls
|
||||
WHERE ls.deleted_at IS NULL AND ls.id NOT IN ${VALID_SPACE_SQL}`
|
||||
);
|
||||
const headlessIds = headlessIdRows.map(row => Number(row.id)).filter(id => id > 0);
|
||||
const headlessIdSet = new Set(headlessIds);
|
||||
summary.headlessSpaceCount = headlessIds.length;
|
||||
|
||||
// 2) 同编码重复分组
|
||||
const [ dupRows ] = await connection.query(
|
||||
`SELECT COUNT(*) group_cnt, COALESCE(SUM(c), 0) rows_in_dup FROM (
|
||||
SELECT warehouse_id, space_code, COUNT(*) c FROM wms_location_space
|
||||
WHERE deleted_at IS NULL GROUP BY warehouse_id, space_code HAVING COUNT(*) > 1
|
||||
) t`
|
||||
);
|
||||
summary.duplicateCodeGroups = Number(dupRows[0].group_cnt) || 0;
|
||||
summary.rowsInDuplicateGroups = Number(dupRows[0].rows_in_dup) || 0;
|
||||
|
||||
// 3) 作业记录库位错挂统计(记录库位编码 == 明细库位编码,但 location_id 不同)
|
||||
const [ sameCodeRows ] = await connection.query(
|
||||
`SELECT COUNT(*) cnt,
|
||||
SUM(CASE WHEN good.id IS NOT NULL THEN 1 ELSE 0 END) fixable
|
||||
FROM wms_stock_check_record r
|
||||
JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id
|
||||
LEFT JOIN wms_location_space good ON good.id = d.location_id AND good.deleted_at IS NULL
|
||||
WHERE r.location_code = d.location_code
|
||||
AND (r.location_id IS NULL OR r.location_id <> d.location_id)`
|
||||
);
|
||||
summary.sameCodeMismatchRecords = Number(sameCodeRows[0].cnt) || 0;
|
||||
summary.sameCodeFixable = Number(sameCodeRows[0].fixable) || 0;
|
||||
|
||||
// 4) 跨库位上报(记录编码 != 明细编码)——需人工确认,不自动改
|
||||
const [ crossCodeRows ] = await connection.query(
|
||||
`SELECT COUNT(*) cnt FROM wms_stock_check_record r
|
||||
JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id
|
||||
WHERE r.location_code <> d.location_code`
|
||||
);
|
||||
summary.crossCodeRecords = Number(crossCodeRows[0].cnt) || 0;
|
||||
|
||||
// 5) 无头库位中「无任何引用」的候选清理数:先取无头库位 id(小集合),再按表分批 IN 查引用,
|
||||
// 避免在 wms_storage_transaction / wms_inbound_direct_log 等大表上做相关 NOT EXISTS 导致超时
|
||||
const referencedHeadlessIds = new Set();
|
||||
for (const [ table, column ] of SPACE_REFERENCE_COLUMNS) {
|
||||
for (const ids of chunk(headlessIds, IN_CHUNK_SIZE)) {
|
||||
const [ refRows ] = await connection.query(
|
||||
`SELECT DISTINCT ${column} AS id FROM ${table} WHERE ${column} IN (?)`,
|
||||
[ ids ]
|
||||
);
|
||||
for (const refRow of refRows) {
|
||||
const refId = Number(refRow.id);
|
||||
if (headlessIdSet.has(refId)) {
|
||||
referencedHeadlessIds.add(refId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
summary.headlessReferencedCount = referencedHeadlessIds.size;
|
||||
summary.headlessOrphanCount = headlessIds.length - referencedHeadlessIds.size;
|
||||
|
||||
// 6) 需人工处理的重复编码 Top 10(按行数)
|
||||
const [ topDup ] = await connection.query(
|
||||
`SELECT warehouse_id, space_code, COUNT(*) c FROM wms_location_space
|
||||
WHERE deleted_at IS NULL GROUP BY warehouse_id, space_code HAVING COUNT(*) > 1
|
||||
ORDER BY c DESC, space_code ASC LIMIT 10`
|
||||
);
|
||||
summary.topDuplicates = topDup.map(row => ({
|
||||
warehouse_id: Number(row.warehouse_id),
|
||||
space_code: row.space_code,
|
||||
rows: Number(row.c),
|
||||
}));
|
||||
|
||||
// 7) 订正作业记录 location_id(仅安全场景,默认只读):
|
||||
// a. 记录编码 == 明细编码 → 改挂明细固化库位(分区有效)
|
||||
// b. 记录编码 != 明细编码(跨库位上报)→ 改挂「同仓库同编码、分区有效」的库位行(取 id 最小)
|
||||
// 两条都只处理当前 location_id 不可用的坏记录(为空/不存在/已归档/分区已删),已经有效的记录不动
|
||||
const [ drySameCode ] = await connection.query(
|
||||
`SELECT COUNT(*) cnt FROM wms_stock_check_record r ${SAME_CODE_TARGET_JOIN}
|
||||
WHERE r.location_code = d.location_code AND r.location_id <> d.location_id
|
||||
AND ${BROKEN_RECORD_LOCATION_SQL}`
|
||||
);
|
||||
const [ dryCrossCode ] = await connection.query(
|
||||
`SELECT COUNT(*) cnt FROM wms_stock_check_record r ${CROSS_CODE_TARGET_JOIN}
|
||||
WHERE r.location_code <> d.location_code
|
||||
AND r.location_id <> t.target_id AND ${BROKEN_RECORD_LOCATION_SQL}`
|
||||
);
|
||||
summary.wouldUpdateSameCode = Number(drySameCode[0].cnt) || 0;
|
||||
summary.wouldUpdateCrossCode = Number(dryCrossCode[0].cnt) || 0;
|
||||
|
||||
if (options.applyRecord) {
|
||||
const [ sameCodeResult ] = await connection.query(
|
||||
`UPDATE wms_stock_check_record r ${SAME_CODE_TARGET_JOIN}
|
||||
SET r.location_id = d.location_id
|
||||
WHERE r.location_code = d.location_code
|
||||
AND r.location_id <> d.location_id
|
||||
AND ${BROKEN_RECORD_LOCATION_SQL}`
|
||||
);
|
||||
const [ crossCodeResult ] = await connection.query(
|
||||
`UPDATE wms_stock_check_record r ${CROSS_CODE_TARGET_JOIN}
|
||||
SET r.location_id = t.target_id
|
||||
WHERE r.location_code <> d.location_code
|
||||
AND r.location_id <> t.target_id
|
||||
AND ${BROKEN_RECORD_LOCATION_SQL}`
|
||||
);
|
||||
summary.updatedRecords = (Number(sameCodeResult.affectedRows) || 0)
|
||||
+ (Number(crossCodeResult.affectedRows) || 0);
|
||||
summary.updatedRecordsSameCode = Number(sameCodeResult.affectedRows) || 0;
|
||||
summary.updatedRecordsCrossCode = Number(crossCodeResult.affectedRows) || 0;
|
||||
}
|
||||
|
||||
// 8) 生成无头库位清理 SQL(不执行)
|
||||
if (options.sqlOut) {
|
||||
const outPath = path.resolve(PROJECT_ROOT, options.sqlOut);
|
||||
const sql = [
|
||||
'-- 由 script/stock-check-location-consistency.cjs 生成,请人工审核后执行',
|
||||
`-- target: ${summary.target}`,
|
||||
'-- 1) 盘点作业记录 location_id 订正(只改当前库位不可用的坏记录:为空/不存在/已归档/分区已删)',
|
||||
'-- 1.1 记录编码 == 明细编码 → 改挂明细固化库位(要求明细库位分区有效)',
|
||||
'UPDATE wms_stock_check_record r',
|
||||
' JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id',
|
||||
' JOIN wms_location_space good ON good.id = d.location_id AND good.deleted_at IS NULL',
|
||||
' JOIN wms_location_zone gz ON gz.id = good.zone_id AND gz.deleted_at IS NULL',
|
||||
' SET r.location_id = d.location_id',
|
||||
' WHERE r.location_code = d.location_code',
|
||||
' AND r.location_id <> d.location_id',
|
||||
` AND ${BROKEN_RECORD_LOCATION_SQL.replace(/\n/g, ' ')};`,
|
||||
'',
|
||||
'-- 1.2 跨库位上报(记录编码 != 明细编码)→ 改挂同仓库同编码、分区有效的库位行(取 id 最小)',
|
||||
'UPDATE wms_stock_check_record r',
|
||||
' JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id',
|
||||
' JOIN (',
|
||||
' SELECT ls.warehouse_id, ls.space_code, MIN(ls.id) target_id',
|
||||
' FROM wms_location_space ls',
|
||||
' JOIN wms_location_zone z ON z.id = ls.zone_id AND z.deleted_at IS NULL',
|
||||
' WHERE ls.deleted_at IS NULL',
|
||||
' GROUP BY ls.warehouse_id, ls.space_code',
|
||||
' ) t ON t.warehouse_id = r.warehouse_id AND t.space_code = r.location_code',
|
||||
' SET r.location_id = t.target_id',
|
||||
' WHERE r.location_code <> d.location_code',
|
||||
' AND r.location_id <> t.target_id',
|
||||
` AND ${BROKEN_RECORD_LOCATION_SQL.replace(/\n/g, ' ')};`,
|
||||
'',
|
||||
'-- 2) 无头库位软删除(仅无任何业务引用的孤行;有引用的需人工合并到有效库位)',
|
||||
'UPDATE wms_location_space ls',
|
||||
' SET ls.deleted_at = NOW()',
|
||||
' WHERE ls.deleted_at IS NULL',
|
||||
` AND ls.id NOT IN ${VALID_SPACE_SQL}`,
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_storage s WHERE s.space_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_picking p WHERE p.space_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_receiving_detail rd WHERE rd.space_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_storage_transaction st WHERE st.space_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log il WHERE il.space_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_stock_check_detail d WHERE d.location_id = ls.id)',
|
||||
' AND NOT EXISTS (SELECT 1 FROM wms_stock_check_record r WHERE r.location_id = ls.id);',
|
||||
'',
|
||||
'-- 3) 清理后复查:仍重复的编码(需人工决定保留哪一行)',
|
||||
'SELECT warehouse_id, space_code, COUNT(*) c FROM wms_location_space',
|
||||
' WHERE deleted_at IS NULL GROUP BY warehouse_id, space_code HAVING COUNT(*) > 1;',
|
||||
'',
|
||||
].join('\n');
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, sql, 'utf8');
|
||||
summary.sqlOut = outPath;
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error('[stock-check-location-consistency] 执行失败:', error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
223
script/stock-check-record-deleted-location.cjs
Normal file
223
script/stock-check-record-deleted-location.cjs
Normal file
@ -0,0 +1,223 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 盘点作业记录「库位指向异常」体检(只读)。
|
||||
*
|
||||
* 输出三类异常,均以 wms_stock_check_record.location_id 为准:
|
||||
* A 已归档库位:location_id 命中 wms_location_space 且 deleted_at IS NOT NULL(软删除/归档行)
|
||||
* B 无头库位:库位未归档,但所属 zone 不存在或已删除(分区被删后库位行漏归档)
|
||||
* C 悬空库位:location_id 在 wms_location_space 中查不到(行已被物理删除)
|
||||
*
|
||||
* 用法:
|
||||
* node script/stock-check-record-deleted-location.cjs # 开发库(只读)
|
||||
* node script/stock-check-record-deleted-location.cjs --prod # 生产库(只读)
|
||||
* node script/stock-check-record-deleted-location.cjs --prod --limit=30 --top=30
|
||||
* node script/stock-check-record-deleted-location.cjs --prod --csv-out=temp/records.csv
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const PROJECT_ROOT = path.resolve(__dirname, '..');
|
||||
|
||||
/**
|
||||
* 解析命令行参数。
|
||||
* @return {Object} 选项。
|
||||
*/
|
||||
function parseArgs() {
|
||||
const args = process.argv.slice(2);
|
||||
const options = { prod: false, limit: 20, top: 20, csvOut: '', config: '' };
|
||||
for (const arg of args) {
|
||||
if (arg === '--prod') {
|
||||
options.prod = true;
|
||||
} else if (arg.startsWith('--limit=')) {
|
||||
options.limit = Math.max(1, Number(arg.slice('--limit='.length)) || 20);
|
||||
} else if (arg.startsWith('--top=')) {
|
||||
options.top = Math.max(1, Number(arg.slice('--top='.length)) || 20);
|
||||
} else if (arg.startsWith('--csv-out=')) {
|
||||
options.csvOut = arg.slice('--csv-out='.length);
|
||||
} else if (arg.startsWith('--config=')) {
|
||||
options.config = arg.slice('--config='.length);
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取数据库连接配置。
|
||||
* @param {Object} options 命令行选项。
|
||||
* @return {Object} mysql2 连接参数。
|
||||
*/
|
||||
function resolveClient(options) {
|
||||
const configPath = options.config
|
||||
? path.resolve(PROJECT_ROOT, options.config)
|
||||
: path.resolve(PROJECT_ROOT, options.prod ? 'script/db-query-prod-config.js' : 'config/config.local.js');
|
||||
// eslint-disable-next-line global-require
|
||||
const configFactory = require(configPath);
|
||||
const config = typeof configFactory === 'function' ? configFactory({ name: 'wms-script' }) : configFactory;
|
||||
const client = config && config.mysql && config.mysql.clients && config.mysql.clients.wms;
|
||||
if (!client) {
|
||||
throw new Error(`未在 ${configPath} 找到 mysql.clients.wms 配置`);
|
||||
}
|
||||
return {
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: client.charset || 'utf8mb4',
|
||||
};
|
||||
}
|
||||
|
||||
/** 分类条件(A 已归档 / B 无头 / C 悬空 / D 无库位ID),均以记录 location_id 为基准 */
|
||||
const CATEGORY_SQL = {
|
||||
A: 'ls.id IS NOT NULL AND ls.deleted_at IS NOT NULL',
|
||||
B: 'ls.id IS NOT NULL AND ls.deleted_at IS NULL AND (z.id IS NULL OR z.deleted_at IS NOT NULL)',
|
||||
C: 'r.location_id IS NOT NULL AND ls.id IS NULL',
|
||||
D: 'r.location_id IS NULL',
|
||||
};
|
||||
|
||||
const BASE_FROM = `FROM wms_stock_check_record r
|
||||
LEFT JOIN wms_stock_check c ON c.id = r.check_id
|
||||
LEFT JOIN wms_location_space ls ON ls.id = r.location_id
|
||||
LEFT JOIN wms_location_zone z ON z.id = ls.zone_id`;
|
||||
|
||||
/**
|
||||
* 主流程。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function main() {
|
||||
const options = parseArgs();
|
||||
// eslint-disable-next-line global-require
|
||||
const mysql = require(path.join(PROJECT_ROOT, 'node_modules/mysql2/promise'));
|
||||
const client = resolveClient(options);
|
||||
const connection = await mysql.createConnection(client);
|
||||
|
||||
try {
|
||||
const summary = { target: `${client.host}:${client.port}/${client.database}`, categories: {} };
|
||||
const [ totalRows ] = await connection.query('SELECT COUNT(*) cnt FROM wms_stock_check_record');
|
||||
summary.totalRecords = Number(totalRows[0].cnt) || 0;
|
||||
|
||||
for (const [ key, condition ] of Object.entries(CATEGORY_SQL)) {
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT COUNT(*) cnt, COUNT(DISTINCT r.check_id) checks FROM wms_stock_check_record r
|
||||
LEFT JOIN wms_location_space ls ON ls.id = r.location_id
|
||||
LEFT JOIN wms_location_zone z ON z.id = ls.zone_id
|
||||
WHERE ${condition}`
|
||||
);
|
||||
summary.categories[key] = {
|
||||
records: Number(rows[0].cnt) || 0,
|
||||
checks: Number(rows[0].checks) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 明细明细:A(已归档库位)与 B(无头库位)分别出「按盘点单 / 按库位 / 样本」三段
|
||||
summary.details = {};
|
||||
for (const key of [ 'A', 'B' ]) {
|
||||
const condition = CATEGORY_SQL[key];
|
||||
const [ topChecks ] = await connection.query(
|
||||
`SELECT r.check_id, MAX(c.check_no) check_no, MAX(r.warehouse_id) warehouse_id,
|
||||
COUNT(*) records, COUNT(DISTINCT r.detail_id) details
|
||||
${BASE_FROM}
|
||||
WHERE ${condition}
|
||||
GROUP BY r.check_id
|
||||
ORDER BY records DESC
|
||||
LIMIT ${options.top}`
|
||||
);
|
||||
const [ topLocations ] = await connection.query(
|
||||
`SELECT r.location_id, MAX(ls.space_code) space_code, MAX(ls.zone_id) zone_id,
|
||||
COUNT(*) records, COUNT(DISTINCT r.check_id) checks
|
||||
${BASE_FROM}
|
||||
WHERE ${condition}
|
||||
GROUP BY r.location_id
|
||||
ORDER BY records DESC
|
||||
LIMIT ${options.top}`
|
||||
);
|
||||
const [ samples ] = await connection.query(
|
||||
`SELECT r.id record_id, r.check_id, c.check_no, r.detail_id, r.stock_id,
|
||||
r.location_id, r.location_code, ls.space_code space_code, ls.zone_id zone_id,
|
||||
z.id zone_exists, z.deleted_at zone_deleted_at,
|
||||
r.quantity, r.checker_name, r.checked_at
|
||||
${BASE_FROM}
|
||||
WHERE ${condition}
|
||||
ORDER BY r.id DESC
|
||||
LIMIT ${options.limit}`
|
||||
);
|
||||
summary.details[key] = {
|
||||
topChecks: topChecks.map(row => ({
|
||||
check_id: Number(row.check_id),
|
||||
check_no: row.check_no,
|
||||
warehouse_id: Number(row.warehouse_id),
|
||||
records: Number(row.records),
|
||||
details: Number(row.details),
|
||||
})),
|
||||
topLocations: topLocations.map(row => ({
|
||||
location_id: Number(row.location_id),
|
||||
space_code: row.space_code,
|
||||
zone_id: row.zone_id === null ? null : Number(row.zone_id),
|
||||
records: Number(row.records),
|
||||
checks: Number(row.checks),
|
||||
})),
|
||||
samples: samples.map(row => ({
|
||||
record_id: Number(row.record_id),
|
||||
check_id: Number(row.check_id),
|
||||
check_no: row.check_no,
|
||||
detail_id: Number(row.detail_id),
|
||||
stock_id: row.stock_id === null ? null : Number(row.stock_id),
|
||||
location_id: Number(row.location_id),
|
||||
record_location_code: row.location_code,
|
||||
space_code: row.space_code,
|
||||
zone_id: row.zone_id === null ? null : Number(row.zone_id),
|
||||
zone_exists: row.zone_exists !== null && row.zone_exists !== undefined,
|
||||
zone_deleted_at: row.zone_deleted_at,
|
||||
quantity: Number(row.quantity),
|
||||
checker_name: row.checker_name,
|
||||
checked_at: row.checked_at,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (options.csvOut) {
|
||||
const header = 'category,record_id,check_id,check_no,detail_id,stock_id,location_id,record_location_code,detail_location_code,detail_location_id,space_code,zone_id,zone_exists,zone_deleted_at,quantity,checker_name,checked_at';
|
||||
const lines = [];
|
||||
for (const key of [ 'A', 'B' ]) {
|
||||
if ((summary.categories[key].records || 0) === 0) {
|
||||
continue;
|
||||
}
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT r.id record_id, r.check_id, c.check_no, r.detail_id, r.stock_id,
|
||||
r.location_id, r.location_code, d.location_code detail_location_code,
|
||||
d.location_id detail_location_id, ls.space_code space_code, ls.zone_id zone_id,
|
||||
z.id zone_exists, z.deleted_at zone_deleted_at,
|
||||
r.quantity, r.checker_name, r.checked_at
|
||||
${BASE_FROM}
|
||||
LEFT JOIN wms_stock_check_detail d ON d.id = r.detail_id AND d.check_id = r.check_id
|
||||
WHERE ${CATEGORY_SQL[key]}
|
||||
ORDER BY r.check_id ASC, r.id ASC`
|
||||
);
|
||||
for (const item of rows) {
|
||||
lines.push([
|
||||
key, item.record_id, item.check_id, item.check_no, item.detail_id, item.stock_id,
|
||||
item.location_id, item.location_code, item.detail_location_code, item.detail_location_id,
|
||||
item.space_code, item.zone_id, item.zone_exists ? 1 : 0, item.zone_deleted_at,
|
||||
item.quantity, item.checker_name,
|
||||
item.checked_at instanceof Date ? item.checked_at.toISOString() : item.checked_at,
|
||||
].map(value => (value === null || value === undefined ? '' : String(value).replace(/,/g, ' '))).join(','));
|
||||
}
|
||||
}
|
||||
const outPath = path.resolve(PROJECT_ROOT, options.csvOut);
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, [ header, ...lines ].join('\n'), 'utf8');
|
||||
summary.csvOut = outPath;
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error('[stock-check-record-deleted-location] 执行失败:', error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user