feat(stock.check): 盘点模块功能扩展并同步接口文档(0.3.227)

- 盘点明细/记录支持未知商品(stock_id 可空)与库位范围,模式/状态口径修正
- 新增静态盘点任务、公告相关模型与迁移,stock_warehouse 增加预警数量
- methods/system.json 同步盘点接口文档;headers platform 微信端取值 wx 修正为 miniprogram
This commit is contained in:
liufumingren 2026-10-02 15:43:49 +08:00
parent 6c8a96de3b
commit 190d3cf9e5
25 changed files with 5188 additions and 441 deletions

View File

@ -64,20 +64,15 @@ module.exports = app => {
defaultValue: 'none_checked',
comment: '明细盘点进度:none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘',
},
check_date: {
type: DATE,
allowNull: false,
comment: '盘点日期',
},
start_time: {
type: DATE,
allowNull: true,
comment: '实际开始时间',
comment: '盘点开始时间(第一个盘点明细写入的时间)',
},
end_time: {
type: DATE,
allowNull: true,
comment: '实际结束时间',
comment: '盘点结束时间(完成盘点的时间)',
},
creator_id: {
type: BIGINT(20).UNSIGNED,
@ -121,7 +116,6 @@ module.exports = app => {
paranoid: false,
indexes: [
{ name: 'uk_check_no', unique: true, fields: [ 'check_no' ] },
{ name: 'idx_warehouse_check_date', fields: [ 'warehouse_id', 'check_date' ] },
{ name: 'idx_warehouse_status', fields: [ 'warehouse_id', 'status' ] },
{ name: 'idx_store_id', fields: [ 'store_id' ] },
{ name: 'idx_creator_id', fields: [ 'creator_id' ] },

View File

@ -1,7 +1,9 @@
'use strict';
/**
* 库存盘点明细表模型(仅存盘点商品:stock_id + 商品快照)。
* 库存盘点明细表模型(盘点范围行:商品或库位)。
* 商品行(scope_type=goods):stock_id + 商品快照 + 账面数量快照;
* 库位行(scope_type=location):location_id/location_code + stock_id/item_code 为空。
* 库位/数量等盘点作业信息存放在 wms_stock_check_record。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
@ -26,15 +28,31 @@ module.exports = app => {
allowNull: false,
comment: '仓库ID(冗余,隔离查询)',
},
scope_type: {
type: STRING(20),
allowNull: false,
defaultValue: 'goods',
comment: '盘点范围类型:goods=商品,location=库位',
},
stock_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '库存商品ID,关联 wms_stock_warehouse.id',
allowNull: true,
comment: '库存商品ID,关联 wms_stock_warehouse.id;库位盘点行为空',
},
location_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '库位ID,关联 wms_location_space.id;库位盘点行为空',
},
location_code: {
type: STRING(50),
allowNull: true,
comment: '库位编码(space_code);库位盘点行为空',
},
item_code: {
type: STRING(50),
allowNull: false,
comment: '商品编码快照',
allowNull: true,
comment: '商品编码快照;库位盘点行为空',
},
item_name: {
type: STRING(255),
@ -55,7 +73,7 @@ module.exports = app => {
type: INTEGER(12),
allowNull: false,
defaultValue: 0,
comment: '账面数量快照(生成盘点明细时的系统库存,用于差异对比)',
comment: '账面数量快照(生成盘点明细时的系统库存,用于差异对比;库位行固定为 0,账面按 wms_storage 现算)',
},
remark: {
type: STRING(500),
@ -64,7 +82,7 @@ module.exports = app => {
},
}, {
tableName: 'wms_stock_check_detail',
comment: '库存盘点明细表(盘点商品清单)',
comment: '库存盘点明细表(盘点范围行:商品或库位)',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
@ -73,6 +91,8 @@ module.exports = app => {
{ name: 'idx_check_id', fields: [ 'check_id' ] },
{ name: 'idx_warehouse_stock', fields: [ 'warehouse_id', 'stock_id' ] },
{ name: 'idx_stock_id', fields: [ 'stock_id' ] },
{ name: 'uk_check_stock', unique: true, fields: [ 'check_id', 'stock_id' ] },
{ name: 'uk_check_location', unique: true, fields: [ 'check_id', 'location_code' ] },
],
});

View File

@ -2,7 +2,10 @@
/**
* 库存盘点作业记录表模型(存储盘点的库位、数量信息)。
* 一个盘点明细(商品)可在多个库位多次上报,每次上报一条记录。
* 一个盘点明细(商品行或库位行)可在多个库位/商品维度多次上报,每次上报一条记录;
* 覆盖式语义为「同明细 + 同商品 + 同库位」(uk_detail_stock_location 唯一索引);
* 支持未知商品(仿收货明细口径):stock_id 为空(NULL)+ barcode + item_name,
* 唯一索引中 NULL 不参与唯一约束,未知商品查重由应用层保证。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
@ -33,8 +36,18 @@ module.exports = app => {
},
stock_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id',
allowNull: true,
comment: '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id;NULL=未知商品',
},
barcode: {
type: STRING(100),
allowNull: true,
comment: '扫描到的条码/编码(未知商品上报使用;已知商品可为空)',
},
item_name: {
type: STRING(255),
allowNull: true,
comment: '未知商品名称快照(缺省为条码);已知商品为空',
},
location_id: {
type: BIGINT(20).UNSIGNED,
@ -85,6 +98,7 @@ module.exports = app => {
{ name: 'idx_detail_id', fields: [ 'detail_id' ] },
{ name: 'idx_stock_id', fields: [ 'stock_id' ] },
{ name: 'idx_warehouse_location', fields: [ 'warehouse_id', 'location_code' ] },
{ name: 'uk_detail_stock_location', unique: true, fields: [ 'detail_id', 'stock_id', 'location_code' ] },
],
});

View File

@ -0,0 +1,57 @@
'use strict';
module.exports = app => {
const { BIGINT, DATE } = app.Sequelize;
const StockStaticCheckTask = app.model.define('stock_static_check_task', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键ID',
},
stock_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '商品ID,关联 wms_stock_warehouse.id',
},
task_time: {
type: DATE,
allowNull: false,
comment: '创建盘点任务时间(有记录即表示已为该静态商品创建过盘点任务)',
},
created_at: {
type: DATE,
allowNull: false,
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
comment: '更新时间',
},
deleted_at: {
type: DATE,
defaultValue: null,
comment: '软删除时间',
},
}, {
tableName: 'wms_stock_static_check_task',
freezeTableName: true,
timestamps: false,
paranoid: true,
comment: '静态商品盘点任务关联表(记录是否已为静态商品创建盘点任务,避免重复创建)',
indexes: [
{
name: 'idx_stock_task_time',
fields: [ 'stock_id', 'task_time' ],
},
{
name: 'idx_task_time',
fields: [ 'task_time' ],
},
],
});
return StockStaticCheckTask;
};

View File

@ -0,0 +1,57 @@
'use strict';
module.exports = app => {
const { BIGINT, DATE } = app.Sequelize;
const StockStaticNotice = app.model.define('stock_static_notice', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键ID',
},
stock_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '商品ID,关联 wms_stock_warehouse.id',
},
notice_time: {
type: DATE,
allowNull: false,
comment: '通知时间',
},
created_at: {
type: DATE,
allowNull: false,
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
comment: '更新时间',
},
deleted_at: {
type: DATE,
defaultValue: null,
comment: '软删除时间',
},
}, {
tableName: 'wms_stock_static_notice',
freezeTableName: true,
timestamps: false,
paranoid: true,
comment: '静态商品通知关联表(记录静态商品已通知时间,避免重复通知)',
indexes: [
{
name: 'idx_stock_notice_time',
fields: [ 'stock_id', 'notice_time' ],
},
{
name: 'idx_notice_time',
fields: [ 'notice_time' ],
},
],
});
return StockStaticNotice;
};

View File

@ -175,6 +175,11 @@ module.exports = app => {
defaultValue: 0,
comment: '锁定数量',
},
warning_quantity: {
type: INTEGER(11),
defaultValue: 0,
comment: '库存预警数量',
},
prohibited_id: {
type: INTEGER.UNSIGNED,
comment: '违禁品类型id',

View File

@ -98,6 +98,9 @@ module.exports = app => {
group_order_pack_max_minutes: 40,
big_group_pack_coefficient: 3,
single_weigh_require_pack: false,
stock_warning_enabled: false,
stock_warning_quantity: 0,
stock_static_hours: 168,
return_unpack_max_record_minutes: 5,
inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES,
auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES,
@ -540,6 +543,36 @@ module.exports = app => {
);
}
// 是否开启库存预警:默认关闭
if (Object.prototype.hasOwnProperty.call(parsed, 'stock_warning_enabled')) {
normalized.stock_warning_enabled = normalizeBooleanFlag(
parsed.stock_warning_enabled,
'subject_config.stock_warning_enabled'
);
}
const rawStockWarningQuantity = parsed.stock_warning_quantity;
if (rawStockWarningQuantity === undefined || rawStockWarningQuantity === null || rawStockWarningQuantity === '') {
normalized.stock_warning_quantity = DEFAULT_SUBJECT_CONFIG.stock_warning_quantity;
} else {
const stockWarningQuantity = Number(rawStockWarningQuantity);
if (!Number.isInteger(stockWarningQuantity) || stockWarningQuantity < 0) {
throw new Error('subject_config.stock_warning_quantity 必须是非负整数');
}
normalized.stock_warning_quantity = stockWarningQuantity;
}
const rawStockStaticHours = parsed.stock_static_hours;
if (rawStockStaticHours === undefined || rawStockStaticHours === null || rawStockStaticHours === '') {
normalized.stock_static_hours = DEFAULT_SUBJECT_CONFIG.stock_static_hours;
} else {
const stockStaticHours = Number(rawStockStaticHours);
if (!Number.isFinite(stockStaticHours) || stockStaticHours <= 0) {
throw new Error('subject_config.stock_static_hours 必须是大于 0 的数字(小时)');
}
normalized.stock_static_hours = stockStaticHours;
}
const rawReturnUnpackMaxRecordMinutes = parsed.return_unpack_max_record_minutes;
if (rawReturnUnpackMaxRecordMinutes === undefined || rawReturnUnpackMaxRecordMinutes === null || rawReturnUnpackMaxRecordMinutes === '') {
normalized.return_unpack_max_record_minutes = DEFAULT_SUBJECT_CONFIG.return_unpack_max_record_minutes;

View File

@ -8,8 +8,8 @@ const STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
/** 单次导出任务允许的最大盘点任务数量 */
const STOCK_CHECK_EXPORT_MAX_TASK_IDS = 50;
/** 全部 14 个 method 名(免权限/免鉴权清单共用) */
const ALL_METHOD_NAMES = 'create,list,addDetail,detailDelete,detail,report,recordList,recordDelete,finish,submit,cancel,audit,export,exportTaskProgress';
/** 全部 20 个 method 名(免权限/免鉴权清单共用) */
const ALL_METHOD_NAMES = 'create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,report,recordList,recordDelete,finish,submit,cancel,audit,batchDelete,export,exportTaskProgress,patternList,patternCreate';
/**
* 系统方法层:stock.check(库存盘点模块接口包装层)。
@ -21,10 +21,10 @@ class StockCheckMethodService extends MainService {
super(ctx);
// 免登录方法列表:空(全部需要登录)
const _noNeedLogin = '';
// 免权限方法列表:全部 14 个方法免 API 权限校验(与 stock/transaction.js 口径一致)
// 免权限方法列表:全部 20 个方法免 API 权限校验(与 stock/transaction.js 口径一致)
const _noNeedRight = ALL_METHOD_NAMES;
// 免日志方法列表:查询类与导出类不记录操作日志(recordDelete 为写操作,保留操作日志)
const _noNeedLog = 'list,detail,recordList,export,exportTaskProgress';
// 免日志方法列表:查询类与导出类不记录操作日志(recordDelete/patternCreate 为写操作,保留操作日志)
const _noNeedLog = 'list,detail,result,workData,recordList,export,exportTaskProgress,patternList';
// 免鉴权(仓库有效期检查)方法列表:全部方法免鉴权(与 stock/transaction.js 口径一致)
const _noNeedAuth = ALL_METHOD_NAMES;
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
@ -58,10 +58,11 @@ class StockCheckMethodService extends MainService {
* @param {Object} data 请求体。
* @param {string} [data.title] 盘点名称/主题。
* @param {string} [data.type] 盘点范围类型:all/store/goods/location。
* @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘。
* @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘;
* 按库位盘点(all/location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
* @param {number} [data.store_id] 货主ID(按货主盘点时必填)。
* @param {string} [data.check_date] 盘点日期。
* @param {string} [data.remark] 备注。
* 盘点日期固定为今天,前端不传。
* @return {Promise<Object>} 统一 success 包装,返回新建的盘点任务信息。
*/
async create(data = {}) {
@ -69,7 +70,7 @@ class StockCheckMethodService extends MainService {
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
const creatorName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : '';
const { title, type, mode, store_id: storeId, check_date: checkDate, remark } = data || {};
const { title, type, mode, store_id: storeId, remark } = data || {};
return this._call(
() => this.service.systems.stockCheck.create({
@ -78,7 +79,6 @@ class StockCheckMethodService extends MainService {
type,
mode,
storeId,
checkDate,
remark,
creatorId,
creatorName,
@ -87,6 +87,60 @@ class StockCheckMethodService extends MainService {
);
}
/**
* 拉取盘点定式清单(供前端选择定式快速创建盘点任务)。
*
* @return {Promise<Object>} 统一 success 包装,返回 { patterns, total };
* patterns 每条含 id/name/description/type。
*/
async patternList() {
return this._call(
() => this.service.systems.stockCheck.patternList(),
'拉取盘点定式失败'
);
}
/**
* 按定式快速创建盘点任务。
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
* 盘点方式由定式范围类型固定:库位类定式一律盲盘(blind)、商品类定式一律明盘(open);
* 盘点日期固定为今天,两者均无需前端传入。
*
* @param {Object} data 请求体。
* @param {string} data.pattern_id 定式ID(兼容 patternId 驼峰写法)。
* @param {string} [data.title] 盘点名称/主题,缺省取定式 name。
* @param {string} [data.remark] 备注。
* @return {Promise<Object>} 统一 success 包装,返回
* { check, total_items, pattern_id }。
*/
async patternCreate(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
const creatorName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : '';
const {
pattern_id: patternIdRaw,
patternId: patternIdAlias,
title,
remark,
} = data || {};
const patternId = patternIdRaw !== undefined && patternIdRaw !== null && patternIdRaw !== ''
? patternIdRaw
: patternIdAlias;
return this._call(
() => this.service.systems.stockCheck.patternCreate({
warehouseId,
patternId,
title,
remark,
creatorId,
creatorName,
}),
'按定式创建盘点任务失败'
);
}
/**
* 拉取盘点任务列表。
* 按当前用户仓库(ctx.user.store_id)限定数据范围。
@ -95,8 +149,13 @@ 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.mode] 盘点方式筛选(open/blind)。
* @param {number} [data.where.store_id] 货主筛选。
* @param {string} [data.where.keyword] 关键字(单号/标题模糊)。
* @param {string|Array<string>} [data.where.created_at] 创建时间筛选(单值=当天起,[from,to]=区间)。
* @param {string|Array<string>} [data.where.start_time] 盘点开始时间筛选。
* @param {string|Array<string>} [data.where.end_time] 盘点结束时间筛选。
* @return {Promise<Object>} 统一 success 包装,返回 rows/total。
*/
async list(data = {}) {
@ -107,74 +166,131 @@ class StockCheckMethodService extends MainService {
return this._call(async () => {
const { whereValue = {} } = this.prepareWhereContext(data);
const status = whereValue.status !== undefined ? whereValue.status : data.status;
const type = whereValue.type !== undefined ? whereValue.type : data.type;
const mode = whereValue.mode !== undefined ? whereValue.mode : data.mode;
const storeId = whereValue.store_id !== undefined ? whereValue.store_id : data.store_id;
const keyword = whereValue.keyword !== undefined ? whereValue.keyword : data.keyword;
const createdAt = whereValue.created_at !== undefined ? whereValue.created_at : data.created_at;
const startTime = whereValue.start_time !== undefined ? whereValue.start_time : data.start_time;
const endTime = whereValue.end_time !== undefined ? whereValue.end_time : data.end_time;
return this.service.systems.stockCheck.list({
warehouseId,
status,
type,
mode,
storeId,
keyword,
createdAt,
startTime,
endTime,
pagination,
});
}, '查询盘点任务列表失败');
}
/**
* 添加盘点明细。
* 添加盘点明细(按任务盘点类型添加商品或库位)。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {Array<number>} data.stock_ids 商品库存ID列表(wms_stock_warehouse.id)。
* @return {Promise<Object>} 统一 success 包装,返回新增数与跳过数。
* @param {Array<number>} [data.stock_ids] 商品库存ID列表(wms_stock_warehouse.id,按商品盘点类型使用)。
* @param {Array<string>} [data.locations] 库位编码列表(按库位盘点类型使用;兼容 location_codes 写法)。
* @param {Array<number>} [data.location_ids] 库位ID列表(wms_location_space.id,按库位盘点类型使用;
* 兼容 locationIds 驼峰写法;与 locations 同时传入时 location_ids 优先、locations 忽略)。
* @return {Promise<Object>} 统一 success 包装,返回新增数、跳过数与非法项列表。
*/
async addDetail(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, stock_ids: stockIds } = data || {};
const {
id,
stock_ids: stockIds,
locations: locationsRaw,
location_codes: locationCodesRaw,
location_ids: locationIdsRaw,
locationIds: locationIdsAlias,
} = data || {};
const locations = locationsRaw !== undefined ? locationsRaw : locationCodesRaw;
const locationIds = locationIdsRaw !== undefined ? locationIdsRaw : locationIdsAlias;
return this._call(
() => this.service.systems.stockCheck.addDetail({ warehouseId, id, stockIds }),
() => this.service.systems.stockCheck.addDetail({
warehouseId,
id,
stockIds,
locations,
locationIds,
}),
'添加盘点明细失败'
);
}
/**
* 删除盘点明细(从任务中移除某个商品)。
* 仅主表状态 created/rejected 允许删除;明细存在作业记录时一并防御性删除;
* 删除后重算主表 total_items。
* 批量添加库位明细(兼容入口,转调 addDetail 的库位ID直查路径)。
* 入参传库位ID列表,服务端直接按 ID 查库校验,不经过 space_code 二次解析;
* 幂等添加 scope_type='location' 明细行,已存在的同库位明细自动跳过。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {number} data.detail_id 盘点明细ID(兼容 detailId 驼峰写法)。
* @param {number} [data.detailId] 盘点明细ID(驼峰别名)。
* @return {Promise<Object>} 统一 success 包装,返回 { detail_id, deleted, total_items }。
* @param {Array<number>} data.location_ids 库位ID列表(wms_location_space.id,单次上限 200;
* 兼容 locationIds 驼峰写法)。
* @return {Promise<Object>} 统一 success 包装,返回
* { added, skipped, invalid_location_ids, total_items }。
*/
async addLocationDetail(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, location_ids: locationIdsRaw, locationIds: locationIdsAlias } = data || {};
const locationIds = locationIdsRaw !== undefined ? locationIdsRaw : locationIdsAlias;
return this._call(
() => this.service.systems.stockCheck.addLocationDetail({ warehouseId, id, locationIds }),
'批量添加库位明细失败'
);
}
/**
* 删除盘点明细(批量:从任务中移除一个或多个商品/库位范围行)。
* 仅主表状态 created/rejected 允许删除;明细存在作业记录时一并防御性删除;
* 查不到的明细 ID 计入 skipped_ids 不报错;删除后重算主表 total_items。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {Array<number>|number} data.detail_ids 盘点明细ID数组(单次上限 200;
* 兼容 detailIds 驼峰写法;兼容旧版单值 detail_id 写法,单值自动转数组)。
* @return {Promise<Object>} 统一 success 包装,返回
* { deleted_count, deleted_ids, skipped_ids, total_items };
* 注意:本接口已由旧版单值删除升级为批量删除,响应结构由旧版
* { detail_id, deleted, total_items } 变更为上述结构。
*/
async detailDelete(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, detail_id: detailIdRaw, detailId: detailIdAlias } = data || {};
const detailId = detailIdRaw !== undefined && detailIdRaw !== null && detailIdRaw !== ''
? detailIdRaw
: detailIdAlias;
const { id, detail_ids: detailIdsRaw, detailIds: detailIdsAlias, detail_id: detailIdSingle } = data || {};
const detailIds = detailIdsRaw !== undefined
? detailIdsRaw
: (detailIdsAlias !== undefined ? detailIdsAlias : detailIdSingle);
return this._call(
() => this.service.systems.stockCheck.detailDelete({
warehouseId,
id,
detailId,
detailIds,
}),
'删除盘点明细失败'
);
}
/**
* 拉取盘点任务的全部明细行(商品清单)及每条明细的盘点作业记录(库位+数量)。
* 拉取盘点任务明细(任务范围行:商品或库位)。
* 只返回范围行,不包含盘点作业聚合与作业记录(作业聚合见 result;
* 作业记录的 barcode/item_name/images 口径见 result/recordList)。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @return {Promise<Object>} 统一 success 包装,返回 { check, rows, total };rows 每条含商品快照 +
* 已盘聚合(checked_quantity/diff_quantity/is_diff/location_codes/checkers/last_checked_at)、
* records(作业记录列表)与 locations(按库位聚合 [{ location_id, location_code, quantity }])。
* @return {Promise<Object>} 统一 success 包装,返回 { check, rows, total };
* rows 每条为纯范围行字段:id/check_id/warehouse_id/scope_type/stock_id/location_id/
* location_code/item_code/item_name/spec/batch_no/system_quantity/remark/created_at/updated_at。
*/
async detail(data = {}) {
const { ctx } = this;
@ -187,23 +303,80 @@ class StockCheckMethodService extends MainService {
);
}
/**
* 拉取盘点明细结果(按范围行聚合作业记录)。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @return {Promise<Object>} 统一 success 包装,返回 { check, rows, total };
* 商品行含已盘聚合(checked_quantity/diff_quantity/is_diff/status/location_codes/
* checkers/last_checked_at)与 records(作业记录列表,每条含 barcode/item_name/images)、
* locations(按库位聚合 [{ location_id, location_code, quantity }]);
* 库位行含 checked_quantity(行级合计)/diff_quantity(行内差异代数和)/is_diff/status
* 与 records、locations、stocks(按商品聚合,账面查 wms_storage SUM(quantity));
* 未知商品(记录 stock_id 为空)行级输出 unknown_items [{ barcode, item_name, checked_quantity }]
* (无账面,差异 = 实盘 - 0 = 盘盈,已计入行级 checked_quantity/diff_quantity/is_diff)。
*/
async result(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id } = data || {};
return this._call(
() => this.service.systems.stockCheck.result({ warehouseId, id }),
'查询盘点结果失败'
);
}
/**
* 拉取盘点作业数据(单接口三视图,view 入参驱动)。
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {string} data.view 视图类型:location/goods/space。
* @return {Promise<Object>} 统一 success 包装,返回 { check, rows, total };rows 结构按 view 不同:
* location=库位结构(任务库位范围行为列表,行内挂 goods/unknown 作业记录子列表);
* goods=商品结构(任务商品范围行为列表,行内挂按库位聚合的 locations 作业记录,
* 明盘返回数量与差异,盲盘不返回数量字段);
* space=商品结构(任务商品所在库位为列表,按拣货路径排序,行内挂该库位的任务商品,
* 明盘返回账面/实盘数量,盲盘不返回数量字段)。
*/
async workData(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, view } = data || {};
return this._call(
() => this.service.systems.stockCheck.workData({ warehouseId, id, view }),
'拉取盘点作业数据失败'
);
}
/**
* 盘点作业上报(覆盖式)。
* 同明细 + 同库位编码重复上报时更新已有记录(未传库位归入"无库位"分组,location_code 为 null),不再新增。
* 同明细 + 同商品 + 同库位编码重复上报时更新已有记录(未传库位归入"无库位"分组,location_code 为 null),不再新增;
* 未知商品(未传 stock_id 但传了 barcode):先按条码匹配系统商品,命中回填 stock_id 按已知商品处理,
* 未命中记录 stock_id=null + barcode + item_name(item_name 缺省为 barcode);
* stock_id 与 barcode 都未传沿用现有报错口径。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {number} data.detail_id 明细ID。
* @param {string} [data.location] 库位编码(可空)。
* @param {string} [data.location] 库位编码(可空;库位明细行以明细库位为准)。
* @param {number} data.quantity 实盘数量(>=0)。
* @return {Promise<Object>} 统一 success 包装,返回 { record, detail_id, mode: 'created'|'updated', ...summary }。
* @param {number} [data.stock_id] 商品库存ID(wms_stock_warehouse.id;库位明细行必填,或改传 barcode)。
* @param {string} [data.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品,未命中记为未知商品)。
* @param {string} [data.item_name] 未知商品名称(缺省为 barcode;已知商品忽略)。
* @return {Promise<Object>} 统一 success 包装,返回 { record, detail_id, mode: 'created'|'updated', ...summary };
* record 为作业记录全字段(含 barcode/item_name)。
*/
async report(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const checkerId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
const checkerName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : '';
const { id, detail_id: detailId, location, quantity } = data || {};
const { id, detail_id: detailId, location, quantity, stock_id: stockId, barcode, item_name: itemName } = data || {};
return this._call(
() => this.service.systems.stockCheck.report({
@ -212,6 +385,9 @@ class StockCheckMethodService extends MainService {
detailId,
location,
quantity,
stockId,
barcode,
itemName,
checkerId,
checkerName,
}),
@ -228,7 +404,8 @@ class StockCheckMethodService extends MainService {
* @param {number} [data.detail_id] 明细ID(可选,传了只查该明细)。
* @param {Object} [data.pagination] 分页参数。
* @return {Promise<Object>} 统一 success 包装,返回 { rows, total, page, pageSize };
* rows 每条为记录表全字段 + 商品快照列(item_code/item_name)。
* rows 每条为记录表全字段(含 barcode/item_name)+ 商品快照列(item_code/item_name,
* 未知商品显示扫描条码与名称快照)与 images: [{ id: file_id, url }](业务类型 stock_check_record)。
*/
async recordList(data = {}) {
const { ctx } = this;
@ -348,9 +525,29 @@ class StockCheckMethodService extends MainService {
);
}
/**
* 批量删除盘点任务(仅删除已作废任务,非作废或查不到的任务跳过)。
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
*
* @param {Object} data 请求体。
* @param {Array<number>} data.ids 盘点任务ID数组(单次上限 200)。
* @return {Promise<Object>} 统一 success 包装,返回
* { total, deleted_count, skipped_count, deleted_ids, skipped_ids }。
*/
async batchDelete(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { ids } = data || {};
return this._call(
() => this.service.systems.stockCheck.batchDelete({ warehouseId, ids }),
'批量删除盘点任务失败'
);
}
/**
* 提交盘点任务导出任务。
* 异步执行:查询任务与明细 → ExcelJS 流式写入(Sheet1=盘点单行,Sheet2=明细行)→ COS 上传。
* 异步执行:查询任务与作业记录 → ExcelJS 流式写入(Sheet1=盘点单行,Sheet2=盘点明细:一行一条实际盘点记录,含商品/库位/实盘数量/盘点人/时间,不导出未盘的任务范围行)→ COS 上传。
* 进度通过 Redis 缓存追踪,立即返回任务ID。
*
* @param {Object} data 请求体。

View File

@ -9,9 +9,9 @@ class WarehouseService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail';
const _noNeedLog = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail';
const _noNeedAuth = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail';
const _noNeedRight = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail,staticList';
const _noNeedLog = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail,staticList';
const _noNeedAuth = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail,staticList';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -561,6 +561,7 @@ class WarehouseService extends MainService {
inbound_min_days,
outbound_min_days,
remaining_threshold_days,
warning_quantity,
} = data || {};
try {
const result = await service.systems.stockStore.saveWarehouseStock({
@ -607,6 +608,7 @@ class WarehouseService extends MainService {
inbound_min_days,
outbound_min_days,
remaining_threshold_days,
warning_quantity,
});
return this.success('ok', { data: result, code: 200 });
} catch (error) {
@ -958,6 +960,26 @@ class WarehouseService extends MainService {
}
}
/**
* 查询静态商品列表(仓库级)。
* 静态判定:商品最后一个收/发流水时间超过仓库配置的静态时间阈值即视为进入静态。
* @param {Object} data 请求体
* @param {Object} [data.pagination] 分页参数(page/pageSize)
* @param {number} [data.hours] 静态时间阈值(小时),缺省读仓库配置 stock_static_hours(默认 168)
* @return {Promise<Object>} data 为 { list, pagination }
*/
async staticList(data = {}) {
const { ctx, service } = this;
const pagination = this.isPlainObject(data.pagination) ? data.pagination : data;
const result = await service.systems.stockWarehouse.getStaticStockList({
warehouseId: ctx.user && ctx.user.store_id,
hours: data.hours,
page: Number(pagination.page || 1),
pageSize: Number(pagination.pageSize || 20),
});
return this.success('ok', result);
}
/**
* 查询库存操作日志。
* @param {Object} data 请求体(会自动注入当前 warehouseId)

View File

@ -500,6 +500,10 @@ class PickSystemService extends Service {
item_name: String(groupItem && groupItem.item_name || '').trim(),
stock_id: Number(groupItem && groupItem.stock_id || 0),
total_qty: Number(groupItem && groupItem.total_qty || 0),
// 拣货要求:取自商品资料链路(getStockDetails),merge_requirements=Y 时已回退为打包要求
pick_requirements: String(
(groupItem && groupItem.stock && groupItem.stock.pick_requirements) || ''
).trim(),
box_allocations: boxAllocations,
store_id: groupItem.store_id != null ? Number(groupItem.store_id) : 0,
owner_code: String(groupItem.owner_code || '').trim(),

View File

@ -354,6 +354,32 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
required: false,
description: '开启后散单称重(订单波次范围 wave_scope 非 1 大团购 / 3 小团购)前必须已打包完成(pack_status=fin),未打包时拒绝称重并返回错误,默认 false(关闭)',
}),
Object.freeze({
key: 'stock_warning_enabled',
name: '是否开启库存预警',
type: 'flag',
default: false,
required: false,
description: '开启后,库存数量低于预警数量时触发库存预警,默认 false(关闭)',
}),
Object.freeze({
key: 'stock_warning_quantity',
name: '库存预警数量',
type: 'integer',
default: 0,
required: false,
description: '库存预警阈值:库存低于该数量时触发预警,默认 0,必须为非负整数',
min: 0,
}),
Object.freeze({
key: 'stock_static_hours',
name: '商品进入静态时间(小时)',
type: 'number',
default: 168,
required: false,
description: '商品最后一个收/发流水时间超过该小时数即视为进入静态,默认 168 小时,必须大于 0',
min: 0.1,
}),
Object.freeze({
key: 'return_unpack_max_record_minutes',
name: '拆包最大录制时长(分钟)',

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,445 @@
'use strict';
const Service = require('egg').Service;
/** 静态盘点:仓库未配置 stock_static_hours 时使用的默认阈值小时数 */
const DEFAULT_STATIC_HOURS = 168;
/**
* 盘点定式定义集合(代码注册,不建表)。
* 字段说明:
* - id:定式唯一标识(method 层 pattern_id 入参);
* - name:定式名称(创建任务时作为默认标题);
* - description:定式描述(含对象收集口径);
* - type:对应盘点任务 type(location=按库位 / goods=按商品);
* - collect:对象收集函数名(本服务内实现,入参 { warehouseId },
* 返回 { locations: [{location_id, location_code}] } 或 { stock_ids: [...] })。
*/
const STOCK_CHECK_PATTERNS = Object.freeze([
Object.freeze({
id: 'empty_location',
name: '空库位盘点',
description: '自动收集当前仓库所有「账面为空」的启用库位:wms_location_space(warehouse_id 匹配且 is_enabled=1)中,在 wms_storage 不存在任何 quantity>0 库存记录的库位(LEFT JOIN 判空)',
type: 'location',
collect: 'collectEmptyLocation',
}),
Object.freeze({
id: 'mis_shipment',
name: '错发盘点',
description: '自动收集所有登记过错发工单(wms_after_sale.type=order 且 sub_type=mis_shipment)关联订单的商品:工单状态口径为「凡登记过即纳入,排除已关闭(closed)/已取消(cancelled)工单」,取工单 order_id 集合查询订单明细分表(OrderItemsFactory.getCurrentModel)后按 stock_id 去重',
type: 'goods',
collect: 'collectMisShipment',
}),
Object.freeze({
id: 'expiring',
name: '临期盘点',
description: '自动收集所有开启保质期管理(wms_stock_warehouse.is_shelf_life_mgmt=Y)且存在临期库存的商品:在 wms_storage 存在 quantity>0 且 expiry_date 非空、expiry_date <= 当前时间+该商品 remaining_threshold_days 天的库存记录(商品维度去重;remaining_threshold_days 为 0 时按已到期 expiry_date <= 当前时间处理)',
type: 'goods',
collect: 'collectExpiring',
}),
Object.freeze({
id: 'static',
name: '静态盘点',
description: '自动收集所有停收停发超过时间的商品:商品最后一次 INBOUND/OUTBOUND 流水(wms_stock_transaction)距今超过仓库配置 stock_static_hours 小时(默认 168 小时),无流水的商品按 wms_stock_warehouse.create_at 计算;已存在 wms_stock_static_check_task 记录的 stock_id(已进入静态已盘点商品)自动排除,创建任务成功后把命中的 stock_id 写入该表',
type: 'goods',
collect: 'collectStatic',
}),
Object.freeze({
id: 'warning',
name: '预警盘点',
description: '自动收集所有到达库存预警线的商品:wms_stock_warehouse.quantity < 仓库配置 stock_warning_quantity(商品维度去重);要求仓库配置 stock_warning_enabled=true 才可执行,未开启时返回 400「未开启库存预警」',
type: 'goods',
collect: 'collectWarning',
}),
]);
/**
* 盘点定式注册服务(供 systems.stockCheck 转调)。
* 职责:维护定式清单、提供定式对象收集函数,不直接落库盘点主表。
*/
class StockCheckPatternsService extends Service {
/**
* 创建带业务错误码的异常对象。
*
* @param {string} message 错误信息。
* @param {number} [code=400] 业务错误码。
* @return {Error} 包含 code 的异常对象。
*/
createBusinessError(message, code = 400) {
const error = new Error(`${message}`);
error.code = code;
return error;
}
/**
* 判断是否为普通对象(非数组、非 null)。
*
* @param {*} value 待判断值。
* @return {boolean} 是普通对象返回 true。
*/
_isPlainObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
/**
* 归一化 subject_config(兼容 JSON 字符串与对象)。
*
* @param {*} raw 原始配置值。
* @return {Object} 配置对象,非法时返回空对象。
*/
_normalizeSubjectConfig(raw) {
if (this._isPlainObject(raw)) {
return raw;
}
if (typeof raw === 'string') {
const trimmed = raw.trim();
if (!trimmed) {
return {};
}
try {
const parsed = JSON.parse(trimmed);
return this._isPlainObject(parsed) ? parsed : {};
} catch {
return {};
}
}
return {};
}
/**
* 判断布尔标志是否开启(兼容 true / 1 / '1' / 'true')。
*
* @param {*} value 标志值。
* @return {boolean} 开启返回 true。
*/
_isTruthyFlag(value) {
return value === true
|| value === 1
|| value === '1'
|| String(value || '').trim().toLowerCase() === 'true';
}
/**
* 读取当前仓库设置(wms_store.subject_config)。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object>} subject_config 对象,读取失败返回空对象。
*/
async _getWarehouseSubjectConfig(warehouseId) {
const { ctx } = this;
try {
const storeModel = ctx.model && ctx.model.Store;
if (!storeModel || typeof storeModel.findByPk !== 'function') {
return {};
}
const store = await storeModel.findByPk(Number(warehouseId), {
attributes: [ 'id', 'subject_config' ],
raw: true,
});
return this._normalizeSubjectConfig(store && store.subject_config);
} catch (error) {
ctx.logger && ctx.logger.warn && ctx.logger.warn(
`[stockCheckPatterns] 读取仓库设置失败 warehouseId=${warehouseId}: ${error && error.message}`
);
return {};
}
}
/**
* 读取静态盘点阈值小时数(仓库配置 stock_static_hours,默认 168)。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<number>} 阈值小时数。
*/
async _resolveStaticHours(warehouseId) {
const subjectConfig = await this._getWarehouseSubjectConfig(warehouseId);
const configHours = Number(subjectConfig.stock_static_hours || 0);
return Number.isFinite(configHours) && configHours > 0 ? configHours : DEFAULT_STATIC_HOURS;
}
/**
* 执行裸 SQL 查询并返回行数组。
*
* @param {string} sql 查询语句(命名占位符 :name)。
* @param {Object} [replacements={}] 占位符替换值。
* @return {Promise<Array<Object>>} 查询结果行数组。
*/
async _queryRows(sql, replacements = {}) {
const { ctx } = this;
const rows = await ctx.model.query(sql, {
replacements,
type: ctx.model.QueryTypes.SELECT,
});
return Array.isArray(rows) ? rows : [];
}
/**
* 将 ID 列表归一化为去重后的正整数列表。
*
* @param {Array<*>} values 原始 ID 列表。
* @return {Array<number>} 去重后的正整数列表。
*/
_normalizePositiveIntegerList(values) {
const list = Array.isArray(values) ? values : [];
return [ ...new Set(
list
.map(value => Number(value))
.filter(value => Number.isInteger(value) && value > 0)
) ];
}
/**
* 拉取定式清单(仅对外字段,不含内部执行函数)。
*
* @return {Array<Object>} 定式数组,每项含 id/name/description/type。
*/
listPatterns() {
return STOCK_CHECK_PATTERNS.map(pattern => ({
id: pattern.id,
name: pattern.name,
description: pattern.description,
type: pattern.type,
}));
}
/**
* 按定式 ID 查询定式定义。
*
* @param {string|number} patternId 定式ID。
* @return {Object|null} 定式定义,不存在返回 null。
*/
getPatternById(patternId) {
const normalized = String(patternId || '').trim();
return STOCK_CHECK_PATTERNS.find(pattern => pattern.id === normalized) || null;
}
/**
* 按定式 ID 收集盘点对象(goods 型返回 stock_ids,location 型返回库位列表)。
*
* @param {string|number} patternId 定式ID。
* @param {Object} [context={}] 收集上下文。
* @param {number} context.warehouseId 仓库ID。
* @return {Promise<Object|null>} { stock_ids } 或 { locations },定式不存在返回 null。
*/
async collectById(patternId, context = {}) {
const pattern = this.getPatternById(patternId);
if (!pattern || typeof this[pattern.collect] !== 'function') {
return null;
}
return this[pattern.collect](context);
}
/**
* 空库位定式:收集账面为空的启用库位。
* 口径:wms_location_space(warehouse_id 匹配、is_enabled=1、未删除)在
* wms_storage 不存在任何 quantity>0 且未删除的库存记录(LEFT JOIN 判空)。
*
* @param {Object} context 收集上下文。
* @param {number} context.warehouseId 仓库ID。
* @return {Promise<Object>} { locations: [{ location_id, location_code }] }。
*/
async collectEmptyLocation(context = {}) {
const warehouseId = Number(context.warehouseId);
const rows = await this._queryRows(
`
SELECT ls.id AS location_id, ls.space_code AS location_code
FROM wms_location_space ls
LEFT JOIN wms_storage st
ON st.space_id = ls.id
AND st.delete_at IS NULL
AND st.quantity > 0
WHERE ls.warehouse_id = :warehouseId
AND ls.is_enabled = 1
AND ls.deleted_at IS NULL
AND st.id IS NULL
ORDER BY ls.id ASC
`,
{ warehouseId }
);
const locations = rows
.filter(row => row && row.location_id)
.map(row => ({
location_id: Number(row.location_id),
location_code: String(row.location_code || '').trim(),
}));
return { locations };
}
/**
* 错发定式:收集登记过错发工单的订单关联商品。
* 口径:wms_after_sale(warehouse_id 匹配、type=order、sub_type=mis_shipment、未删除)
* 中排除已关闭(closed)/已取消(cancelled)工单,其余状态一律纳入;
* 取 order_id 集合查询订单明细分表(OrderItemsFactory.getCurrentModel)后按 stock_id 去重。
*
* @param {Object} context 收集上下文。
* @param {number} context.warehouseId 仓库ID。
* @return {Promise<Object>} { stock_ids: number[] }。
*/
async collectMisShipment(context = {}) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const warehouseId = Number(context.warehouseId);
const afterSaleRows = await ctx.model.AfterSale.findAll({
where: {
warehouse_id: warehouseId,
type: 'order',
sub_type: 'mis_shipment',
status: { [Op.notIn]: [ 'closed', 'cancelled' ] },
deleted_at: null,
},
attributes: [ 'order_id' ],
raw: true,
});
const orderIds = this._normalizePositiveIntegerList(
(Array.isArray(afterSaleRows) ? afterSaleRows : []).map(row => row && row.order_id)
);
if (orderIds.length === 0) {
return { stock_ids: [] };
}
const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
const itemRows = await orderItemsModel.findAll({
where: { order_id: { [Op.in]: orderIds } },
attributes: [ 'stock_id' ],
raw: true,
});
const stockIds = this._normalizePositiveIntegerList(
(Array.isArray(itemRows) ? itemRows : []).map(row => row && row.stock_id)
);
return { stock_ids: stockIds };
}
/**
* 临期定式:收集开启保质期管理且存在临期库存的商品。
* 口径:wms_stock_warehouse(warehouse_id 匹配、is_valid=Y、未删除、is_shelf_life_mgmt=Y)
* 关联 wms_storage(quantity>0、expiry_date 非空、未删除)按 stock_id 取最早到期日:
* remaining_threshold_days>0 时最早到期日 <= 当前时间+阈值天数,
* remaining_threshold_days<=0(含空)时按已到期处理(最早到期日 <= 当前时间),商品维度去重。
*
* @param {Object} context 收集上下文。
* @param {number} context.warehouseId 仓库ID。
* @return {Promise<Object>} { stock_ids: number[] }。
*/
async collectExpiring(context = {}) {
const warehouseId = Number(context.warehouseId);
const rows = await this._queryRows(
`
SELECT sw.id AS stock_id
FROM wms_stock_warehouse sw
INNER JOIN (
SELECT stock_id, MIN(expiry_date) AS min_expiry_date
FROM wms_storage
WHERE warehouse_id = :warehouseId
AND quantity > 0
AND expiry_date IS NOT NULL
AND delete_at IS NULL
GROUP BY stock_id
) st ON st.stock_id = sw.id
WHERE sw.warehouse_id = :warehouseId
AND sw.is_valid = 'Y'
AND sw.deleted_at IS NULL
AND sw.is_shelf_life_mgmt = 'Y'
AND (
(COALESCE(sw.remaining_threshold_days, 0) > 0
AND st.min_expiry_date <= DATE_ADD(NOW(), INTERVAL COALESCE(sw.remaining_threshold_days, 0) DAY))
OR
(COALESCE(sw.remaining_threshold_days, 0) <= 0
AND st.min_expiry_date <= NOW())
)
ORDER BY sw.id ASC
`,
{ warehouseId }
);
return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) };
}
/**
* 静态定式:收集停收停发超过阈值的商品。
* 口径:商品最后一次 INBOUND/OUTBOUND 流水(wms_stock_transaction,命中
* warehouse_id+transaction_type+stock_id 索引)距今超过仓库配置
* stock_static_hours 小时(默认 168 小时),无流水的商品按
* wms_stock_warehouse.create_at 计算;排除 wms_stock_static_check_task
* 已有记录(未删除)的 stock_id,商品维度去重。
*
* @param {Object} context 收集上下文。
* @param {number} context.warehouseId 仓库ID。
* @return {Promise<Object>} { stock_ids: number[] }。
*/
async collectStatic(context = {}) {
const warehouseId = Number(context.warehouseId);
const staticHours = await this._resolveStaticHours(warehouseId);
const cutoff = new Date(Date.now() - staticHours * 3600 * 1000);
const rows = await this._queryRows(
`
SELECT sw.id AS stock_id
FROM wms_stock_warehouse sw
LEFT JOIN (
SELECT stock_id, MAX(last_flow_at) AS last_flow_at
FROM (
SELECT stock_id, MAX(created_at) AS last_flow_at
FROM wms_stock_transaction
WHERE warehouse_id = :warehouseId
AND transaction_type = 'INBOUND'
GROUP BY stock_id
UNION ALL
SELECT stock_id, MAX(created_at) AS last_flow_at
FROM wms_stock_transaction
WHERE warehouse_id = :warehouseId
AND transaction_type = 'OUTBOUND'
GROUP BY stock_id
) flow_union
GROUP BY stock_id
) t ON t.stock_id = sw.id
WHERE sw.warehouse_id = :warehouseId
AND sw.is_valid = 'Y'
AND sw.deleted_at IS NULL
AND COALESCE(t.last_flow_at, sw.create_at) < :cutoff
AND NOT EXISTS (
SELECT 1
FROM wms_stock_static_check_task sct
WHERE sct.stock_id = sw.id
AND sct.deleted_at IS NULL
)
ORDER BY sw.id ASC
`,
{ warehouseId, cutoff }
);
return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) };
}
/**
* 预警定式:收集到达库存预警线的商品。
* 口径:仓库配置 stock_warning_enabled=true 时才可执行(未开启抛 400「未开启库存预警」),
* 收集 wms_stock_warehouse(warehouse_id 匹配、is_valid=Y、未删除)中
* quantity < stock_warning_quantity 的商品,商品维度去重。
*
* @param {Object} context 收集上下文。
* @param {number} context.warehouseId 仓库ID。
* @return {Promise<Object>} { stock_ids: number[] }。
* @throws {Error} 未开启库存预警时抛出业务错误(错误码 400)。
*/
async collectWarning(context = {}) {
const warehouseId = Number(context.warehouseId);
const subjectConfig = await this._getWarehouseSubjectConfig(warehouseId);
if (!this._isTruthyFlag(subjectConfig.stock_warning_enabled)) {
throw this.createBusinessError('未开启库存预警');
}
const threshold = Number(subjectConfig.stock_warning_quantity || 0);
const rows = await this._queryRows(
`
SELECT id AS stock_id
FROM wms_stock_warehouse
WHERE warehouse_id = :warehouseId
AND is_valid = 'Y'
AND deleted_at IS NULL
AND quantity < :threshold
ORDER BY id ASC
`,
{ warehouseId, threshold }
);
return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) };
}
}
module.exports = StockCheckPatternsService;

View File

@ -2588,7 +2588,7 @@ class stockStoreService extends Service {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'pick_requirements', 'recheck_requirements', 'merge_requirements', 'managementFlags', 'stock_unit', 'need_recheck' ];
const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'pick_requirements', 'recheck_requirements', 'merge_requirements', 'managementFlags', 'stock_unit', 'need_recheck', 'warning_quantity' ];
const { ids, method, value } = ctx.request.body;
@ -2671,6 +2671,18 @@ class stockStoreService extends Service {
update_by: ctx.user.id || ctx.user.username,
};
} else if (method === 'warning_quantity') {
// 库存预警数量:必须为非负整数
const updateValue = parseInt(value, 10);
if (isNaN(updateValue) || updateValue < 0 || !Number.isInteger(Number(value))) {
return { message: '库存预警数量必须是非负整数', code: 405 };
}
updateData = {
warning_quantity: updateValue,
update_at: new Date(),
update_by: ctx.user.id || ctx.user.username,
};
} else if (method === 'merge_requirements') {
// 要求是否合并:Y=合并,N=不合并
const updateValue = String(value).trim().toUpperCase();
@ -3114,6 +3126,7 @@ class stockStoreService extends Service {
'width',
'enable_box_spec',
'quantity_per_box',
'warning_quantity',
'box_gross_weight',
'box_net_weight',
'box_length',
@ -3162,6 +3175,7 @@ class stockStoreService extends Service {
box_volume_m3, boxVolumeM3,
shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days,
need_recheck,
warning_quantity,
} = data;
const normalizedVolume = volume ?? volume_cm3 ?? volumeCm3;
const normalizedBoxVolume = box_volume ?? box_volume_m3 ?? boxVolumeM3;
@ -3255,6 +3269,7 @@ class stockStoreService extends Service {
inbound_min_days,
outbound_min_days,
remaining_threshold_days,
warning_quantity,
updated_at: new Date(),
};
// 5. 清除空值
@ -3330,6 +3345,7 @@ class stockStoreService extends Service {
box_gross_weight, box_net_weight, box_length,
box_width, box_height, box_volume, box_remark,
need_recheck,
warning_quantity,
} = data;
// 1. 参数验证
@ -3374,6 +3390,7 @@ class stockStoreService extends Service {
quantity_per_box,
box_gross_weight,
box_net_weight,
warning_quantity,
item_type: 'ZC',
level: 'C',
store_id,
@ -3438,7 +3455,7 @@ class stockStoreService extends Service {
}
// 数值类型验证
const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight' ];
const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight', 'warning_quantity' ];
for (const field of numericFields) {
if (data[field] && isNaN(Number(data[field]))) {
throw new Error(`${field} 必须是有效的数字`);

View File

@ -190,7 +190,89 @@ class StockTransactionService extends Service {
created_at: data.created_at || new Date(),
};
return ctx.model.StockTransaction.create(payload, options);
const row = await ctx.model.StockTransaction.create(payload, options);
// 订单出入库(收/发)后商品离开静态状态:硬删除静态通知/盘点任务关联记录(失败不影响主流程)
if (data.transaction_type === 'INBOUND' || data.transaction_type === 'OUTBOUND') {
await Promise.all([
this.clearStaticNoticeByStockId(data.stock_id, options),
this.clearStaticCheckTaskByStockId(data.stock_id, options),
]);
}
return row;
}
/**
* 硬删除指定商品的静态通知记录。
*
* 商品一旦有新的收/发流水即离开静态状态,历史通知记录不再有意义,
* 因此在流水写入成功后直接物理删除(不走软删)。
* 清理失败不影响出入库主流程(仅记录 warn)。
*
* @param {number} stockId 商品库存ID
* @param {Object} [options] 写入选项
* @param {Object} [options.transaction] 数据库事务(建议与流水写入同一事务)
* @return {Promise<number>} 删除行数(异常时返回 0)
*/
async clearStaticNoticeByStockId(stockId, options = {}) {
const { ctx } = this;
const numericStockId = Number(stockId);
if (!Number.isFinite(numericStockId) || numericStockId <= 0) {
return 0;
}
try {
const noticeModel = ctx.model && ctx.model.StockStaticNotice;
if (!noticeModel) {
return 0;
}
return await noticeModel.destroy({
where: { stock_id: numericStockId },
force: true, // 硬删除(paranoid 表需 force 才能物理删除)
...(options && options.transaction ? { transaction: options.transaction } : {}),
});
} catch (err) {
ctx.logger && ctx.logger.warn && ctx.logger.warn(
`[stockTransaction.clearStaticNoticeByStockId] 清理静态通知记录失败 stockId=${numericStockId}: ${err && err.message}`
);
return 0;
}
}
/**
* 硬删除指定商品的静态盘点任务关联记录。
*
* 商品一旦有新的收/发流水即离开静态状态,已创建的盘点任务关联不再有意义,
* 因此在流水写入成功后直接物理删除(不走软删)。
* 清理失败不影响出入库主流程(仅记录 warn)。
*
* @param {number} stockId 商品库存ID
* @param {Object} [options] 写入选项
* @param {Object} [options.transaction] 数据库事务(建议与流水写入同一事务)
* @return {Promise<number>} 删除行数(异常时返回 0)
*/
async clearStaticCheckTaskByStockId(stockId, options = {}) {
const { ctx } = this;
const numericStockId = Number(stockId);
if (!Number.isFinite(numericStockId) || numericStockId <= 0) {
return 0;
}
try {
const taskModel = ctx.model && ctx.model.StockStaticCheckTask;
if (!taskModel) {
return 0;
}
return await taskModel.destroy({
where: { stock_id: numericStockId },
force: true, // 硬删除(paranoid 表需 force 才能物理删除)
...(options && options.transaction ? { transaction: options.transaction } : {}),
});
} catch (err) {
ctx.logger && ctx.logger.warn && ctx.logger.warn(
`[stockTransaction.clearStaticCheckTaskByStockId] 清理静态盘点任务关联记录失败 stockId=${numericStockId}: ${err && err.message}`
);
return 0;
}
}
/**

View File

@ -257,6 +257,225 @@ class StockWarehouseService extends Service {
// 删除缓存失败不影响主流程
}
}
/**
* 读取商品库存预警数量(内部方法)。
*
* 优先级:
* 1. 商品单独设置了预警数量(warning_quantity > 0)→ 取商品设置数;
* 2. 货主(stock.store_id 对应 wms_store)开启库存预警(stock_warning_enabled)
* 且配置了预警数量(stock_warning_quantity > 0)→ 取货主设置数;
* 3. 以上均不满足 → 返回 0(不预警)。
*
* @param {number|string} stockId 仓库商品ID(wms_stock_warehouse.id)。
* @return {Promise<number>} 库存预警数量(非负整数),读取异常时返回 0。
*/
async getStockWarningQuantity(stockId) {
const { ctx } = this;
const normalizedStockId = Number(stockId || 0);
if (!Number.isFinite(normalizedStockId) || normalizedStockId <= 0) {
return 0;
}
try {
const stockModel = ctx.model && ctx.model.StockWarehouse;
if (!stockModel || typeof stockModel.findOne !== 'function') {
return 0;
}
const stock = await stockModel.findOne({
where: { id: normalizedStockId, is_valid: 'Y', deleted_at: null },
attributes: [ 'id', 'store_id', 'warning_quantity' ],
raw: true,
});
if (!stock) {
return 0;
}
// 商品单独设置优先
const productWarningQuantity = Number(stock.warning_quantity || 0);
if (Number.isInteger(productWarningQuantity) && productWarningQuantity > 0) {
return productWarningQuantity;
}
// 货主配置:开启且数量 > 0 才生效
const storeId = Number(stock.store_id || 0);
if (storeId > 0) {
const storeModel = ctx.model && ctx.model.Store;
if (storeModel && typeof storeModel.findByPk === 'function') {
const store = await storeModel.findByPk(storeId, {
attributes: [ 'id', 'subject_config' ],
raw: true,
});
const subjectConfig = store && store.subject_config
? store.subject_config
: {};
const enabled = subjectConfig.stock_warning_enabled === true
|| subjectConfig.stock_warning_enabled === 1
|| String(subjectConfig.stock_warning_enabled || '').trim().toLowerCase() === 'true';
const storeWarningQuantity = Number(subjectConfig.stock_warning_quantity || 0);
if (enabled && Number.isInteger(storeWarningQuantity) && storeWarningQuantity > 0) {
return storeWarningQuantity;
}
}
}
return 0;
} catch (err) {
ctx.logger && ctx.logger.warn && ctx.logger.warn(
`[stockWarehouse.getStockWarningQuantity] 读取库存预警数量失败 stockId=${normalizedStockId}: ${err && err.message}`
);
return 0;
}
}
/**
* 查询静态商品列表(仓库级)。
*
* 静态判定:商品最后一个收(INBOUND)/发(OUTBOUND)流水时间超过阈值小时数
* 即视为进入静态;无收发流水记录的商品以创建时间(create_at)为基准。
* 阈值优先取入参 hours,缺省读仓库配置 subject_config.stock_static_hours(默认 168 小时)。
*
* @param {Object} [options={}] 选项。
* @param {number} [options.warehouseId] 仓库ID,缺省取 ctx.user.store_id。
* @param {number} [options.hours] 静态时间阈值(小时),缺省读仓库配置。
* @param {number} [options.page=1] 页码。
* @param {number} [options.pageSize=20] 每页条数。
* @return {Promise<{list: Array<Object>, pagination: {page:number, pageSize:number, total:number, totalPages:number}}>}
* list 每项含 id/item_code/item_name/sku_property/stock_unit/store_id/quantity/locked_quantity/
* gross_weight/warning_quantity/create_at/last_flow_at/static_hours/is_static。
*/
async getStaticStockList(options = {}) {
const { ctx } = this;
const requestData = options && typeof options === 'object' ? options : {};
const warehouseId = Number(requestData.warehouseId || (ctx.user && ctx.user.store_id) || 0);
const page = Number(requestData.page || 1) > 0 ? Math.floor(Number(requestData.page)) : 1;
const pageSize = Number(requestData.pageSize || 20) > 0
? Math.min(500, Math.floor(Number(requestData.pageSize)))
: 20;
const emptyPagination = {
page,
pageSize,
total: 0,
totalPages: 0,
};
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
return { list: [], pagination: emptyPagination };
}
// 阈值小时数:入参优先,否则仓库配置(默认 168)
let staticHours = Number(requestData.hours);
if (!Number.isFinite(staticHours) || staticHours <= 0) {
staticHours = 168;
try {
const storeModel = ctx.model && ctx.model.Store;
if (storeModel && typeof storeModel.findByPk === 'function') {
const store = await storeModel.findByPk(warehouseId, {
attributes: [ 'id', 'subject_config' ],
raw: true,
});
const subjectConfig = store && store.subject_config ? store.subject_config : {};
const configHours = Number(subjectConfig.stock_static_hours || 0);
if (Number.isFinite(configHours) && configHours > 0) {
staticHours = configHours;
}
}
} catch (err) {
ctx.logger && ctx.logger.warn && ctx.logger.warn(
`[stockWarehouse.getStaticStockList] 读取仓库静态时间配置失败,按默认 168 小时: ${err && err.message}`
);
}
}
const cutoff = new Date(Date.now() - staticHours * 3600 * 1000);
const fromSql = `
FROM wms_stock_warehouse sw
LEFT JOIN (
SELECT stock_id, MAX(last_flow_at) AS last_flow_at
FROM (
SELECT stock_id, MAX(created_at) AS last_flow_at
FROM wms_stock_transaction
WHERE warehouse_id = :warehouseId
AND transaction_type = 'INBOUND'
GROUP BY stock_id
UNION ALL
SELECT stock_id, MAX(created_at) AS last_flow_at
FROM wms_stock_transaction
WHERE warehouse_id = :warehouseId
AND transaction_type = 'OUTBOUND'
GROUP BY stock_id
) flow_union
GROUP BY stock_id
) t ON t.stock_id = sw.id
WHERE sw.warehouse_id = :warehouseId
AND sw.is_valid = 'Y'
AND sw.deleted_at IS NULL
AND COALESCE(t.last_flow_at, sw.create_at) < :cutoff
`;
const listSql = `
SELECT sw.id, sw.item_code, sw.item_name, sw.sku_property, sw.stock_unit,
sw.store_id, sw.quantity, sw.locked_quantity, sw.gross_weight,
sw.warning_quantity, sw.create_at, t.last_flow_at
${fromSql}
ORDER BY COALESCE(t.last_flow_at, sw.create_at) ASC
LIMIT :limit OFFSET :offset
`;
const countSql = `
SELECT COUNT(1) AS total
${fromSql}
`;
const { QueryTypes } = ctx.model;
const baseReplacements = {
warehouseId,
cutoff,
};
const offset = (page - 1) * pageSize;
const [ countRows, listRows ] = await Promise.all([
ctx.model.query(countSql, {
replacements: baseReplacements,
type: QueryTypes.SELECT,
}),
ctx.model.query(listSql, {
replacements: { ...baseReplacements, limit: pageSize, offset },
type: QueryTypes.SELECT,
}),
]);
const total = Number(
(Array.isArray(countRows) && countRows.length > 0 ? countRows[0].total : 0) || 0
);
const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0;
const list = (Array.isArray(listRows) ? listRows : []).map(row => ({
id: Number(row && row.id || 0),
item_code: String(row && row.item_code || '').trim(),
item_name: String(row && row.item_name || '').trim(),
sku_property: String(row && row.sku_property || '').trim(),
stock_unit: String(row && row.stock_unit || '').trim(),
store_id: row && row.store_id != null ? Number(row.store_id) : 0,
quantity: Number(row && row.quantity || 0),
locked_quantity: Number(row && row.locked_quantity || 0),
gross_weight: Number(row && row.gross_weight || 0),
warning_quantity: Number(row && row.warning_quantity || 0),
create_at: row && row.create_at ? row.create_at : null,
last_flow_at: row && row.last_flow_at ? row.last_flow_at : null,
static_hours: staticHours,
is_static: true,
}));
return {
list,
pagination: {
page,
pageSize,
total,
totalPages,
},
};
}
}
module.exports = StockWarehouseService;

View File

@ -0,0 +1,17 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_stock_warehouse', 'warning_quantity', {
type: Sequelize.INTEGER(11),
allowNull: true,
defaultValue: 0,
comment: '库存预警数量',
after: 'locked_quantity',
});
},
async down(queryInterface) {
await queryInterface.removeColumn('wms_stock_warehouse', 'warning_quantity');
},
};

