liufumingren 562f63f18e feat(stock.check): 商品视图按商品汇总、账面按静态标记取值、静态盘点锁定缓存与库存操作拦截
盘点作业数据(workData / workDataDetail)
- workData goods 视图按 stock_id 汇总为一行(同商品多库位明细合并):行级账面=各库位之和,
  作业记录跨明细按库位合并,locations 每项补 detail_id/snapshot_quantity,行级不再返回 detail_id。
- workDataDetail 商品分支改为 id + stock_id 钻取,返回 summary(汇总)+ rows(按库位分行:
  明细ID/库位ID/账面快照/当前账面/实盘/差异);兼容传商品范围 detail_id。
- 账面取值按任务 is_static 区分:静态盘点取明细快照(冻结基准),普通盘点取当前 wms_storage;
  新增 storage_quantity / is_static / book_source 字段,差异统一为「实盘 - system_quantity」。
- report 的 detail_id 改为可选:商品行可只传 id + stock_id + space_id,服务端按库位明细反查。

静态盘点(is_static)
- wms_stock_check 新增 is_static(TINYINT(1) DEFAULT 0,迁移 20261028010000);create 支持 is_static
  (仅商品盘点有效,库位盘点恒 0);静态定式 pattern=static 创建的任务自动置 1。
- 新增公共查询 stock.check.staticLockList:返回 is_static=1 且 approved/checking 任务的商品集合,
  按仓库缓存(TTL 300s、状态流转先递增代次再重建、回源前后代次校验防脏读、空集合也缓存、
  进程内 singleflight 防击穿),并提供 isStockStaticLocked / getStaticLockConflict 供内部判断。
- 审核通过时刷新商品明细账面快照(快照基准=开始盘点时点),finish 立即释放锁定并返回 released_stock_ids。
- 库存操作拦截:分配储位命中锁定商品时按「库存不足」同流程将该订单标记失败(storage_status=error +
  order_flag),同批次其它订单继续;移库(transferLocation / transferByProduct)命中锁定直接 400。

其他
- 新增开发环境实测脚本 script/stock-check-goods-summary-verify.cjs。
- 测试:stock_check.test.js 覆盖汇总/钻取/静态标记/锁定缓存/账面口径;新增 static_lock_guard.test.js
  覆盖分配与移库拦截;methods/system.json 与 changes 更新至 0.3.318。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-28 07:22:44 +08:00

