- workData 三视图:goods 视图 locations=商品所在全部库位列表(明盘每库位 system_quantity 账面/quantity 盘点、盲盘只显示库位);space 视图同口径;新增 workDataSpaceDetails 分页版 - workDataDetail 增加 goods 分支(单行结构,复用视图构建器);detail 补 profit_total/loss_total 差异汇总 - 库位账面全量统一为 SUM(available_quantity+locked_quantity)(可用+锁定)并标记 locked_quantity:result/report/finish/detail/addDetail 拆行快照与作业视图一致 - 未盘行不误显盘亏:diff/is_diff 仅存在作业记录时计算 - 文档 methods/system.json 0.3.249 + changes 变更记录,开发/生产库已回填
981 lines
39 KiB
JavaScript
981 lines
39 KiB
JavaScript
'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;
|
||
|
||
/** 全部 23 个 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,exportTaskProgress,patternList,patternCreate';
|
||
|
||
/**
|
||
* 系统方法层: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,export,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] 盘点范围类型:all/store/goods/location。
|
||
* @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘;
|
||
* 按库位盘点(all/location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。
|
||
* @param {number} [data.store_id] 货主ID(按货主盘点时必填)。
|
||
* @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: storeId, remark } = data || {};
|
||
|
||
return this._call(
|
||
() => this.service.systems.stockCheck.create({
|
||
warehouseId,
|
||
title,
|
||
type,
|
||
mode,
|
||
storeId,
|
||
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 由服务端从当前上下文自动注入,前端无需传递。
|
||
* 盘点方式由定式范围类型固定:库位类定式一律盲盘(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] 范围类型筛选(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 = {}) {
|
||
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/all)时一律按库位视图返回(无视 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 {Object} [data.pagination] 分页配置 { page, pageSize }。
|
||
* @return {Promise<Object>} 统一 success 包装,返回 { view, rows, total, page, pageSize };rows 结构按视图不同:
|
||
* location=库位结构(任务库位范围行为列表,行内挂 goods/unknown 作业记录子列表);
|
||
* goods=商品结构(任务商品范围行为列表,行内挂按库位聚合的 locations 作业记录,
|
||
* 明盘返回数量与差异,盲盘不返回数量字段);
|
||
* 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,
|
||
} = data || {};
|
||
const isGoods = isGoodsSnake !== undefined ? isGoodsSnake : isGoodsCamel;
|
||
|
||
return this._call(
|
||
() => this.service.systems.stockCheck.workData({ warehouseId, id, isGoods, keyword, pagination }),
|
||
'拉取盘点作业数据失败'
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 拉取盘点作业数据(space 视图分页版)。
|
||
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
|
||
* 行结构与 workData space 视图行一致(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 }),
|
||
'拉取盘点作业数据失败'
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 拉取单条盘点明细的作业数据(workData 单行版)。
|
||
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
|
||
* 按明细范围类型分流,均返回单行对象(与对应视图单行结构一致):
|
||
* 库位明细(scope_type=location)行结构同 workData location 视图单行
|
||
* (detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/
|
||
* checked_at/checkers/goods);商品明细(scope_type=goods)行结构同 workData goods 视图行
|
||
* (detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/locations,
|
||
* 明盘含 system_quantity/checked_quantity/diff_quantity/is_diff,盲盘不含数量字段)。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {number} data.detail_id 盘点明细ID(库位范围行或商品范围行;兼容 detailId 驼峰写法)。
|
||
* @return {Promise<Object>} 统一 success 包装,data 为单行作业数据(结构随明细范围类型)。
|
||
*/
|
||
async workDataDetail(data = {}) {
|
||
const { ctx } = this;
|
||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||
const { detail_id: detailIdSnake, detailId: detailIdCamel } = data || {};
|
||
const detailId = detailIdSnake !== undefined ? detailIdSnake : detailIdCamel;
|
||
|
||
return this._call(
|
||
() => this.service.systems.stockCheck.workDataDetail({ warehouseId, 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。
|
||
* @param {string} [data.location] 库位编码(可空;库位明细行以明细库位为准)。
|
||
* @param {number} data.quantity 实盘数量(>=0)。
|
||
* @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,
|
||
} = data || {};
|
||
|
||
return this._call(
|
||
() => this.service.systems.stockCheck.report({
|
||
warehouseId,
|
||
id,
|
||
detailId,
|
||
location,
|
||
quantity,
|
||
stockId,
|
||
barcode,
|
||
itemName,
|
||
is_empty: isEmpty,
|
||
checkerId,
|
||
checkerName,
|
||
}),
|
||
'盘点作业上报失败'
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 标记库位为空(库位盘点模式专属)。
|
||
* warehouse_id 由服务端从当前上下文自动注入;仅任务范围为库位(type=location/all)时允许,
|
||
* 非库位任务报 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/all)且状态 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(),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 查询盘点任务导出进度。
|
||
*
|
||
* @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;
|