View File

@ -0,0 +1,131 @@
'use strict';
/**
* 库存盘点范围类型改造:盘点明细表支持「商品」与「库位」两种盘点范围行。
* 注:原计划时间戳 20260930100000 已被 add-packages-weight-to-wms-order-delivery 占用,
* 故本迁移使用 20260930110000 保证确定性排序。
*
* wms_stock_check_detail:
* 1. 新增 scope_type(盘点范围类型:goods=商品,location=库位)。
* 2. stock_id / item_code 改为可空(库位行无商品快照)。
* 3. 重新引入 location_id / location_code(库位行专用;商品行为空)。
* 4. 更新表注释。
* 5. 防御性合并历史重复明细(同 check_id+stock_id 保留 id 最大行,旧行作业记录重指向保留行)。
* 6. 新增唯一索引 uk_check_stock(check_id, stock_id) 与 uk_check_location(check_id, location_code)
* (MySQL 唯一索引允许多个 NULL:商品行 location_code=NULL、库位行 stock_id=NULL 互不干扰)。
*
* wms_stock_check_record:
* 1. 移除唯一索引 uk_detail_location(detail_id, location_code)。
* 2. 防御性合并重复(同 detail_id+stock_id+location_code 组保留 id 最大一条,raw SQL)。
* 3. 新增唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code)。
* 原因:按库位盘点时同一库位明细行下会有多个商品的记录,
* 覆盖式语义应升级为「同明细 + 同商品 + 同库位」。
*/
const DETAIL_TABLE_NAME = 'wms_stock_check_detail';
const RECORD_TABLE_NAME = 'wms_stock_check_record';
module.exports = {
up: async queryInterface => {
// ===== wms_stock_check_detail =====
// 1) 新增字段(raw SQL 保证列位置与注释精确)
await queryInterface.sequelize.query(`
ALTER TABLE \`${DETAIL_TABLE_NAME}\`
ADD COLUMN \`scope_type\` VARCHAR(20) NOT NULL DEFAULT 'goods' COMMENT '盘点范围类型:goods=商品,location=库位' AFTER \`warehouse_id\`,
ADD COLUMN \`location_id\` BIGINT(20) UNSIGNED NULL COMMENT '库位ID,关联 wms_location_space.id;库位盘点行为空' AFTER \`stock_id\`,
ADD COLUMN \`location_code\` VARCHAR(50) NULL COMMENT '库位编码(space_code);库位盘点行为空' AFTER \`location_id\`
`);
// 2) stock_id / item_code 改为可空
await queryInterface.sequelize.query(`
ALTER TABLE \`${DETAIL_TABLE_NAME}\`
MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NULL COMMENT '库存商品ID,关联 wms_stock_warehouse.id;库位盘点行为空',
MODIFY COLUMN \`item_code\` VARCHAR(50) NULL COMMENT '商品编码快照;库位盘点行为空'
`);
// 3) 更新表注释
await queryInterface.sequelize.query(
`ALTER TABLE \`${DETAIL_TABLE_NAME}\` COMMENT='库存盘点明细表(盘点范围行:商品或库位)'`
);
// 4) 防御性合并重复明细:同 (check_id, stock_id) 保留 id 最大行,旧行的作业记录重指向保留行
await queryInterface.sequelize.query(`
UPDATE \`${RECORD_TABLE_NAME}\` r
JOIN \`${DETAIL_TABLE_NAME}\` d ON r.detail_id = d.id
JOIN (
SELECT check_id, stock_id, MAX(id) AS keep_id
FROM \`${DETAIL_TABLE_NAME}\`
WHERE stock_id IS NOT NULL
GROUP BY check_id, stock_id
HAVING COUNT(*) > 1
) g ON g.check_id = d.check_id AND g.stock_id = d.stock_id AND d.id <> g.keep_id
SET r.detail_id = g.keep_id
`);
await queryInterface.sequelize.query(`
DELETE d FROM \`${DETAIL_TABLE_NAME}\` d
JOIN (
SELECT check_id, stock_id, MAX(id) AS keep_id
FROM \`${DETAIL_TABLE_NAME}\`
WHERE stock_id IS NOT NULL
GROUP BY check_id, stock_id
HAVING COUNT(*) > 1
) g ON g.check_id = d.check_id AND g.stock_id = d.stock_id AND d.id < g.keep_id
`);
// 5) 新增唯一索引
await queryInterface.addIndex(DETAIL_TABLE_NAME, [ 'check_id', 'stock_id' ], {
unique: true,
name: 'uk_check_stock',
});
await queryInterface.addIndex(DETAIL_TABLE_NAME, [ 'check_id', 'location_code' ], {
unique: true,
name: 'uk_check_location',
});
// ===== wms_stock_check_record =====
// 1) 移除旧唯一索引 uk_detail_location
await queryInterface.removeIndex(RECORD_TABLE_NAME, 'uk_detail_location');
// 2) 合并重复:同 (detail_id, stock_id, location_code) 组保留 id 最大一条
await queryInterface.sequelize.query(`
DELETE r1 FROM \`${RECORD_TABLE_NAME}\` r1
JOIN \`${RECORD_TABLE_NAME}\` r2
ON r1.detail_id = r2.detail_id
AND r1.stock_id = r2.stock_id
AND r1.location_code = r2.location_code
AND r1.id < r2.id
`);
// 3) 新增唯一索引 uk_detail_stock_location
await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'detail_id', 'stock_id', 'location_code' ], {
unique: true,
name: 'uk_detail_stock_location',
});
},
down: async queryInterface => {
// 回退 wms_stock_check_record
await queryInterface.removeIndex(RECORD_TABLE_NAME, 'uk_detail_stock_location');
await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'detail_id', 'location_code' ], {
unique: true,
name: 'uk_detail_location',
});
// 回退 wms_stock_check_detail
await queryInterface.removeIndex(DETAIL_TABLE_NAME, 'uk_check_location');
await queryInterface.removeIndex(DETAIL_TABLE_NAME, 'uk_check_stock');
await queryInterface.sequelize.query(
`ALTER TABLE \`${DETAIL_TABLE_NAME}\` COMMENT='库存盘点明细表(盘点商品清单)'`
);
await queryInterface.removeColumn(DETAIL_TABLE_NAME, 'location_code');
await queryInterface.removeColumn(DETAIL_TABLE_NAME, 'location_id');
await queryInterface.removeColumn(DETAIL_TABLE_NAME, 'scope_type');
await queryInterface.sequelize.query(`
ALTER TABLE \`${DETAIL_TABLE_NAME}\`
MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NOT NULL COMMENT '库存商品ID,关联 wms_stock_warehouse.id',
MODIFY COLUMN \`item_code\` VARCHAR(50) NOT NULL COMMENT '商品编码快照'
`);
},
};