1144 lines
47 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const MainService = require('../../main');
const STOCK_CHECK_EXPORT_TASK_CACHE_KEY_PREFIX = 'stock_check_export_task_';
const STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
/** 单次导出任务允许的最大盘点任务数量 */
const STOCK_CHECK_EXPORT_MAX_TASK_IDS = 50;
/** 全部 25 个 method 名(免权限/免鉴权清单共用) */
const ALL_METHOD_NAMES = 'create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,workDataSpaceDetails,workDataDetail,report,markEmpty,recordList,recordDelete,recheckClearLocation,finish,submit,cancel,audit,batchDelete,export,exportDetail,exportTaskProgress,patternList,patternCreate,staticLockList';
/**
* 系统方法层:stock.check(库存盘点模块接口包装层)。
* 主要职责:统一包装系统方法接口,处理权限、日志、where 解析等公共逻辑,
* 将具体业务逻辑下沉到 systems.stockCheck 中。
*/
class StockCheckMethodService extends MainService {
constructor(ctx) {
super(ctx);
// 免登录方法列表:空(全部需要登录)
const _noNeedLogin = '';
// 免权限方法列表:全部 20 个方法免 API 权限校验(与 stock/transaction.js 口径一致)
const _noNeedRight = ALL_METHOD_NAMES;
// 免日志方法列表:查询类与导出类不记录操作日志(recordDelete/patternCreate 为写操作,保留操作日志)
const _noNeedLog = 'list,detail,result,workData,workDataSpaceDetails,workDataDetail,recordList,staticLockList,export,exportDetail,exportTaskProgress,patternList';
// 免鉴权(仓库有效期检查)方法列表:全部方法免鉴权(与 stock/transaction.js 口径一致)
const _noNeedAuth = ALL_METHOD_NAMES;
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 统一调用库存盘点业务服务,并捕获业务错误码。
* 成功/失败均按统一 data 层封装:{ flag, code, message, data },
* 与项目 toSuccess/toFailure 常规口径一致(业务数据整体放入 data)。
*
* @param {Function} fn 业务调用函数。
* @param {string} fallbackMessage 兜底错误文案。
* @return {Promise<Object>} 统一 { flag, code, message, data } 包装。
*/
async _call(fn, fallbackMessage) {
try {
const result = await fn();
return { flag: 'success', code: 1, message: 'ok', data: result };
} catch (error) {
const code = Number(error && error.code);
if (Number.isInteger(code) && code >= 400 && code < 600) {
return { flag: 'failure', code, message: error.message || fallbackMessage, data: null };
}
this.ctx.logger.error(`[stock.check] ${fallbackMessage}: ${error && error.message ? error.message : error}`);
return { flag: 'failure', code: 500, message: '服务器内部错误', data: null };
}
}
/**
* 创建盘点任务(空任务)。
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
*
* @param {Object} data 请求体。
* @param {string} [data.title] 盘点名称/主题。
* @param {string} [data.type] 盘点范围类型:location/store/goods,缺省 location。
* @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘;
* 按库位盘点(location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
* @param {number} [data.store_id] 货主ID(按货主盘点时必填)。
* @param {boolean|number} [data.is_static] 是否静态盘点(纯标记,0/1 或布尔;兼容 isStatic 驼峰写法;
* 缺省 0=普通盘点;仅对商品盘点有效,按库位盘点一律 0。静态盘点定式创建的任务由服务端自动置 1)。
* @param {string} [data.remark] 备注。
* 盘点日期固定为今天,前端不传。
* @return {Promise<Object>} 统一 success 包装,返回新建的盘点任务信息。
*/
async create(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 {
title,
type,
mode,
store_id: storeIdSnake,
storeId: storeIdCamel,
is_static: isStaticSnake,
isStatic: isStaticCamel,
remark,
} = data || {};
const storeId = storeIdSnake !== undefined ? storeIdSnake : storeIdCamel;
const isStatic = isStaticSnake !== undefined ? isStaticSnake : isStaticCamel;
return this._call(
() => this.service.systems.stockCheck.create({
warehouseId,
title,
type,
mode,
storeId,
isStatic,
remark,
creatorId,
creatorName,
}),
'创建盘点任务失败'
);
}
/**
* 拉取盘点定式清单(供前端选择定式快速创建盘点任务)。
*
* @return {Promise<Object>} 统一 success 包装,返回 { patterns, total };
* patterns 每条含 id/name/description/type。
*/
async patternList() {
return this._call(
() => this.service.systems.stockCheck.patternList(),
'拉取盘点定式失败'
);
}
/**
* 拉取「静态盘点锁定中」的库存商品列表(公共查询,供库存操作前置判断)。
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
* 口径:is_static=1 且状态为 approved(审核完成)/checking(盘点作业中)任务的商品明细 stock_id 去重集合;
* 结果按仓库维度缓存(TTL 300 秒,状态流转时主动失效)。
*
* @return {Promise<Object>} 统一 success 包装,返回
* { warehouse_id, stock_ids, rows, total, cached, updated_at };
* rows 每个 stock_id 一条:{ stock_id, item_code, item_name, check_ids, check_nos, location_codes }。
*/
async staticLockList() {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
return this._call(
() => this.service.systems.stockCheck.staticLockList({ warehouseId }),
'拉取静态盘点锁定商品列表失败'
);
}
/**
* 按定式快速创建盘点任务。
* 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)限定数据范围。
*
* @param {Object} data 请求体。
* @param {Object} [data.pagination] 分页参数。
* @param {Object} [data.where] 查询条件。
* @param {string|Array<string>} [data.where.status] 状态筛选(单值或数组)。
* @param {string|Array<string>} [data.where.type] 范围类型筛选(location/store/goods)。
* @param {string|Array<string>} [data.where.mode] 盘点方式筛选(open/blind)。
* @param {number} [data.where.store_id] 货主筛选。
* @param {string} [data.where.keyword] 关键字(单号/标题模糊)。
* @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 = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { pagination } = data || {};
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,按商品盘点类型使用)。
* @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,
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,
locations,
locationIds,
}),
'添加盘点明细失败'
);
}
/**
* 批量添加库位明细(兼容入口,转调 addDetail 的库位ID直查路径)。
* 入参传库位ID列表,服务端直接按 ID 查库校验,不经过 space_code 二次解析;
* 幂等添加 scope_type='location' 明细行,已存在的同库位明细自动跳过。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @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_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,
detailIds,
}),
'删除盘点明细失败'
);
}
/**
* 拉取盘点任务详情(只返回任务本身信息)。
* 不返回明细范围行(明细范围行/盘点结果请调用 result)、作业记录(recordList)
* 与盘点作业数据(workData)。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @return {Promise<Object>} 统一 success 包装,返回 { check };
* check 为盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/
* start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/
* remark/created_at/updated_at)。
*/
async detail(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id } = data || {};
return this._call(
() => this.service.systems.stockCheck.detail({ warehouseId, id }),
'查询盘点明细失败'
);
}
/**
* 拉取盘点明细结果(按范围行聚合作业记录)。
*
* @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 }),
'查询盘点结果失败'
);
}
/**
* 拉取盘点作业数据(视图由任务类型与 is_goods 驱动)。
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
* 视图规则:任务范围为库位(type=location)时一律按库位视图返回(无视 view/is_goods);
* 任务范围为商品(type=goods/store)时默认聚合库位视图(space),
* 仅传入 is_goods=true 时按商品视图(goods)返回。
* 分页:data.pagination.{page,pageSize}(与 stock.check.list 口径一致,
* 未传或非法时默认 page=1、pageSize=20,上限 200);
* 响应 rows 为当前页行、total 为全部行数,并返回 page/pageSize。
* 不返回任务主表信息(check)——任务信息请调用 stock.check.detail;
* 响应返回 view(服务端实际解析出的视图类型 location/goods/space),供调用方判断 rows 行结构。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {boolean} [data.is_goods] 商品任务是否按商品视图返回(true=goods);
* 缺省 false=聚合库位视图(space);库位任务无视该参数(兼容 isGoods 驼峰写法)。
* @param {string} [data.keyword] 关键字(仅库位任务 location 视图生效):按行
* location_code/location_name 模糊匹配(不区分大小写)过滤任务明细后返回;非库位任务忽略。
* @param {boolean} [data.only_abnormal] 只看未盘和差异(可选,向后兼容新增,兼容 onlyAbnormal 驼峰写法):
* 过滤在 keyword 之后、分页切片之前完成,三视图均生效——location 视图仅保留 status=unchecked
* 或含未知商品记录(has_unknown=true)的行;goods 视图仅保留未盘行(locations 均无 record_ids)
* 或明盘差异行(is_diff=1,盲盘无数量字段仅按未盘过滤);space 视图按行内 goods 子项过滤
* (status=unchecked 或明盘 checked_quantity≠system_quantity),过滤后 goods 为空的行整体移除。
* @param {Object} [data.pagination] 分页配置 { page, pageSize }。
* @return {Promise<Object>} 统一 success 包装,返回 { view, rows, total, page, pageSize };rows 结构按视图不同:
* location=库位结构(任务库位范围行为列表,行内挂 goods/unknown 作业记录子列表);
* goods=商品结构(按商品 stock_id 汇总,一个商品一行——同商品的库位明细行合并:
* 行内 locations 每项带该库位明细ID detail_id 与账面快照 snapshot_quantity(明盘),
* 明盘返回数量与差异,盲盘不返回数量字段;逐库位明细请调 workDataDetail(id + stock_id));
* space=聚合库位结构(任务商品所在库位为列表,按拣货路径排序,行内挂该库位的任务商品,
* 明盘返回账面/实盘数量,盲盘不返回数量字段)。
*/
async workData(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const {
id,
is_goods: isGoodsSnake,
isGoods: isGoodsCamel,
keyword,
pagination,
only_abnormal: onlyAbnormalSnake,
onlyAbnormal: onlyAbnormalCamel,
} = data || {};
const isGoods = isGoodsSnake !== undefined ? isGoodsSnake : isGoodsCamel;
const onlyAbnormal = onlyAbnormalSnake !== undefined ? onlyAbnormalSnake : onlyAbnormalCamel;
return this._call(
() => this.service.systems.stockCheck.workData({ warehouseId, id, isGoods, keyword, pagination, onlyAbnormal }),
'拉取盘点作业数据失败'
);
}
/**
* 拉取盘点作业数据(space 视图分页版)。
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
* 行结构与 workData space 视图行一致(id=库位ID/location_id 同义库位ID/space_code/custom_barcode/custom_name/goods,
* goods 行含 detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/
* record_ids,明盘另含 system_quantity/checked_quantity,status=checked/unchecked);
* 传入 location_id 时只返回该库位行(total=1),不传时按分页返回全部库位行。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {number} [data.location_id] 库位ID(兼容 locationId 驼峰写法)。
* @param {Object} [data.pagination] 分页配置 { page, pageSize }。
* @return {Promise<Object>} 统一 success 包装,返回 { view:'space', rows, total, page, pageSize }。
*/
async workDataSpaceDetails(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const {
id,
location_id: locationIdSnake,
locationId: locationIdCamel,
pagination,
} = data || {};
const locationId = locationIdSnake !== undefined ? locationIdSnake : locationIdCamel;
return this._call(
() => this.service.systems.stockCheck.workDataSpaceDetails({ warehouseId, id, locationId, pagination }),
'拉取盘点作业数据失败'
);
}
/**
* 拉取盘点作业数据明细(库位明细单行 / 商品钻取)。
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
* ① 库位明细(detail_id 指向 scope_type=location 的行)返回单行,
* 结构与 workData location 视图单行一致(detail_id/location_id/location_code/location_name/
* status/has_unknown/is_empty/checked_at/checkers/goods);
* ② 商品(id=盘点任务ID + stock_id,或 detail_id 指向商品范围行)返回该商品的库位分行数据 + 汇总:
* { check_id, stock_id, item_code/item_name/spec/store_id/store_name/barcode/images,
* summary 商品级汇总(明盘含 system_quantity 账面快照合计/checked_quantity 实盘合计/
* diff_quantity/is_diff;盲盘不含数量字段),
* rows 按库位分行(detail_id 该库位明细ID/location_id 与同义 space_id/location_code,
* 明盘另含 system_quantity 该库位当前账面/snapshot_quantity 该库位账面快照/locked_quantity/
* checked_quantity 该库位实盘/diff_quantity 该库位差异,另有 checked_at/checker_name/record_ids/images) }。
*
* @param {Object} data 请求体。
* @param {number} [data.id] 盘点任务ID(商品钻取必传,与 stock_id 搭配)。
* @param {number} [data.stock_id] 商品库存ID(商品钻取必传;兼容 stockId 驼峰写法)。
* @param {number} [data.detail_id] 盘点明细ID(库位明细必传;商品可只传本参数按明细商品钻取;
* 兼容 detailId 驼峰写法)。
* @return {Promise<Object>} 统一 success 包装,data 为库位单行或商品 { summary, rows } 结构。
*/
async workDataDetail(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const {
id,
detail_id: detailIdSnake,
detailId: detailIdCamel,
stock_id: stockIdSnake,
stockId: stockIdCamel,
} = data || {};
const detailId = detailIdSnake !== undefined ? detailIdSnake : detailIdCamel;
const stockId = stockIdSnake !== undefined ? stockIdSnake : stockIdCamel;
return this._call(
() => this.service.systems.stockCheck.workDataDetail({ warehouseId, id, stockId, detailId }),
'拉取盘点明细作业数据失败'
);
}
/**
* 盘点作业上报(覆盖式)。
* 同明细 + 同商品 + 同库位编码重复上报时更新已有记录(未传库位归入"无库位"分组,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(可选:商品行可不传,服务端按 id + stock_id + space_id
* 反查该商品的库位明细;库位盘点行仍必传)。
* @param {number} data.space_id 库位ID(wms_location_space.id,**必传**;兼容 spaceId / location_id / locationId 写法)。
* 必须属于本仓库且所属分区有效;服务端以该 ID 为准落库,不再按库位编码猜库位。
* @param {string} [data.location] 库位编码(可选,仅做一致性校验:与 space_id 对应库位编码不一致报 400)。
* @param {number} data.quantity 实盘数量(>=0 且 <= 2147483647)。
* @param {number} [data.stock_id] 商品库存ID(wms_stock_warehouse.id;库位明细行必填,或改传 barcode)。
* @param {string} [data.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品,未命中记为未知商品)。
* @param {string} [data.item_name] 未知商品名称(缺省为 barcode;已知商品忽略)。
* @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,
stock_id: stockId,
barcode,
item_name: itemName,
is_empty: isEmpty,
space_id: spaceIdSnake,
spaceId: spaceIdCamel,
location_id: locationIdSnake,
locationId: locationIdCamel,
} = data || {};
const spaceId = [ spaceIdSnake, spaceIdCamel, locationIdSnake, locationIdCamel ]
.find(value => value !== undefined && value !== null && value !== '');
return this._call(
() => this.service.systems.stockCheck.report({
warehouseId,
id,
detailId,
location,
spaceId,
quantity,
stockId,
barcode,
itemName,
is_empty: isEmpty,
checkerId,
checkerName,
}),
'盘点作业上报失败'
);
}
/**
* 标记库位为空(库位盘点模式专属)。
* warehouse_id 由服务端从当前上下文自动注入;仅任务范围为库位(type=location)时允许,
* 非库位任务报 400;状态仅 approved/checking;明细必须属于本任务且为库位范围行。
* 行为与 report(is_empty=true) 一致:写/更新空标记记录、清除该明细商品记录、重算汇总。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {number} data.detail_id 库位明细ID。
* @return {Promise<Object>} 统一 success 包装,返回
* { record, detail_id, mode, total_items, checked_items, diff_items, detail_status }。
*/
async markEmpty(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 } = data || {};
return this._call(
() => this.service.systems.stockCheck.markEmpty({
warehouseId,
id,
detailId,
checkerId,
checkerName,
}),
'标记空库位失败'
);
}
/**
* 拉取盘点作业记录列表。
* 至少传 id(盘点任务ID)或 detail_id(明细ID)之一;按记录 id 倒序,返回分页结果。
*
* @param {Object} data 请求体。
* @param {number} [data.id] 盘点任务ID(可选)。
* @param {number} [data.detail_id] 明细ID(可选,传了只查该明细)。
* @param {Object} [data.pagination] 分页参数。
* @return {Promise<Object>} 统一 success 包装,返回 { rows, total, page, pageSize };
* rows 每条为记录表全字段(含 barcode/item_name)+ 商品快照列(item_code/item_name,
* 未知商品显示扫描条码与名称快照)与 images: [{ id: file_id, url }](业务类型 stock_check_record)。
*/
async recordList(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, detail_id: detailId, pagination } = data || {};
return this._call(
() => this.service.systems.stockCheck.recordList({
warehouseId,
id,
detailId,
pagination,
}),
'查询盘点作业记录失败'
);
}
/**
* 批量删除盘点作业记录(按行清除盘点信息)。
* 仅主表状态 approved/checking 允许删除;删除后重算盘点进度汇总,主表状态不回退。
* 查不到的记录 ID 计入 skipped_ids 不报错;deleted_ids/skipped_ids 保持入参顺序。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {Array<number>|number} data.record_ids 作业记录ID数组(单次上限 200;
* 兼容 recordIds 驼峰写法;兼容旧版单值 record_id 写法,单值自动转数组)。
* @return {Promise<Object>} 统一 success 包装,返回
* { deleted_count, deleted_ids, skipped_ids, total_items, checked_items, diff_items, detail_status };
* 注意:本接口已由旧版单值删除升级为批量删除,响应结构由旧版
* { record_id, deleted, ...summary } 变更为上述结构。
*/
async recordDelete(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const {
id,
record_ids: recordIdsRaw,
recordIds: recordIdsArrayAlias,
recordId: recordIdSingleAlias,
record_id: recordIdSingleSnake,
} = data || {};
const recordIds = recordIdsRaw !== undefined
? recordIdsRaw
: (recordIdsArrayAlias !== undefined
? recordIdsArrayAlias
: (recordIdSingleAlias !== undefined ? recordIdSingleAlias : recordIdSingleSnake));
return this._call(
() => this.service.systems.stockCheck.recordDelete({
warehouseId,
id,
recordIds,
}),
'批量删除盘点作业记录失败'
);
}
/**
* 重盘清除库位(按库位清除盘点信息,库位盘点模式专属)。
* 传入任务ID与库位ID,清除该库位范围内明细的全部作业记录(含空库位标记),该库位回到未盘;
* 仅任务范围为库位(type=location)且状态 approved/checking 时允许,非库位任务报 400。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {number} data.location_id 库位ID(wms_location_space.id;兼容 locationId 驼峰写法)。
* @return {Promise<Object>} 统一 success 包装,返回
* { detail_id, location_id, deleted_count, total_items, checked_items, diff_items, detail_status }。
*/
async recheckClearLocation(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, location_id: locationIdRaw, locationId: locationIdAlias } = data || {};
const locationId = locationIdRaw !== undefined ? locationIdRaw : locationIdAlias;
return this._call(
() => this.service.systems.stockCheck.recheckClearLocation({
warehouseId,
id,
locationId,
}),
'重盘清除库位失败'
);
}
/**
* 完成盘点作业(允许部分未盘完成,未盘明细按实盘 0 处理计为盘亏)。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @return {Promise<Object>} 统一 success 包装,返回差异汇总(含 unchecked_items 未盘明细数)。
*/
async finish(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id } = data || {};
return this._call(
() => this.service.systems.stockCheck.finish({ warehouseId, id }),
'完成盘点作业失败'
);
}
/**
* 完成盘点任务(提交审核)。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @return {Promise<Object>} 统一 success 包装,返回最新状态。
*/
async submit(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id } = data || {};
return this._call(
() => this.service.systems.stockCheck.submit({ warehouseId, id }),
'提交盘点任务失败'
);
}
/**
* 取消盘点任务。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @return {Promise<Object>} 统一 success 包装,返回最新状态。
*/
async cancel(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id } = data || {};
return this._call(
() => this.service.systems.stockCheck.cancel({ warehouseId, id }),
'取消盘点任务失败'
);
}
/**
* 审核盘点任务。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {string} data.action 审核动作:approve=通过,reject=驳回。
* @param {string} [data.reason] 驳回原因(写入备注)。
* @return {Promise<Object>} 统一 success 包装,返回最新状态。
*/
async audit(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, action, reason } = data || {};
return this._call(
() => this.service.systems.stockCheck.audit({ warehouseId, id, action, reason }),
'审核盘点任务失败'
);
}
/**
* 批量删除盘点任务(仅删除已作废任务,非作废或查不到的任务跳过)。
* 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 上传。
* 进度通过 Redis 缓存追踪,立即返回任务ID。
*
* @param {Object} data 请求体。
* @param {Array<number>} [data.ids] 盘点任务ID数组(兼容 task_ids 写法,上限 50)。
* @param {Array<number>} [data.task_ids] 盘点任务ID数组(兼容别名)。
* @return {Promise<Object>} 统一 success 包装,返回任务ID。
*/
async export(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { ids, task_ids: taskIdsRaw } = data || {};
const idSource = ids !== undefined ? ids : taskIdsRaw;
const idList = Array.isArray(idSource) ? idSource : (idSource !== undefined ? [ idSource ] : []);
const numericIds = [ ...new Set(idList.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ];
if (numericIds.length === 0) {
return this.fail('请至少选择一个盘点任务', {}, 400);
}
if (numericIds.length > STOCK_CHECK_EXPORT_MAX_TASK_IDS) {
return this.fail(`单次最多导出 ${STOCK_CHECK_EXPORT_MAX_TASK_IDS} 个盘点任务`, {}, 400);
}
const taskId = this.generateExportTaskId();
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: 0,
current_count: 0,
total_count: 0,
message: '导出任务已提交',
result: null,
error: '',
};
await this.setExportTaskProgress(taskId, taskPayload);
setImmediate(async () => {
try {
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'running',
progress: 5,
current_count: 0,
total_count: 0,
message: '导出任务执行中',
result: null,
error: '',
});
const result = await this.service.systems.stockCheck.exportStockChecks({
warehouseId,
ids: numericIds,
onProgress: async progress => {
const safeProgress = this.isPlainObject(progress) ? progress : {};
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: safeProgress.status || 'running',
progress: safeProgress.progress,
current_count: safeProgress.currentCount || 0,
total_count: safeProgress.totalCount || 0,
message: safeProgress.message || '导出任务执行中',
result: safeProgress.result || null,
error: '',
});
},
});
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'success',
progress: 100,
current_count: result.current_count || 0,
total_count: result.total_count || 0,
message: '导出任务完成',
result,
error: '',
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'failed',
progress: 100,
current_count: 0,
total_count: 0,
message: '导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 提交盘点明细导出任务(单任务,按盘点范围分流)。
* 异步执行:商品范围任务固定两个 Sheet——Sheet1「汇总和差异」(每商品一行:账面快照合计/实盘合计/差异/差异类型盘盈|盘亏)+ Sheet2「库位明细」(库位编码/数量/条码/商品名称);
* 库位范围任务 Sheet「盘点明细」(库位/商品/盘点数量)→ ExcelJS 流式写入 → COS 上传。
* 进度通过 Redis 缓存追踪,立即返回任务ID;进度查询复用 exportTaskProgress。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @return {Promise<Object>} 统一 success 包装,返回任务ID。
*/
async exportDetail(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id } = data || {};
const checkId = Number(id);
if (!Number.isInteger(checkId) || checkId <= 0) {
return this.fail('盘点任务ID不能为空', {}, 400);
}
const taskId = this.generateExportTaskId();
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: 0,
current_count: 0,
total_count: 0,
message: '导出任务已提交',
result: null,
error: '',
};
await this.setExportTaskProgress(taskId, taskPayload);
setImmediate(async () => {
try {
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'running',
progress: 5,
current_count: 0,
total_count: 0,
message: '导出任务执行中',
result: null,
error: '',
});
const result = await this.service.systems.stockCheck.exportCheckDetail({
warehouseId,
id: checkId,
onProgress: async progress => {
const safeProgress = this.isPlainObject(progress) ? progress : {};
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: safeProgress.status || 'running',
progress: safeProgress.progress,
current_count: safeProgress.currentCount || 0,
total_count: safeProgress.totalCount || 0,
message: safeProgress.message || '导出任务执行中',
result: safeProgress.result || null,
error: '',
});
},
});
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'success',
progress: 100,
current_count: result.current_count || 0,
total_count: result.total_count || 0,
message: '导出任务完成',
result,
error: '',
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'failed',
progress: 100,
current_count: 0,
total_count: 0,
message: '导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 查询盘点任务导出进度。
*
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @return {Promise<Object>} 统一 success 包装,包含进度与下载链接。
*/
async exportTaskProgress(data = {}) {
const taskId = this.normalizeExportTaskId(data);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const cachedTask = await this.getExportTaskProgress(taskId);
if (!cachedTask) {
return this.success('ok', {
task_id: taskId,
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
const downloadUrl = String(
safeResult.url
|| safeResult.cdnUrl
|| safeResult.cosUrl
|| safeResult.fileKey
|| ''
);
return this.success('ok', {
task_id: taskId,
...cachedTask,
download_url: downloadUrl,
});
}
// ===========================
// 导出任务辅助方法
// ===========================
/**
* 生成导出任务ID。
*
* @return {string} 导出任务ID。
*/
generateExportTaskId() {
const warehouseId = this.ctx && this.ctx.user && this.ctx.user.store_id
? this.ctx.user.store_id
: 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `stock_check_export_${warehouseId}_${timestamp}_${randomToken}`;
}
/**
* 归一化导出任务ID(兼容 task_id / taskId)。
*
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @return {string} 归一化后的任务ID。
*/
normalizeExportTaskId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
}
/**
* 获取导出任务缓存键。
*
* @param {string} taskId 任务ID。
* @return {string} 缓存键。
*/
getExportTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${STOCK_CHECK_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入导出任务进度缓存。
*
* @param {string} taskId 任务ID。
* @param {Object} payload 任务状态载荷。
* @return {Promise<void>} 无返回值。
*/
async setExportTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const normalizeCount = value => {
const numericValue = Number(value);
return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0;
};
const progressPayload = {
task_id: String(taskId || '').trim(),
status: String(safePayload.status || 'submitted').trim() || 'submitted',
progress: Number.isFinite(Number(safePayload.progress))
? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress))))
: 0,
current_count: normalizeCount(safePayload.current_count),
total_count: normalizeCount(safePayload.total_count),
message: String(safePayload.message || ''),
result: safePayload.result ?? null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(
cacheKey,
progressPayload,
STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS
);
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[stock.check.export] 写入导出任务缓存失败: ${errorMessage}`);
}
}
/**
* 读取导出任务进度缓存。
*
* @param {string} taskId 任务ID。
* @return {Promise<Object|null>} 任务缓存,不存在则返回 null。
*/
async getExportTaskProgress(taskId = '') {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[stock.check.export] 读取导出任务缓存失败: ${errorMessage}`);
return null;
}
}
}
module.exports = StockCheckMethodService;