625 lines
22 KiB
JavaScript
Raw 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;
/** 全部 14 个 method 名(免权限/免鉴权清单共用) */
const ALL_METHOD_NAMES = 'create,list,addDetail,detailDelete,detail,report,recordList,recordDelete,finish,submit,cancel,audit,export,exportTaskProgress';
/**
* 系统方法层:stock.check(库存盘点模块接口包装层)。
* 主要职责:统一包装系统方法接口,处理权限、日志、where 解析等公共逻辑,
* 将具体业务逻辑下沉到 systems.stockCheck 中。
*/
class StockCheckMethodService extends MainService {
constructor(ctx) {
super(ctx);
// 免登录方法列表:空(全部需要登录)
const _noNeedLogin = '';
// 免权限方法列表:全部 14 个方法免 API 权限校验(与 stock/transaction.js 口径一致)
const _noNeedRight = ALL_METHOD_NAMES;
// 免日志方法列表:查询类与导出类不记录操作日志(recordDelete 为写操作,保留操作日志)
const _noNeedLog = 'list,detail,recordList,export,exportTaskProgress';
// 免鉴权(仓库有效期检查)方法列表:全部方法免鉴权(与 stock/transaction.js 口径一致)
const _noNeedAuth = ALL_METHOD_NAMES;
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 统一调用库存盘点业务服务,并捕获业务错误码。
*
* @param {Function} fn 业务调用函数。
* @param {string} fallbackMessage 兜底错误文案。
* @return {Promise<Object>} 统一 success/fail 包装。
*/
async _call(fn, fallbackMessage) {
try {
const result = await fn();
return this.success('ok', result);
} catch (error) {
const code = Number(error && error.code);
if (Number.isInteger(code) && code >= 400 && code < 600) {
return this.fail(error.message || fallbackMessage, {}, code);
}
this.ctx.logger.error(`[stock.check] ${fallbackMessage}: ${error && error.message ? error.message : error}`);
return this.fail('服务器内部错误', {}, 500);
}
}
/**
* 创建盘点任务(空任务)。
* warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
*
* @param {Object} data 请求体。
* @param {string} [data.title] 盘点名称/主题。
* @param {string} [data.type] 盘点范围类型:all/store/goods/location。
* @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘。
* @param {number} [data.store_id] 货主ID(按货主盘点时必填)。
* @param {string} [data.check_date] 盘点日期。
* @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, check_date: checkDate, remark } = data || {};
return this._call(
() => this.service.systems.stockCheck.create({
warehouseId,
title,
type,
mode,
storeId,
checkDate,
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 {number} [data.where.store_id] 货主筛选。
* @param {string} [data.where.keyword] 关键字(单号/标题模糊)。
* @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 storeId = whereValue.store_id !== undefined ? whereValue.store_id : data.store_id;
const keyword = whereValue.keyword !== undefined ? whereValue.keyword : data.keyword;
return this.service.systems.stockCheck.list({
warehouseId,
status,
storeId,
keyword,
pagination,
});
}, '查询盘点任务列表失败');
}
/**
* 添加盘点明细。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {Array<number>} data.stock_ids 商品库存ID列表(wms_stock_warehouse.id)。
* @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 || {};
return this._call(
() => this.service.systems.stockCheck.addDetail({ warehouseId, id, stockIds }),
'添加盘点明细失败'
);
}
/**
* 删除盘点明细(从任务中移除某个商品)。
* 仅主表状态 created/rejected 允许删除;明细存在作业记录时一并防御性删除;
* 删除后重算主表 total_items。
*
* @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 }。
*/
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;
return this._call(
() => this.service.systems.stockCheck.detailDelete({
warehouseId,
id,
detailId,
}),
'删除盘点明细失败'
);
}
/**
* 拉取盘点任务的全部明细行(商品清单)及每条明细的盘点作业记录(库位+数量)。
*
* @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 }])。
*/
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 }),
'查询盘点明细失败'
);
}
/**
* 盘点作业上报(覆盖式)。
* 同明细 + 同库位编码重复上报时更新已有记录(未传库位归入"无库位"分组,location_code 为 null),不再新增。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {number} data.detail_id 明细ID。
* @param {string} [data.location] 库位编码(可空)。
* @param {number} data.quantity 实盘数量(>=0)。
* @return {Promise<Object>} 统一 success 包装,返回 { record, detail_id, mode: 'created'|'updated', ...summary }。
*/
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 || {};
return this._call(
() => this.service.systems.stockCheck.report({
warehouseId,
id,
detailId,
location,
quantity,
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 每条为记录表全字段 + 商品快照列(item_code/item_name)。
*/
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 允许删除;删除后重算盘点进度汇总,主表状态不回退。
*
* @param {Object} data 请求体。
* @param {number} data.id 盘点任务ID。
* @param {number} data.record_id 作业记录ID(兼容 recordId 写法)。
* @param {number} [data.recordId] 作业记录ID(驼峰别名)。
* @return {Promise<Object>} 统一 success 包装,返回 { record_id, deleted, ...summary }。
*/
async recordDelete(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
const { id, record_id: recordIdRaw, recordId: recordIdAlias } = data || {};
const recordId = recordIdRaw !== undefined && recordIdRaw !== null && recordIdRaw !== ''
? recordIdRaw
: recordIdAlias;
return this._call(
() => this.service.systems.stockCheck.recordDelete({
warehouseId,
id,
recordId,
}),
'删除盘点作业记录失败'
);
}
/**
* 完成盘点作业(允许部分未盘完成,未盘明细按实盘 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 }),
'审核盘点任务失败'
);
}
/**
* 提交盘点任务导出任务。
* 异步执行:查询任务与明细 → 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;