View File

@ -0,0 +1,16 @@
'use strict';
module.exports = {
async up(queryInterface) {
// 静态商品查询优化:覆盖索引,支撑 warehouse_id + transaction_type 过滤、stock_id 分组、created_at 取 MAX
await queryInterface.addIndex(
'wms_stock_transaction',
[ 'warehouse_id', 'transaction_type', 'stock_id', 'created_at' ],
{ name: 'idx_wh_type_stock_time' }
);
},
async down(queryInterface) {
await queryInterface.removeIndex('wms_stock_transaction', 'idx_wh_type_stock_time');
},
};

View File

@ -0,0 +1,63 @@
'use strict';
const TABLE_NAME = 'wms_stock_static_notice';
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
if (exists) return;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
stock_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '商品ID,关联 wms_stock_warehouse.id',
},
notice_time: {
type: Sequelize.DATE,
allowNull: false,
comment: '通知时间',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
comment: '静态商品通知关联表(记录静态商品已通知时间,避免重复通知)',
});
// 核心查询:查某商品最近一次通知时间
await queryInterface.addIndex(TABLE_NAME, [ 'stock_id', 'notice_time' ], {
name: 'idx_stock_notice_time',
});
// 时间范围扫描:按通知时间清理/统计
await queryInterface.addIndex(TABLE_NAME, [ 'notice_time' ], {
name: 'idx_notice_time',
});
},
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -0,0 +1,63 @@
'use strict';
const TABLE_NAME = 'wms_stock_static_check_task';
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
if (exists) return;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
stock_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '商品ID,关联 wms_stock_warehouse.id',
},
task_time: {
type: Sequelize.DATE,
allowNull: false,
comment: '创建盘点任务时间(有记录即表示已为该静态商品创建过盘点任务)',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
comment: '静态商品盘点任务关联表(记录是否已为静态商品创建盘点任务,避免重复创建)',
});
// 核心查询:查某商品最近一次创建盘点任务时间
await queryInterface.addIndex(TABLE_NAME, [ 'stock_id', 'task_time' ], {
name: 'idx_stock_task_time',
});
// 时间范围扫描:按任务创建时间清理/统计
await queryInterface.addIndex(TABLE_NAME, [ 'task_time' ], {
name: 'idx_task_time',
});
},
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -0,0 +1,56 @@
'use strict';
/**
* 盘点主表时间字段调整:
* 1. 移除盘点日期 check_date(及其联合索引 idx_warehouse_check_date)——
* 创建任务不再传盘点时间,盘点时间线由 start_time/end_time 表达。
* 2. start_time(盘点开始时间:第一个盘点明细写入时间)与
* end_time(盘点结束时间:完成盘点时间)注释对齐新语义,类型不变。
*/
const TABLE_NAME = 'wms_stock_check';
module.exports = {
up: async (queryInterface, Sequelize) => {
const { DATE } = Sequelize;
// 先删索引再删列
await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_check_date');
await queryInterface.removeColumn(TABLE_NAME, 'check_date');
await queryInterface.changeColumn(TABLE_NAME, 'start_time', {
type: DATE,
allowNull: true,
comment: '盘点开始时间(第一个盘点明细写入的时间)',
});
await queryInterface.changeColumn(TABLE_NAME, 'end_time', {
type: DATE,
allowNull: true,
comment: '盘点结束时间(完成盘点的时间)',
});
},
down: async (queryInterface, Sequelize) => {
const { DATE } = Sequelize;
await queryInterface.addColumn(TABLE_NAME, 'check_date', {
type: DATE,
allowNull: false,
comment: '盘点日期',
});
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'check_date' ], {
name: 'idx_warehouse_check_date',
});
await queryInterface.changeColumn(TABLE_NAME, 'start_time', {
type: DATE,
allowNull: true,
comment: '实际开始时间',
});
await queryInterface.changeColumn(TABLE_NAME, 'end_time', {
type: DATE,
allowNull: true,
comment: '实际结束时间',
});
},
};

View File

@ -0,0 +1,40 @@
'use strict';
/**
* 库存盘点作业记录表支持未知商品(仿收货明细口径:stock_id 可空 + barcode + item_name):
*
* wms_stock_check_record:
* 1. stock_id 改为可空(NULL=未知商品;唯一索引 uk_detail_stock_location 中 NULL 不参与唯一约束,
* MySQL 语义允许多个 NULL 行,索引保持不动)。
* 2. 新增 barcode(扫描到的条码/编码,STRING(100) 可空,已知商品可为空)。
* 3. 新增 item_name(未知商品名称快照,缺省为条码,STRING(255) 可空,已知商品为空)。
*
* 未知商品无账面:盘点差异 = 实盘数量 - 0 = 盘盈;
* 覆盖式查重由应用层按(detail_id + stock_id IS NULL + barcode + location_code)保证。
*/
const TABLE_NAME = 'wms_stock_check_record';
module.exports = {
up: async queryInterface => {
await queryInterface.sequelize.query(`
ALTER TABLE \`${TABLE_NAME}\`
MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NULL COMMENT '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id;NULL=未知商品',
ADD COLUMN \`barcode\` VARCHAR(100) NULL COMMENT '扫描到的条码/编码(未知商品上报使用;已知商品可为空)' AFTER \`stock_id\`,
ADD COLUMN \`item_name\` VARCHAR(255) NULL COMMENT '未知商品名称快照(缺省为条码);已知商品为空' AFTER \`barcode\`
`);
},
down: async queryInterface => {
// 回退前先清理未知商品记录(stock_id 为 NULL 的行),保证恢复 NOT NULL 不失败
await queryInterface.sequelize.query(
`DELETE FROM \`${TABLE_NAME}\` WHERE \`stock_id\` IS NULL`
);
await queryInterface.removeColumn(TABLE_NAME, 'item_name');
await queryInterface.removeColumn(TABLE_NAME, 'barcode');
await queryInterface.sequelize.query(`
ALTER TABLE \`${TABLE_NAME}\`
MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NOT NULL COMMENT '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id'
`);
},
};

View File

@ -1,4 +1,408 @@
[
{
"version": "2026.10.02-system-platform-header-miniprogram",
"date": "2026-10-02",
"type": "updated",
"summary": "docs 全局 Header 的 platform 下拉修正:「微信端」取值由 wx 改为 miniprogram,并移除重复的「小程序端」(miniProgram)选项",
"methods": [
"/api/docs"
],
"notes": [
"依据:app/service/system.js#ALLOWED_PLATFORMS 含小写 miniprogram(校验前 toLowerCase,实际建议使用规范值);app/service/systems/wechat.js 登录链路 platform_code 兜底为 'miniprogram';接口日志实测客户端 platform 取值只有 web/pda/miniprogram,从未出现 wx/miniProgram。",
"文档变更范围:methods/system.json 根 headers 的 platform.list——「微信端」value 由 wx 改为 miniprogram,删除「小程序端」(value=miniProgram,与微信端同义且大小写与规范不一致);platform 描述示例补充 miniprogram;project 列表及其它 header 不变;根版本 0.3.226 → 0.3.227、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);所有 method 条目未改动。",
"库表维护源说明:wms_method_doc_meta.headers 与 version 同步更新后按 import→export 往返校验,保持库与文件一致。"
]
},
{
"version": "2026.10.02-stock-check-work-data-status-guard",
"date": "2026-10-02",
"type": "updated",
"summary": "workData 新增状态限制:仅 approved/checking 任务可拉取盘点作业数据,其他状态返回 400 并说明原因",
"methods": [
"stock.check.workData"
],
"notes": [
"代码依据:app/service/systems/stock_check.js#workData 在任务存在校验之后新增状态守卫——check.status 不在 REPORT_ALLOWED_STATUSES(approved/checking,与 report/finish 一致)内时抛 400(createBusinessError(message, 400)),文案『当前状态({STOCK_CHECK_STATUS_LABELS 中文标签,无标签回退状态值})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取』;本次仅同步文档,未改动任何代码(代码变更已通过 ESLint 与 193 条集成测试)。",
"状态限制口径:仅任务状态 approved(审核完成)或 checking(盘点作业中)可拉取盘点作业数据;created 已创建/submitted 待审核/rejected 已驳回/completed 已完成/cancelled 已取消 均返回 400;与 report(盘点作业上报,approved 首次上报自动转 checking)及 finish(完成盘点)使用同一 REPORT_ALLOWED_STATUSES 常量。",
"400 文案:盘点任务ID不能为空 / 视图类型非法(仅支持 location/goods/space)→ 当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取 → 盘点任务不存在(校验顺序:id → view → 任务存在 → 状态守卫)。",
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(errors 的 400 拆分三条并新增状态限制文案、description/notes 补充状态限制口径);根版本 0.3.225 → 0.3.226、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(NODE_ENV=production + --env production 双设置)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。"
]
},
{
"version": "2026.10.02-stock-check-work-data",
"date": "2026-10-02",
"type": "added",
"summary": "新增 stock.check.workData 盘点作业数据接口:一个接口按 view 入参驱动三种视图(location 库位结构含未知商品子列表;goods 商品列表按库位子列表;space 聚合库位列表按拣货路径排序),明盘显示数量、盲盘隐藏数量",
"methods": [
"stock.check.workData"
],
"notes": [
"代码依据:app/service/systems/stock_check.js#workData(id 非正整数抛 400『盘点任务ID不能为空』;view 非 location/goods/space 抛 400『视图类型非法(仅支持 location/goods/space)』;任务不存在(按 id+warehouse_id 查 wms_stock_check)抛 400『盘点任务不存在』;按 view 分派 _buildLocationWorkRows/_buildGoodsWorkRows/_buildSpaceWorkRows,统一返回 { check: _formatCheckRow 口径, rows, total: rows.length })+ app/service/systemMethods/stock/check.js#workData(warehouse_id 由服务端从 ctx.user.store_id 自动注入,前端无需传递);本次仅同步文档,未改动任何代码。",
"三视图口径:location=库位结构,以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位盘点作业记录——goods 已知商品子列表(stock_id 有值,商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名 _resolveStoreNameMap 解析、图片 image_url)与 unknown 未知商品子列表(stock_id 为空,输出记录快照 barcode/item_name/images,图片经 _attachRecordImages 挂载 FileReference business_type=stock_check_record);goods=商品结构,以任务商品范围行(scope_type=goods)为列表(按明细 id 升序),行内挂按库位聚合的 locations(空库位归 location_code=null 组,按首条记录 id 升序);space=聚合库位列表,以任务商品(scope_type=goods 的 stock_id 集合)所在库位为列表——wms_storage(warehouse_id + stock_id 在集合 + is_enabled=1 未删除)DISTINCT space_id,行内 goods 为该库位下的任务商品,未在 wms_storage 有库位的商品不入列表。",
"明盘/盲盘数量控制:明盘(mode=open)goods 视图行返回 system_quantity(明细账面快照)/checked_quantity(已盘合计=locations.quantity 合计)/diff_quantity(已盘-账面)/is_diff(差异非 0 为 1),locations 各项含 quantity(该库位实盘合计);space 视图 goods 各项含 system_quantity(wms_storage space+stock SUM(quantity) 账面)/checked_quantity(该商品在该库位的实盘合计);盲盘(mode=blind)不返回任何数量字段(goods 视图 locations 仅 location_code/checked_at/checker_name,space 视图 goods 仅商品信息+status);无作业记录时 locations 为空数组、明盘已盘合计/差异按 0(避免未盘行误显盘亏差异)。",
"排序口径:space 视图库位按拣货路径排序——pick_sequence 升序、pick_priority 降序、同值按库位 id 升序兜底;space 行内 goods 按 stock_id 升序;location/goods 视图行按明细 id 升序;goods 视图 locations 按首条记录 id 升序。",
"权限口径:随 ALL_METHOD_NAMES(20 个:create/list/addDetail/addLocationDetail/detailDelete/detail/result/workData/report/recordList/recordDelete/finish/submit/cancel/audit/batchDelete/export/exportTaskProgress/patternList/patternCreate)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(_noNeedAuth)、必须登录(isNeedLogin=true,免登录清单为空);为查询类方法,加入免日志清单 _noNeedLog(list/detail/result/workData/recordList/export/exportTaskProgress/patternList),不记录操作日志。",
"文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.workData 一条(位于 stock.check.result 之后);根版本 0.3.224 → 0.3.225、updatedAt 2026-10-01 → 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组由 19 条增至 20 条)。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(NODE_ENV=production + --env production 双设置)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。"
]
},
{
"version": "2026.10.01-stock-check-detail-delete-batch",
"date": "2026-10-01",
"type": "updated",
"summary": "detailDelete 支持批量删除:入参 detail_ids(兼容旧 detail_id 单值),返回改为 { deleted_count, deleted_ids, skipped_ids, total_items },未命中跳过不报错",
"methods": [
"stock.check.detailDelete"
],
"notes": [
"代码依据:app/service/systems/stock_check.js(detailDelete:id 非法抛 400『盘点任务ID不能为空』、任务不存在抛 400『盘点任务不存在』、状态非 created/rejected 抛 400『当前状态(xxx)不允许删除明细』、_normalizeIdList 归一化(单值自动转数组、去重、仅保留正整数)后为空抛 400『请至少选择一个明细』、超过 200 抛 400『单次最多删除 200 条明细』;按 id in ids + check_id + warehouse_id 仓库隔离查询,未命中 ID 计入 skipped_ids 不报错;命中明细批量 destroy 并防御性清理 wms_stock_check_record,重算主表 total_items;返回 { deleted_count, deleted_ids, skipped_ids, total_items },deleted_ids/skipped_ids 保持入参顺序)+ app/service/systemMethods/stock/check.js(detailDelete 入参改为 detail_ids 数组,兼容 detailIds 驼峰与旧 detail_id 单值,优先级 detail_ids > detailIds > detail_id,单值自动转数组);本次仅同步文档,未改动任何代码。",
"批量口径:单次上限 200;单值自动转数组并去重;未命中的明细ID计入 skipped_ids 不报错;命中批量删除并防御清理作业记录(正常流程 created/rejected 不应有记录);删除后重算 total_items;deleted_ids/skipped_ids 保持入参顺序。",
"响应结构变更(兼容性影响):由旧版 { detail_id, deleted, total_items } 变更为 { deleted_count, deleted_ids, skipped_ids, total_items },旧前端需按新结构适配。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.detailDelete(params 改为 detail_ids 数组+兼容字段 detailIds/detail_id、response 改为批量结构、errors 同步批量文案、description/notes 同步);根版本 0.3.223 → 0.3.224、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动(stock.check 分组仍为 19 条)。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(NODE_ENV=production + --env production 双设置)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 19 条 method 无损。"
]
},
{
"version": "2026.10.01-stock-check-add-detail-location-ids",
"date": "2026-10-01",
"type": "updated",
"summary": "addDetail 支持 location_ids 按库位ID直查添加(与 stock_ids 按任务类型区分维度),addLocationDetail 转调 addDetail 保留兼容",
"methods": [
"stock.check.addDetail",
"stock.check.addLocationDetail"
],
"notes": [
"代码依据:app/service/systems/stock_check.js(addDetail 新增 locationIds 入参与 _addLocationRowsByIds 库位ID直查路径、addLocationDetail 薄封装转调 addDetail 并映射返回结构)+ app/service/systemMethods/stock/check.js(addDetail/addLocationDetail 新增 location_ids 入参并兼容 locationIds 驼峰,location_ids 优先);本次仅同步文档,未改动任何代码。",
"分派口径:addDetail 按任务盘点类型区分维度——type=store/goods 接受 stock_ids(传 locations 报 400『当前盘点类型按商品盘点,请传 stock_ids』、传 location_ids 报 400『当前盘点类型按商品盘点,不能添加库位明细』);type=all/location 接受 locations 或 location_ids(传 stock_ids 报 400『当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)』)。",
"ID 直查与幂等口径:location_ids 优先于 locations(两者都传时 locations 忽略),按 wms_location_space.id+warehouse_id 直查校验(不再按 space_code 二次解析),查不到的 ID 记入新增返回字段 invalid_location_ids(不报错);幂等按 check_id+location_code(uk_check_location 唯一索引),location_ids 路径跳过项按库位ID记入 skipped;商品行幂等仍按 uk_check_stock。",
"兼容说明:addLocationDetail 保留旧接口名与返回结构 { added, skipped, invalid_location_ids, total_items },薄封装转调 addDetail 库位ID直查路径(stockIds/locations 置空、传 locationIds),返回结构过滤 invalid_locations/invalid_stock_ids;转发前保留旧口径参数校验(任务ID不能为空、库位ID不能为空、单次上限 200)。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.addDetail(params 新增 location_ids、response 新增 invalid_location_ids、description/errors/notes 同步新口径)并新增 stock.check.addLocationDetail 一条(此前未登记,分组由 18 条增至 19 条);根版本 0.3.222 → 0.3.223、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 19 条 method 无损。"
]
},
{
"version": "2026.10.01-stock-check-unknown-goods",
"date": "2026-10-01",
"type": "updated",
"summary": "盘点作业上报支持未知商品(stock_id 可空 + barcode/item_name,仿收货明细);图片独立维护(上传 businessType=stock_check_record,查询挂载 images,删除清理)",
"methods": [
"stock.check.report",
"stock.check.result",
"stock.check.recordList",
"stock.check.recordDelete",
"stock.check.export"
],
"notes": [
"代码依据:app/service/systems/stock_check.js(report/_resolveStockIdByBarcode/result/_buildDetailAggregations/_formatDetailAggregationRow/_attachRecordImages/recordList/recordDelete/exportStockChecks/_generateAndUploadStockCheckExcel)+ app/service/systemMethods/stock/check.js(report 新增入参 barcode/item_name 透传);未改动任何业务代码之外的逻辑。",
"迁移依据:database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js(wms_stock_check_record:stock_id 改可空(NULL=未知商品,唯一索引 uk_detail_stock_location 中 NULL 不参与唯一约束)+ 新增 barcode VARCHAR(100) 可空/item_name VARCHAR(255) 可空),本地与生产均已执行。",
"未知商品上报口径:report 新增入参 barcode/item_name;stock_id 与 barcode 至少传一项——仅传 barcode 先按条码匹配系统商品(wms_stock_barcodes 按 barcode+本仓库,关联 StockWarehouse 校验商品属于本仓库),命中回填 stock_id 走已知商品逻辑(商品明细行校验与明细商品一致),未命中记录未知商品(stock_id=NULL+barcode+item_name,item_name 缺省为 barcode);都未传沿用原报错口径;未知商品覆盖式查重 where { detail_id, stock_id:null, barcode, location_code }(应用层查重,唯一索引不约束 NULL 行,并发兜底逻辑对未知商品同样降级更新)。",
"差异口径:未知商品账面 0,实盘=盘盈(差异=实盘-0),必然计入 diff_items;result 行级新增 unknown_items [{ barcode, item_name, checked_quantity }](stock_id 为空的记录按条码归组、条码升序,已计入行级 checked_quantity/diff_quantity/is_diff);finish 未知商品实盘>0 计入盘盈合计与差异行数。",
"图片独立维护口径:上传走通用上传接口(businessType='stock_check_record' + businessId=作业记录ID,建 FileReference,仿收货 receivingItem);result 的 records 与 recordList 的 rows 每条挂载 images [{ id, url }](wms_file_reference 关联 wms_file.file_url,无图片返回空数组);recordDelete 删除记录后清理关联图片引用(失败仅告警不影响主流程);report 不接收图片。",
"查询/导出显示口径:recordList 与 export Sheet2 未知商品(stock_id 为空)item_code 显示扫描条码(barcode)、item_name 显示上报名称快照(item_name 或 barcode 兜底);已知商品维持原口径(明细表/wms_stock_warehouse 商品快照)。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.report/result/recordList/recordDelete/export 五条(report 新增 params barcode/item_name、response record 补充 barcode/item_name/stock_id 可空;result 新增 response unknown_items 与 records.images;recordList 补充 rows barcode/item_name/images 口径;export 补充 Sheet2 未知商品列口径;recordDelete 补充图片清理说明);根版本 0.3.221 → 0.3.222、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 13 条 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。"
]
},
{
"version": "2026.10.01-stock-check-detail-stock-mount",
"date": "2026-10-01",
"type": "updated",
"summary": "stock.check.detail 商品行新增挂载 stock 对象(stockWarehouse.getStockDetails 全局商品信息:条码/图片/管理标识等,带缓存),库位行不挂载",
"methods": [
"stock.check.detail"
],
"notes": [
"代码依据:app/service/systems/stock_check.js#detail(对 scope_type=goods 行按 stock_id 去重后批量调用 ctx.service.systems.stockWarehouse.getStockDetails(goodsStockIds, { warehouseId }),结果按 stock_id 挂载到各行 stock 字段,未命中为 null;库位行不挂载)与 app/service/systems/storage/stock_warehouse.js#getStockDetails(带缓存批量取商品详情,key=cache:stock_detail:{warehouseId}:{stockId},默认 TTL 300 秒);未改动任何业务代码。",
"挂载口径:stock 为 wms_stock_warehouse 全局商品信息,含 id/item_code/item_name/sku_property/quantity 库存数量/locked_quantity 锁定数量/is_batch_mgmt 批次管理/is_shelf_life_mgmt 效期管理/image_url 商品图片/is_images/need_recheck 是否需要复核/store_id 货主ID/packing_requirements 打包要求/pick_requirements 拣货要求/recheck_requirements 复核要求/merge_requirements 要求合并开关/stock_unit 库存单位/barcodes 条码数组;仅 scope_type=goods 商品行挂载(未命中 stock=null),scope_type=location 库位行不挂载;范围行原有 15 字段与其余返回结构不变。",
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.detail 一条(description/response.rows/notes 补充商品行 stock 挂载口径);根版本 0.3.220 → 0.3.221、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。"
]
},
{
"version": "2026.10.01-stock-check-list-store-name",
"date": "2026-10-01",
"type": "updated",
"summary": "stock.check.list 返回行新增 store_name 货主名称(合约货主备注 store_remask 优先、公司全称 company_name 兜底)",
"methods": [
"stock.check.list"
],
"notes": [
"代码依据:app/service/systems/stock_check.js#list(返回前调用 _resolveStoreNameMap() 批量解析货主名称,每行新增 store_name 字段)与 #_resolveStoreNameMap(货主名称解析方法);未改动任何业务代码。",
"解析口径:优先 wms_store_warehouse.store_remask(合约货主备注,按 store_id+warehouse_id 匹配);无合约或备注为空时回退 wms_store.company_name(公司全称);两者均查不到时返回空字符串 ''。",
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.list 一条(response.rows 描述新增 store_name 货主名称与解析口径,description/notes 同步;params/errors/headers/鉴权不变);根版本 0.3.219 → 0.3.220、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。"
]
},
{
"version": "2026.10.01-stock-check-list-filters",
"date": "2026-10-01",
"type": "updated",
"summary": "stock.check.list 查询条件扩展:修复 type 筛选不生效,新增 mode/货主 store_id/创建时间 created_at/盘点开始时间 start_time/盘点结束时间 end_time 筛选(时间支持单值 gte 与 [from,to] 区间)",
"methods": [
"stock.check.list"
],
"notes": [
"代码依据:app/service/systems/stock_check.js#list(新增 type/mode 枚举筛选与 created_at/start_time/end_time 时间筛选,status/store_id/keyword 已有不变)与 app/service/systemMethods/stock/check.js#list(prepareWhereContext 提取 where,支持 {operator,value} 标准结构);未改动任何业务代码。",
"修复点:原方法层 list 未从 where 提取 type(where.type 传入不生效);本次方法层补齐 type/mode/created_at/start_time/end_time 提取(whereValue 优先、data 顶层字段兜底兼容),status/keyword 已有逻辑不变。",
"筛选口径:status/type/mode 单值 eq、数组 in(归一化去重);store_id 数值 eq;keyword 对 check_no/title 模糊匹配;全部筛选叠加仓库隔离(ctx.user.store_id)。",
"时间范围语义:created_at/start_time/end_time 口径一致——单值=gte 从该值起;[from,to] 两端合法=between 闭区间、仅 from=gte、仅 to=lte;非法时间值静默忽略。",
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.list 一条(params 新增 where.type/where.mode/where.created_at/where.start_time/where.end_time);根版本 0.3.218 → 0.3.219、updatedAt 更新为 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;写入 JSON 后同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。"
]
},
{
"version": "2026.09.30-stock-check-time-fields",
"date": "2026-09-30",
"type": "updated",
"summary": "盘点主表移除盘点日期 check_date,改用 start_time(第一个盘点明细写入时间)/end_time(完成盘点时间)表达盘点时间线;导出 Sheet1 移除盘点日期列",
"methods": [
"stock.check.create",
"stock.check.patternCreate",
"stock.check.report",
"stock.check.finish",
"stock.check.detail",
"stock.check.result",
"stock.check.list",
"stock.check.export"
],
"notes": [
"代码依据:app/service/systems/stock_check.js——create/patternCreate 不再写 check_date;_formatCheckRow 不再返回 check_date(保留 start_time/end_time);report 首次写入明细时主表 start_time 为空则补写(盘点开始时间=第一个盘点明细写入的时间);finish 写 end_time(盘点结束时间=完成盘点的时间);_generateAndUploadStockCheckExcel 的 Sheet1 表头已移除「盘点日期」列(保留开始时间/结束时间列)。",
"迁移文件:database/migrations/20260930150000-remove-check-date-from-wms-stock-check.js——移除 wms_stock_check 的 check_date 字段与 idx_warehouse_check_date 联合索引,start_time/end_time 注释对齐新语义(类型不变);本地与生产均已执行。",
"语义口径:盘点时间线由 start_time/end_time 表达——start_time=盘点开始时间(第一个盘点明细写入的时间,report 首次写入明细时补写)、end_time=盘点结束时间(完成盘点的时间,finish 时写入);create/patternCreate 均不传盘点时间。",
"接口兼容性影响:create/patternCreate 响应移除 check_date 字段(主表已无该字段);detail/result/list 返回主表行的字段清单移除 check_date;finish 响应结构不变(不返回 end_time,语义体现在主表回填与 description);export Sheet1 列移除「盘点日期」(保留开始/结束时间列);入参、errors、headers、鉴权(isNeedAuth=false、isNeedLogin=true)均不变;未改动任何业务代码。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 8 条(create/patternCreate/report/finish/detail/result/list/export);根版本 0.3.217 → 0.3.218、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 10 条 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。"
]
},
{
"version": "2026.09.30-stock-check-create-no-date",
"date": "2026-09-30",
"type": "updated",
"summary": "create 移除 check_date 入参,盘点日期固定为今天(与 patternCreate 口径一致)",
"methods": [
"stock.check.create"
],
"notes": [
"代码依据:app/service/systems/stock_check.js#create——入参解析已无 check_date(仅 warehouseId/title/type/mode/storeId/remark/creatorId/creatorName),checkDateValue = new Date() 后 setHours(0,0,0,0) 固定今天 00:00:00 写入主表 check_date;app/service/systemMethods/stock/check.js#create——data 解构已无 check_date,JSDoc 同步「盘点日期固定为今天,前端不传」;与 patternCreate 口径一致(systems 层 #patternCreate 同样 setHours(0,0,0,0) 固定今天)。",
"规则口径:盘点日期固定为今天 00:00:00,前端不传 check_date(响应中仍返回 check_date 字段);创建后主表 status=created、detail_status=none_checked,其余创建口径(单号生成、范围类型语义、盘点方式规则)均不变。",
"接口兼容性影响:params 移除 check_date(原为必填项,现前端不传;若前端仍传会被方法层忽略,不影响接口可用性与既有调用);errors 400 文案移除「盘点日期不能为空且格式必须合法」;headers/response 结构/鉴权(isNeedAuth=false、isNeedLogin=true)均不变;未改动任何业务代码。",
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.create 一条(params 移除 check_date、description/notes/errors 同步口径);根版本 0.3.216 → 0.3.217、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。"
]
},
{
"version": "2026.09.30-stock-check-location-blind-only",
"date": "2026-09-30",
"type": "updated",
"summary": "create 按库位盘点(all/location)一律盲盘,忽略前端传入的 mode;按商品盘点(store/goods)仍按传入值",
"methods": [
"stock.check.create"
],
"notes": [
"代码依据:app/service/systems/stock_check.js#create——normalizedType 校验通过后,type 为 all/location 时强制 normalizedMode='blind'(忽略前端传入的 mode);type 为 store/goods 时保持传入值(缺省 open);method 层 JSDoc 已同步该口径(按库位盘点一律盲盘)。",
"规则口径:按库位盘点(type=all/location,明细为库位行 scope_type=location)一律盲盘(blind),前端传入的 mode 不生效;按商品盘点(type=store/goods,明细为商品行 scope_type=goods)按传入值,默认明盘(open)。",
"接口兼容性影响:mode 仍为可选字符串参数(open/blind),入参结构、必填项、响应结构、errors、headers、鉴权(isNeedAuth=false、isNeedLogin=true)均不变;仅 all/location 场景服务端强制覆盖 mode 为 blind(前端传 blind 行为不变,传 open 落库值为 blind),对既有调用完全兼容。",
"文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.create 一条(mode 参数描述补充规则、notes 补充规则说明);根版本 0.3.215 → 0.3.216、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);未改动任何业务代码。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。"
]
},
{
"version": "2026.09.30-stock-check-pattern-fixed-mode",
"date": "2026-09-30",
"type": "updated",
"summary": "patternCreate 移除 mode/check_date 入参:库位类定式一律盲盘、商品类定式一律明盘,盘点日期固定为今天",
"methods": [
"stock.check.patternCreate"
],
"notes": [
"代码依据:app/service/systemMethods/stock/check.js#patternCreate(入参仅 pattern_id/patternId 驼峰别名/title/remark,不再解析 mode/check_date)+ app/service/systems/stock_check.js#patternCreate(normalizedMode=pattern.type==='location'?'blind':'open';checkDateValue=new Date() 后 setHours(0,0,0,0) 固定今天;主表 mode/check_date 直接取服务端固定值)。",
"固定规则:库位类定式(type=location,即 empty_location)一律盲盘(blind)、商品类定式(type=goods,其余 4 个定式)一律明盘(open);盘点日期固定为今天 00:00:00;前端不再传 mode/check_date。",
"接口兼容性影响:params 移除 mode/check_date 两个可选参数(前端若仍传会被忽略,不影响接口可用性与既有调用);errors 400 文案移除「盘点方式不合法,仅支持 open/blind」与「盘点日期格式不合法」;headers/response 结构/鉴权(isNeedAuth=false、isNeedLogin=true)均不变。",
"文档变更范围:methods/system.json 的 stock.check.patternCreate 条目更新(description/params/errors/notes);根版本 0.3.214 → 0.3.215、updatedAt 保持 2026-09-30;methods/changes/system.json 插入本条(数组首位);未改动任何业务代码。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。"
]
},
{
"version": "2026.09.30-stock-check-patterns",
"date": "2026-09-30",
"type": "added",
"summary": "新增定式快速创建盘点任务:patternList 拉取 5 个注册定式(空库位/错发/临期/静态/预警),patternCreate 按定式 id 收集对象创建盘点任务并直接进入待审核(submitted);静态盘点写入 wms_stock_static_check_task 并排除已盘商品",
"methods": [
"stock.check.patternList",
"stock.check.patternCreate"
],
"notes": [
"代码依据:app/service/systems/stock_check_patterns.js(STOCK_CHECK_PATTERNS 注册 5 个定式 empty_location/mis_shipment/expiring/static/warning,collectEmptyLocation/collectMisShipment/collectExpiring/collectStatic/collectWarning 五个收集函数)+ app/service/systems/stock_check.js#patternList/#patternCreate(收集对象、创建主表 status=submitted、写明细、static 写 wms_stock_static_check_task)+ app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 扩为 18 个含 patternList/patternCreate;patternList 在免日志清单 _noNeedLog;warehouseId/创建人从登录上下文注入;统一 _call 捕获业务错误码)。",
"5 个定式口径(与 stock_check_patterns.js 代码注释一致):空库位=启用且未删除、在 wms_storage 不存在 quantity>0 库存的账面空库位(type=location,其余为 goods);错发=登记过错发工单(wms_after_sale type=order+sub_type=mis_shipment,排除 closed/cancelled)关联订单商品按 stock_id 去重;临期=开启保质期管理且最早到期日 <= 当前时间+remaining_threshold_days 天(阈值 <=0 按已到期)的商品;静态=最后一次 INBOUND/OUTBOUND 流水距今超过 stock_static_hours 小时(默认 168,无流水按建档时间)且未进入 wms_stock_static_check_task 的商品;预警=quantity < stock_warning_quantity 的商品(需仓库配置 stock_warning_enabled=true,未开启报 400「未开启库存预警」)。",
"状态口径:patternCreate 创建后主表 status 直接 submitted(进入待审核)、detail_status=none_checked、total_items 按明细重算,无需再调 stock.check.submit;无符合条件对象报 400(location 型报「当前仓库没有账面为空的库位」,goods 型报「没有符合条件的商品」)。",
"静态记录表口径:收集阶段排除 wms_stock_static_check_task 已有记录(未删除)的 stock_id(已进入静态已盘点商品);任务创建成功后把命中 stock_id 批量写入该表(task_time=创建时间),写入失败仅告警不影响主流程。",
"权限口径:两个新 method 均随 ALL_METHOD_NAMES(18 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权,必须登录(isNeedLogin=true);patternList 为查询类在免日志清单(_noNeedLog)不记操作日志,patternCreate 为写操作保留操作日志。",
"文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.patternList/patternCreate 两条(追加在 exportTaskProgress 之后,与代码 ALL_METHOD_NAMES 顺序一致);根版本 0.3.213 → 0.3.214、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);未改动任何业务代码。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。"
]
},
{
"version": "2026.09.30-stock-check-operation-log",
"date": "2026-09-30",
"type": "updated",
"summary": "库存盘点 10 个写操作补齐业务操作日志:成功路径写入 wms_operation_log(businessType=stock_check,operationCode STOCK_CHECK_*),失败不写、日志异常不影响主流程",
"methods": [
"stock.check.create",
"stock.check.addDetail",
"stock.check.detailDelete",
"stock.check.report",
"stock.check.recordDelete",
"stock.check.finish",
"stock.check.submit",
"stock.check.cancel",
"stock.check.audit",
"stock.check.batchDelete"
],
"notes": [
"代码依据:app/service/systems/stock_check.js 的 10 个写操作(create/addDetail/detailDelete/report/recordDelete/finish/submit/cancel/audit/batchDelete)在主流程写入成功后调用 ctx.service.systems.operationLog.createOperationLog 写入 wms_operation_log(businessType=stock_check);operationCode 前缀 STOCK_CHECK_*,对应 CREATE/ADD_DETAIL/DELETE_DETAIL/REPORT/DELETE_RECORD/FINISH/SUBMIT/CANCEL/AUDIT/BATCH_DELETE;operationAction 对应 CREATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/DELETE。",
"日志口径:businessId=盘点任务 id(create 取新建记录 plainRecord.id,其余取 checkId);operator 取登录上下文 ctx.user(id=employees_id 回退 user.id,name=employees_name);extras 统一携带 warehouseId、checkNo(create 用 plainRecord.check_no)与 message,report/finish/audit/batchDelete 等另带业务关键字段(明细/库位/实盘数量、差异/盘盈/盘亏、审核动作与原因、deletedIds/skippedIds 等);changeSummary 为中文变更描述。",
"batchDelete 特殊口径:仅删除集非空(deletedIds.length>0)时写日志(全跳过不写);businessId 取首个删除 id(deletedIds[0]);extras 附 deletedIds/skippedIds/deletedCount/skippedCount;日志在事务提交后写入,不随事务回滚残留。",
"失败不写与降级:10 个日志调用点全部位于主流程成功路径之后(各写操作失败时先抛业务错误码 400,不会执行到日志写入);createOperationLog 内部 try/catch,日志写入失败仅记录 error 日志并返回 null,不影响主流程(业务已提交的变更不受日志失败影响)。",
"接口契约不变:本次仅服务层行为变更(补充业务操作日志),10 个 method 的入参/响应/错误码/鉴权均未变化,methods/system.json 接口条目与根版本号均不修改(不 bump);本条仅追加到 methods/changes/system.json 数组首位;changes 不入库表,无需回填 wms_api_method_doc。"
]
},
{
"version": "2026.09.30-stock-check-doc-polish",
"date": "2026-09-30",
"type": "updated",
"summary": "盘点接口文档文案修正:detail 字段计数 14→15、result 权限注释方法数 15→16、recordList/detailDelete 免日志清单补 result、export errors 补「未找到可导出的盘点任务」400",
"methods": [
"stock.check.detail",
"stock.check.result",
"stock.check.recordList",
"stock.check.detailDelete",
"stock.check.export"
],
"notes": [
"修正点明细:① stock.check.detail 的 description/response/notes 中「纯范围行 14 字段」改为「15 字段」(_formatDetailScopeRow 实际枚举 id/check_id/warehouse_id/scope_type/stock_id/location_id/location_code/item_code/item_name/spec/batch_no/system_quantity/remark/created_at/updated_at 共 15 个,枚举清单原本完整,仅计数文案错误);② stock.check.result notes 首条「随 ALL_METHOD_NAMES(15 个)免 API 权限」改为「16 个」;③ stock.check.recordList 与 stock.check.detailDelete 的免日志清单枚举补 result;④ stock.check.export errors 补 400「未找到可导出的盘点任务」。",
"代码依据:app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 共 16 个:create/list/addDetail/detailDelete/detail/result/report/recordList/recordDelete/finish/submit/cancel/audit/batchDelete/export/exportTaskProgress;_noNeedLog='list,detail,result,recordList,export,exportTaskProgress';export 超 50 上限校验)+ app/service/systems/stock_check.js#_formatDetailScopeRow(15 字段返回对象)与 #exportStockChecks(checks.length===0 时抛「未找到可导出的盘点任务」400)。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.detail/result/recordList/detailDelete/export 五条;根版本 0.3.212 → 0.3.213、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);仅文档文案与错误码清单修正,未改动任何业务代码。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。"
]
},
{
"version": "2026.09.30-wavePickTaskDetail-pick-requirements",
"date": "2026-09-30",
"type": "updated",
"summary": "pick.wavePickTaskDetail 的 picking_view.items 新增 pick_requirements(拣货要求),团购形态(pick_mode=1/5)不返回 picking_details,前端改由 items 展示拣货要求",
"methods": [
"pick.wavePickTaskDetail"
],
"notes": [
"代码依据:app/service/systems/pick.js#buildPickingView——items 聚合行新增 pick_requirements,取值自商品资料链路(getStockDetails)的 stock.pick_requirements(merge_requirements=Y 时已按打包要求回退),空值兜底为空字符串。",
"背景:团购小波次/大波次(pick_mode=1/5)不返回 picking_details,此前 picking_view.items 缺拣货要求字段,前端无法展示拣货要求。",
"picking_view.items 其余字段不变;picking_details 的 stock 对象本就含该字段,本次仅补齐 items 层。",
"文档变更范围:methods/system.json 的 pick.wavePickTaskDetail 响应 picking_view.items 新增 pick_requirements 字段描述;根版本 0.3.211 → 0.3.212、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位)。"
]
},
{
"version": "2026.09.30-stock-check-batch-delete",
"date": "2026-09-30",
"type": "added",
"summary": "新增 stock.check.batchDelete:批量删除盘点任务(入参 ids,上限 200),仅作废(cancelled)任务删除,非作废任务跳过;级联删除作业记录与明细(事务)",
"methods": [
"stock.check.batchDelete"
],
"notes": [
"代码依据:app/service/systems/stock_check.js#batchDelete(入参归一化 _normalizeIdList:单值兼容、去重、正整数过滤、上限 200;仓库隔离查询主表 id in ids + warehouse_id;状态分流与级联删除事务)+ app/service/systemMethods/stock/check.js#batchDelete(ALL_METHOD_NAMES 扩为 16 个含 batchDelete;warehouseId 从登录上下文注入;走统一 _call 捕获业务错误码)。",
"状态分流口径:仅 status=cancelled(作废)任务执行删除;其他状态及仓库内查不到的任务跳过(计入 skipped_ids,保持入参顺序),不报错。",
"级联删除顺序(事务内):先删作业记录(wms_stock_check_record where check_id in 删除集),再删明细(wms_stock_check_detail where check_id in 删除集),最后删主表(wms_stock_check where id in 删除集)。",
"权限口径:batchDelete 随 ALL_METHOD_NAMES(16 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(免鉴权清单)、必须登录(isNeedLogin=true);为写操作,不在免日志清单 _noNeedLog,保留操作日志。",
"文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.batchDelete(插入 audit 之后,与代码 ALL_METHOD_NAMES 顺序一致);根版本 0.3.210 → 0.3.211、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。"
]
},
{
"version": "2026.09.30-wavePickTaskDetail-pick-mode-enum",
"date": "2026-09-30",
"type": "updated",
"summary": "pick.wavePickTaskDetail 响应 task.pick_mode 描述补全枚举:1-团购小波次 2-散单单品单件 3-散单先拣后分 4-边拣边分 5-团购大波次",
"methods": [
"pick.wavePickTaskDetail"
],
"notes": [
"原描述仅「拣货模式」,缺少 pick_mode=5 为大团购(团购大波次)的枚举说明;现与 pick.query、order.recheckOrder 等接口的 pick_mode 描述对齐。",
"仅更新 methods/system.json 的 pick.wavePickTaskDetail 响应字段描述,不修改任何业务实现。"
]
},
{
"version": "2026.09.30-stock-check-export-records",
"date": "2026-09-30",
"type": "updated",
"summary": "盘点导出口径调整:Sheet2 导出盘点明细(作业记录:一行一条实际盘点记录,含商品/库位/实盘数量/盘点人/时间),不再导出任务明细(未盘范围行)",
"methods": [
"stock.check.export"
],
"notes": [
"代码依据:app/service/systems/stock_check.js#exportStockChecks/_generateAndUploadStockCheckExcel——Sheet2 直接拉 wms_stock_check_record 作业记录(不按任务范围行展开,任务明细与未盘范围行不导出),商品快照(item_code/item_name)从 wms_stock_warehouse 补齐,totalCount=作业记录总数;app/service/systemMethods/stock/check.js#export 异步任务入口与 Redis 进度缓存机制不变。",
"口径变化:Sheet2「盘点明细」由「按任务范围行展开(含未盘空行,账面按 wms_storage 现算)」改为「一行一条实际盘点记录(作业记录)」——列:盘点单号/商品编码/商品名称/库位编码(空库位输出为空)/实盘数量/盘点人/盘点时间;未盘的任务范围行不再导出;进度 totalCount=作业记录总数(导出前即确定),进度按已写明细行数/总数计算。",
"Sheet1 不变说明:Sheet1「盘点单」保持一行一个盘点任务(盘点单号/盘点名称/盘点范围/盘点方式/盘点状态/盘点进度/盘点日期/货主ID/创建人/明细行数/已盘行数/差异行数/开始时间/结束时间/备注)。",
"文档变更范围:methods/system.json 的 stock.check.export 更新 description/response(total_count/current_count 口径)/notes;根版本 0.3.208 → 0.3.209、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。"
]
},
{
"version": "2026.09.30-stock-check-detail-result-split",
"date": "2026-09-30",
"type": "updated",
"summary": "任务明细与盘点结果接口拆分:detail 只返回任务范围行(商品/库位),新增 result 返回盘点结果聚合(商品行 checked/diff/records/locations,库位行 stocks 按商品聚合账面查 wms_storage)",
"methods": [
"stock.check.detail",
"stock.check.result"
],
"notes": [
"代码依据:app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 扩为 15 个含 result;新增 result() 从登录上下文注入 warehouseId、入参 id、走统一 _call 捕获业务错误码;_noNeedLog 扩为 list/detail/result/recordList/export/exportTaskProgress)+ app/service/systems/stock_check.js(detail() 改为只返回纯范围行(_formatDetailScopeRow 14 字段,不再调 _buildDetailAggregations);新增 result() 查询全部明细与作业记录后调 _buildDetailAggregations/_formatDetailAggregationRow 聚合)。",
"拆分口径:detail 只返回任务范围行(商品/库位原始字段 14 个,不含任何盘点作业聚合);新增 result 返回盘点结果聚合——商品行 checked_quantity/diff_quantity/is_diff/status/location_codes/checkers/last_checked_at + records + locations,库位行 checked_quantity(行级合计)/diff_quantity(差异代数和)+ records/locations + stocks(按商品聚合,账面查 wms_storage)。",
"接口兼容性影响:旧 detail 的商品行聚合字段(checked_quantity/diff_quantity/is_diff/status/location_codes/checkers/last_checked_at)、records、locations 与库位行 stocks 全部迁移到新接口 result;detail 仅用于任务范围行展示,需要盘点结果的调用方改调 stock.check.result(入参同为 id,返回同为 { check, rows, total })。",
"权限口径:result 随 ALL_METHOD_NAMES(15 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(免鉴权清单)、必须登录(isNeedLogin=true);为查询类方法,加入免日志清单 _noNeedLog。",
"文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.result(放在 detail 之后,与代码 ALL_METHOD_NAMES 顺序一致)、更新 stock.check.detail 的 description/response/notes(纯范围行 14 字段,移除聚合字段描述);根版本 0.3.207 → 0.3.208、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。"
]
},
{
"version": "2026.09.30-stock-check-add-detail-compat",
"date": "2026-09-30",
"type": "updated",
"summary": "addDetail 兼容历史任务:type=all 且已存在商品明细行(改造前创建)时继续按商品模式接受 stock_ids,避免旧调用 400;全新 type=all 任务维持按库位语义",
"methods": [
"stock.check.addDetail"
],
"notes": [
"代码依据:app/service/systems/stock_check.js#addDetail——type=all 且 wms_stock_check_detail 已存在 scope_type='goods' 明细行(count>0)时置 isGoodsScope=true/isLocationScope=false,继续按商品模式接受 stock_ids;全新 type=all 任务维持按库位语义;入参维度互斥校验的库位错误文案更新为『当前盘点类型按库位盘点,请传 locations(如需按商品盘点请创建 type=goods 任务)』。",
"兼容判定口径:以 wms_stock_check_detail 中 check_id 对应 scope_type='goods' 行是否存在为准(改造前 type=all 任务按商品添加明细,明细行 scope_type='goods');仅 type=all 任务走兼容判定,store/goods/location 类型判定逻辑不变。",
"新任务语义保持:全新 type=all 任务(无任何商品明细行)维持按库位盘点语义——传 stock_ids 报 400『当前盘点类型按库位盘点,请传 locations(如需按商品盘点请创建 type=goods 任务)』;历史任务(按商品模式)传 locations 报 400『当前盘点类型按商品盘点,请传 stock_ids』。",
"文档变更范围:methods/system.json 的 stock.check.addDetail 更新 description/errors/notes(历史任务兼容口径 + 库位错误码文案);根版本 0.3.206 → 0.3.207、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。"
]
},
{
"version": "2026.09.30-stock-check-location-scope",
"date": "2026-09-30",
"type": "updated",
"summary": "盘点明细支持商品/库位两种范围行:all/location 按库位盘点、store/goods 按商品盘点;添加商品限制非本货主商品;库位行作业上报指定商品,账面来源 wms_storage",
"methods": [
"stock.check.create",
"stock.check.addDetail",
"stock.check.report",
"stock.check.detail",
"stock.check.finish",
"stock.check.export"
],
"notes": [
"代码依据:app/service/systems/stock_check.js(create/addDetail/_addGoodsDetailRows/_addLocationDetailRows/detail/_buildDetailAggregations/report/finish/exportStockChecks)+ app/service/systemMethods/stock/check.js(入参透传与 locations/location_codes、stock_id 兼容)+ app/model/stock_check_detail.js / app/model/stock_check_record.js(模型与索引定义)。",
"迁移文件:database/migrations/20260930110000-support-location-scope-in-stock-check-detail.js(本地+生产已执行)——明细表新增 scope_type/location_id/location_code、stock_id/item_code 改可空、防御性合并重复明细并新增唯一索引 uk_check_stock(check_id, stock_id) 与 uk_check_location(check_id, location_code);记录表移除 uk_detail_location(detail_id, location_code)、防御性合并重复记录并新增 uk_detail_stock_location(detail_id, stock_id, location_code)(覆盖式语义升级为同明细+同商品+同库位)。",
"语义变化明细:①create.type 语义明确——all=按库位盘点(未传库位自动全仓库启用库位生成范围)/ location=按库位盘点 / store=按货主按商品盘点 / goods=按商品盘点;②addDetail 新增 locations 入参(兼容 location_codes),按任务 type 与 stock_ids 二选一,响应新增 invalid_locations,商品货主必须与任务 store_id 一致否则计入 invalid_stock_ids;③report 新增可选 stock_id 入参(库位行必填且商品须本仓库),覆盖式查重升级为 detail_id+stock_id+location_code;④detail 库位行输出 scope_type='location' + stocks 数组(按商品聚合,账面查 wms_storage);⑤finish 库位行账面来源 wms_storage(space_id+stock_id SUM(quantity));⑥export Sheet2 按盘点项展开(goods 1 行、location 按商品 N 行)。",
"接口兼容性影响:向后兼容——create.type 枚举不变(all/store/goods/location);addDetail 原 stock_ids 入参与响应字段保留(新增 invalid_locations,非法商品仍走 invalid_stock_ids);report 原入参不变(stock_id 为新增可选参数,商品行不传保持原行为);detail 商品行响应结构不变(库位行为新输出形态);finish/export 响应结构不变。",
"文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create/addDetail/report/detail/finish/export 六条 description/params/response/errors;根版本 0.3.205 → 0.3.206、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。"
]
},
{
"version": "2026.09.30-manual-waybill-express-code",
"date": "2026-09-30",

File diff suppressed because it is too large Load Diff