feat(stock): 库存/仓库模块货主侧查询与报表增强
- stock/warehouse: 新增 externalList/externalExport(外仓/货主维度查询) - storeWarehouse/store: 新增货主侧接口(list/get 等) - stock_store: getWarehouseStock 支持 externalWarehouseId/externalStoreId - store_warehouse: 合同关系改为单向维度查询(不再 OR 两边) - storage/report: 库存报表支持 store 维度 + stockIds/keyword 精确筛选 - stock/transaction: storeList/exportStore store_id 从 ctx 获取防越权 - stock_warehouse: getStockDetails 支持显式传 null 跳过仓库过滤 - storage/management: 储位分配待处理排除待审核(step=1)订单
This commit is contained in:
parent
3c53b3c8fa
commit
510b87632a
@ -36,7 +36,8 @@ class StockTransactionMethodService extends MainService {
|
|||||||
start_time: startTime,
|
start_time: startTime,
|
||||||
end_time: endTime,
|
end_time: endTime,
|
||||||
store_ids: storeIds,
|
store_ids: storeIds,
|
||||||
stock_ids: stockIds,
|
stock_ids: stockIdsRaw,
|
||||||
|
stock_id: stockIdRaw,
|
||||||
keyword,
|
keyword,
|
||||||
ids,
|
ids,
|
||||||
transaction_type: transactionType,
|
transaction_type: transactionType,
|
||||||
@ -48,6 +49,11 @@ class StockTransactionMethodService extends MainService {
|
|||||||
order_id: orderId,
|
order_id: orderId,
|
||||||
} = whereValue;
|
} = whereValue;
|
||||||
|
|
||||||
|
// 兼容 stock_id(单数)和 stock_ids(数组)
|
||||||
|
const stockIds = stockIdsRaw !== undefined
|
||||||
|
? stockIdsRaw
|
||||||
|
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
|
||||||
|
|
||||||
const { sort = {} } = data;
|
const { sort = {} } = data;
|
||||||
const {
|
const {
|
||||||
sort_field: sortFieldSnake,
|
sort_field: sortFieldSnake,
|
||||||
@ -86,9 +92,8 @@ class StockTransactionMethodService extends MainService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 货主侧商品出入库流水列表查询。
|
* 货主侧商品出入库流水列表查询。
|
||||||
* 按货主 store_id 限定数据范围。
|
* 按当前登录货主的 store_id(ctx.user.store_id)限定数据范围,不接受外部传入 store_id,防止跨货主查询。
|
||||||
* @param {Object} data 请求体
|
* @param {Object} data 请求体
|
||||||
* @param {number} data.store_id 货主ID(必传)
|
|
||||||
* @param {Object} [data.pagination] 分页参数
|
* @param {Object} [data.pagination] 分页参数
|
||||||
* @param {Object} [data.where] 查询条件
|
* @param {Object} [data.where] 查询条件
|
||||||
* @param {Object} [data.sort] 排序参数
|
* @param {Object} [data.sort] 排序参数
|
||||||
@ -96,9 +101,9 @@ class StockTransactionMethodService extends MainService {
|
|||||||
*/
|
*/
|
||||||
async storeList(data = {}) {
|
async storeList(data = {}) {
|
||||||
const { service } = this;
|
const { service } = this;
|
||||||
const storeId = Number(data.store_id);
|
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
|
||||||
if (!Number.isInteger(storeId) || storeId <= 0) {
|
if (!Number.isInteger(storeId) || storeId <= 0) {
|
||||||
return this.failure('store_id 不能为空');
|
return this.failure('无法获取当前货主身份,请重新登录');
|
||||||
}
|
}
|
||||||
|
|
||||||
const { pagination } = data;
|
const { pagination } = data;
|
||||||
@ -180,7 +185,8 @@ class StockTransactionMethodService extends MainService {
|
|||||||
start_time: startTime,
|
start_time: startTime,
|
||||||
end_time: endTime,
|
end_time: endTime,
|
||||||
store_ids: storeIds,
|
store_ids: storeIds,
|
||||||
stock_ids: stockIds,
|
stock_ids: stockIdsRaw,
|
||||||
|
stock_id: stockIdRaw,
|
||||||
keyword,
|
keyword,
|
||||||
ids,
|
ids,
|
||||||
transaction_type: transactionType,
|
transaction_type: transactionType,
|
||||||
@ -192,6 +198,11 @@ class StockTransactionMethodService extends MainService {
|
|||||||
order_id: orderId,
|
order_id: orderId,
|
||||||
} = whereValue;
|
} = whereValue;
|
||||||
|
|
||||||
|
// 兼容 stock_id(单数)和 stock_ids(数组)
|
||||||
|
const stockIds = stockIdsRaw !== undefined
|
||||||
|
? stockIdsRaw
|
||||||
|
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
|
||||||
|
|
||||||
const { sort = {} } = data;
|
const { sort = {} } = data;
|
||||||
const sortOption = {
|
const sortOption = {
|
||||||
sortField: sort.sortField || sort.sort_field,
|
sortField: sort.sortField || sort.sort_field,
|
||||||
@ -270,15 +281,15 @@ class StockTransactionMethodService extends MainService {
|
|||||||
/**
|
/**
|
||||||
* 货主侧提交商品流水导出任务。
|
* 货主侧提交商品流水导出任务。
|
||||||
* 与 storeList 使用相同查询条件,异步执行,立即返回任务ID。
|
* 与 storeList 使用相同查询条件,异步执行,立即返回任务ID。
|
||||||
|
* store_id 从当前登录上下文(ctx.user.store_id)获取,不接受外部传入,防止跨货主查询。
|
||||||
* @param {Object} data 请求体
|
* @param {Object} data 请求体
|
||||||
* @param {number} data.store_id 货主ID(必传)
|
|
||||||
* @return {Promise<Object>} 统一 success 包装(返回任务ID)
|
* @return {Promise<Object>} 统一 success 包装(返回任务ID)
|
||||||
*/
|
*/
|
||||||
async exportStore(data = {}) {
|
async exportStore(data = {}) {
|
||||||
const { service } = this;
|
const { service } = this;
|
||||||
const storeId = Number(data.store_id);
|
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
|
||||||
if (!Number.isInteger(storeId) || storeId <= 0) {
|
if (!Number.isInteger(storeId) || storeId <= 0) {
|
||||||
return this.failure('store_id 不能为空');
|
return this.failure('无法获取当前货主身份,请重新登录');
|
||||||
}
|
}
|
||||||
|
|
||||||
const { whereValue = {} } = this.prepareWhereContext(data);
|
const { whereValue = {} } = this.prepareWhereContext(data);
|
||||||
|
|||||||
@ -9,9 +9,9 @@ class WarehouseService extends MainService {
|
|||||||
constructor(ctx) {
|
constructor(ctx) {
|
||||||
super(ctx);
|
super(ctx);
|
||||||
const _noNeedLogin = '';
|
const _noNeedLogin = '';
|
||||||
const _noNeedRight = 'list,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail';
|
const _noNeedRight = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail';
|
||||||
const _noNeedLog = 'list,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail';
|
const _noNeedLog = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail';
|
||||||
const _noNeedAuth = 'list,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';
|
||||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -79,6 +79,159 @@ class WarehouseService extends MainService {
|
|||||||
return this.success('ok', result);
|
return this.success('ok', result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 外仓商品列表查询。
|
||||||
|
* - 传入 warehouse_id:按指定仓库维度查询
|
||||||
|
* - 不传 warehouse_id:按当前货主维度查询(store_id = ctx.user.store_id)
|
||||||
|
* @param {Object} data 请求体
|
||||||
|
* @param {number} [data.warehouse_id] 仓库ID(可选)
|
||||||
|
* @param {Object} [data.pagination] 分页参数
|
||||||
|
* @param {Object} [data.where] 筛选条件
|
||||||
|
* @return {Promise<Object>} 统一成功包装响应
|
||||||
|
*/
|
||||||
|
async externalList(data = {}) {
|
||||||
|
const { service, ctx } = this;
|
||||||
|
const warehouseId = Number(data.warehouse_id || data.warehouseId || 0);
|
||||||
|
const { pagination } = data;
|
||||||
|
const sort = data.sort || {};
|
||||||
|
const sortParams = {
|
||||||
|
sortField: sort.sortField || sort.sort_field || 'id',
|
||||||
|
sortOrder: sort.sortOrder || sort.sort_order || 'DESC',
|
||||||
|
};
|
||||||
|
if (this.isPlainObject(data)) {
|
||||||
|
const rawWhere = this.isPlainObject(data.where) ? data.where : {};
|
||||||
|
data.where = this.normalizeWarehouseRecycleWhere(rawWhere);
|
||||||
|
}
|
||||||
|
// 传入 warehouse_id 时合并到 where 条件中
|
||||||
|
if (warehouseId > 0) {
|
||||||
|
data.where = {
|
||||||
|
...(data.where || {}),
|
||||||
|
warehouse_id: { operator: 'eq', value: warehouseId },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const { where } = this.prepareWhereContext(data, {
|
||||||
|
specialFieldMap: {
|
||||||
|
barcode: {
|
||||||
|
bucket: 'barcode',
|
||||||
|
},
|
||||||
|
prohibited_type: {
|
||||||
|
bucket: 'prohibited',
|
||||||
|
field: 'id',
|
||||||
|
},
|
||||||
|
has_bound_item: {
|
||||||
|
bucket: 'storeOutStock',
|
||||||
|
field: 'stock_id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// 始终按当前货主维度查(store_id = self)
|
||||||
|
const result = await service.systems.stockStore.getWarehouseStock(where, pagination, sortParams, 0, ctx.user.store_id);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交外仓商品导出任务(复用 externalList 的筛选语义与排序规则)。
|
||||||
|
* - 传入 warehouse_id:按指定仓库维度导出
|
||||||
|
* - 不传 warehouse_id:按当前货主维度导出(store_id = ctx.user.store_id)
|
||||||
|
* @param {Object} data 请求体
|
||||||
|
* @param {number} [data.warehouse_id] 仓库ID(可选)
|
||||||
|
* @param {Object} [data.where] 筛选条件
|
||||||
|
* @param {Object} [data.sort] 排序参数
|
||||||
|
* @param {string} [data.sort.sortField] 排序字段(兼容:sort_field)
|
||||||
|
* @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order)
|
||||||
|
* @return {Promise<Object>} 统一成功包装响应,data 为导出任务信息
|
||||||
|
*/
|
||||||
|
async externalExport(data = {}) {
|
||||||
|
const { service, ctx } = this;
|
||||||
|
const warehouseId = Number(data.warehouse_id || data.warehouseId || 0);
|
||||||
|
const sort = data.sort || {};
|
||||||
|
const sortField = sort.sortField || sort.sort_field;
|
||||||
|
const sortOrder = sort.sortOrder || sort.sort_order;
|
||||||
|
const sortParams = {
|
||||||
|
...(sortField ? { sortField } : {}),
|
||||||
|
...(sortOrder ? { sortOrder } : {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (this.isPlainObject(data)) {
|
||||||
|
const rawWhere = this.isPlainObject(data.where) ? data.where : {};
|
||||||
|
data.where = this.normalizeWarehouseRecycleWhere(rawWhere);
|
||||||
|
}
|
||||||
|
// 传入 warehouse_id 时合并到 where 条件中
|
||||||
|
if (warehouseId > 0) {
|
||||||
|
data.where = {
|
||||||
|
...(data.where || {}),
|
||||||
|
warehouse_id: { operator: 'eq', value: warehouseId },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const { where } = this.prepareWhereContext(data, {
|
||||||
|
specialFieldMap: {
|
||||||
|
barcode: {
|
||||||
|
bucket: 'barcode',
|
||||||
|
},
|
||||||
|
prohibited_type: {
|
||||||
|
bucket: 'prohibited',
|
||||||
|
field: 'id',
|
||||||
|
},
|
||||||
|
has_bound_item: {
|
||||||
|
bucket: 'storeOutStock',
|
||||||
|
field: 'stock_id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const taskId = this.generateExportTaskId('external');
|
||||||
|
const taskPayload = {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'submitted',
|
||||||
|
progress: 0,
|
||||||
|
message: '外仓导出任务已提交',
|
||||||
|
result: null,
|
||||||
|
error: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
await this.setExportTaskProgress(taskId, taskPayload);
|
||||||
|
|
||||||
|
setImmediate(async () => {
|
||||||
|
try {
|
||||||
|
await this.setExportTaskProgress(taskId, {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'running',
|
||||||
|
progress: 10,
|
||||||
|
message: '外仓导出任务执行中',
|
||||||
|
result: null,
|
||||||
|
error: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 始终按当前货主维度导出(store_id = self)
|
||||||
|
const result = await service.systems.stockStore.exportExternalWarehouseStock(where, sortParams, warehouseId, ctx.user.store_id);
|
||||||
|
|
||||||
|
await this.setExportTaskProgress(taskId, {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'success',
|
||||||
|
progress: 100,
|
||||||
|
message: '外仓导出任务完成',
|
||||||
|
result,
|
||||||
|
error: '',
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||||
|
await this.setExportTaskProgress(taskId, {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'failed',
|
||||||
|
progress: 100,
|
||||||
|
message: '外仓导出任务失败',
|
||||||
|
result: null,
|
||||||
|
error: errorMessage,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.success('ok', {
|
||||||
|
...taskPayload,
|
||||||
|
update_time: Date.now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 提交仓库商品导出任务(复用 list 的筛选语义与排序规则)。
|
* 提交仓库商品导出任务(复用 list 的筛选语义与排序规则)。
|
||||||
* @param {Object} data 请求体
|
* @param {Object} data 请求体
|
||||||
@ -224,13 +377,15 @@ class WarehouseService extends MainService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 生成仓库商品导出任务ID。
|
* 生成仓库商品导出任务ID。
|
||||||
|
* @param {string} [prefix=''] 任务类型前缀(如 'external')
|
||||||
* @return {string} 导出任务ID
|
* @return {string} 导出任务ID
|
||||||
*/
|
*/
|
||||||
generateExportTaskId() {
|
generateExportTaskId(prefix = '') {
|
||||||
const warehouseId = this.ctx?.user?.store_id || 'unknown';
|
const warehouseId = this.ctx?.user?.store_id || 'unknown';
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||||
return `stock_warehouse_export_${warehouseId}_${timestamp}_${randomToken}`;
|
const typePrefix = prefix ? `${prefix}_` : '';
|
||||||
|
return `stock_warehouse_${typePrefix}export_${warehouseId}_${timestamp}_${randomToken}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -644,7 +799,22 @@ class WarehouseService extends MainService {
|
|||||||
* @return {Promise<Object>} data 为关联分页结果
|
* @return {Promise<Object>} data 为关联分页结果
|
||||||
*/
|
*/
|
||||||
async getStoreStocks(data) {
|
async getStoreStocks(data) {
|
||||||
const { service } = this;
|
const { ctx, service } = this;
|
||||||
|
// 校验归属:stock_warehouse 的 store_id 或 warehouse_id 匹配当前主体即可放行
|
||||||
|
const stockId = Number(data.stock_id || 0);
|
||||||
|
if (stockId > 0) {
|
||||||
|
const stock = await ctx.model.StockWarehouse.findOne({
|
||||||
|
where: { id: stockId },
|
||||||
|
attributes: [ 'id', 'store_id', 'warehouse_id' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
if (!stock
|
||||||
|
|| (stock.store_id !== ctx.user.store_id && stock.warehouse_id !== ctx.user.store_id)) {
|
||||||
|
return this.fail('无权限查看该商品的绑定信息', { code: 403 });
|
||||||
|
}
|
||||||
|
// 使用实际的 warehouse_id 查询
|
||||||
|
data._warehouseId = stock.warehouse_id;
|
||||||
|
}
|
||||||
const result = await service.systems.stockStore.getStoreStocks(data);
|
const result = await service.systems.stockStore.getStoreStocks(data);
|
||||||
return this.success('ok', { data: result, code: 200 });
|
return this.success('ok', { data: result, code: 200 });
|
||||||
}
|
}
|
||||||
@ -730,10 +900,24 @@ class WarehouseService extends MainService {
|
|||||||
* @return {Promise<Object>} data 为日志分页结果
|
* @return {Promise<Object>} data 为日志分页结果
|
||||||
*/
|
*/
|
||||||
async queryStockLogs(data) {
|
async queryStockLogs(data) {
|
||||||
const { ctx } = this;
|
const { ctx, service } = this;
|
||||||
try {
|
try {
|
||||||
const { service } = this;
|
const stockId = Number(data.id || 0);
|
||||||
|
if (stockId > 0) {
|
||||||
|
// 校验 stock_warehouse:store_id 或 warehouse_id 匹配当前主体即可放行
|
||||||
|
const stock = await ctx.model.StockWarehouse.findOne({
|
||||||
|
where: { id: stockId },
|
||||||
|
attributes: [ 'id', 'store_id', 'warehouse_id' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
if (!stock
|
||||||
|
|| (stock.store_id !== ctx.user.store_id && stock.warehouse_id !== ctx.user.store_id)) {
|
||||||
|
return this.fail('无权限查看该商品的库存日志', { code: 403 });
|
||||||
|
}
|
||||||
|
data.warehouseId = stock.warehouse_id;
|
||||||
|
} else {
|
||||||
data.warehouseId = ctx.user.store_id;
|
data.warehouseId = ctx.user.store_id;
|
||||||
|
}
|
||||||
const result = await service.systems.operationLog.queryStockLogs(data);
|
const result = await service.systems.operationLog.queryStockLogs(data);
|
||||||
return this.success('ok', { data: result, code: 200 });
|
return this.success('ok', { data: result, code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
const MainService = require('../../main');
|
const MainService = require('../../main');
|
||||||
|
|
||||||
|
const PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_KEY_PREFIX = 'print_quantity_log_export_task_';
|
||||||
|
const PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 规范仓库配置方法入参,避免把原始引用直接传给下游服务。
|
* 规范仓库配置方法入参,避免把原始引用直接传给下游服务。
|
||||||
@ -26,9 +29,9 @@ class StoreWarehouseStoreService extends MainService {
|
|||||||
constructor(ctx) {
|
constructor(ctx) {
|
||||||
super(ctx);
|
super(ctx);
|
||||||
const _noNeedLogin = '';
|
const _noNeedLogin = '';
|
||||||
const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
|
const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity';
|
||||||
const _noNeedLog = '*';
|
const _noNeedLog = '*';
|
||||||
const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
|
const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportPrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity';
|
||||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -417,6 +420,444 @@ class StoreWarehouseStoreService extends MainService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交面单余额变更日志导出任务。
|
||||||
|
* 入参条件与 queryPrintQuantityLogs 的 where 语义一致,异步执行,立即返回 task_id。
|
||||||
|
*
|
||||||
|
* @param {Object} data 请求数据。
|
||||||
|
* @param {number|string} data.store_id 货主ID(必填)。
|
||||||
|
* @param {Object} [data.where] 动态筛选条件,与 queryPrintQuantityLogs 的 where 语义一致。
|
||||||
|
* @return {Promise<Object>} 统一响应结果(包含 task_id)。
|
||||||
|
*/
|
||||||
|
async exportPrintQuantityLogs(data = {}) {
|
||||||
|
const { service } = this;
|
||||||
|
const targetService = service && service.systems && service.systems.storeWarehouse;
|
||||||
|
|
||||||
|
if (!targetService || typeof targetService.exportPrintQuantityLogs !== 'function') {
|
||||||
|
return this.fail('导出面单余额变更日志失败', { code: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const requestData = normalizeStoreWarehousePayload(data);
|
||||||
|
const { where } = this.prepareWhereContext(requestData);
|
||||||
|
const { store_id } = requestData;
|
||||||
|
|
||||||
|
const taskId = this.generateExportTaskId();
|
||||||
|
const taskPayload = {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'submitted',
|
||||||
|
progress: 0,
|
||||||
|
message: '导出任务已提交',
|
||||||
|
result: null,
|
||||||
|
error: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
await this.setExportTaskProgress(taskId, taskPayload);
|
||||||
|
|
||||||
|
setImmediate(async () => {
|
||||||
|
try {
|
||||||
|
await this.setExportTaskProgress(taskId, {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'running',
|
||||||
|
progress: 10,
|
||||||
|
message: '导出任务执行中',
|
||||||
|
result: null,
|
||||||
|
error: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await targetService.exportPrintQuantityLogs({
|
||||||
|
store_id,
|
||||||
|
where,
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.setExportTaskProgress(taskId, {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'success',
|
||||||
|
progress: 100,
|
||||||
|
message: '导出任务完成',
|
||||||
|
result,
|
||||||
|
error: '',
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||||
|
await this.setExportTaskProgress(taskId, {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'failed',
|
||||||
|
progress: 100,
|
||||||
|
message: '导出任务失败',
|
||||||
|
result: null,
|
||||||
|
error: errorMessage,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.success('ok', {
|
||||||
|
...taskPayload,
|
||||||
|
update_time: Date.now(),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
return this.fail(error.message || '导出面单余额变更日志失败', {
|
||||||
|
code: Number(error.code) || 500,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询面单余额变更日志导出任务进度。
|
||||||
|
*
|
||||||
|
* @param {Object} data 请求数据。
|
||||||
|
* @param {string} [data.task_id] 任务ID(下划线写法)。
|
||||||
|
* @param {string} [data.taskId] 任务ID(驼峰写法)。
|
||||||
|
* @return {Promise<Object>} 统一响应结果。
|
||||||
|
*/
|
||||||
|
async exportPrintQuantityLogsTaskProgress(data = {}) {
|
||||||
|
const taskId = this.normalizeExportTaskId(data);
|
||||||
|
if (!taskId) {
|
||||||
|
return this.success('ok', {
|
||||||
|
task_id: '',
|
||||||
|
status: 'not_found',
|
||||||
|
progress: 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,
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 货主侧查询面单余额变更日志(自动从平台激活上下文获取 store_id)。
|
||||||
|
* 无需显式传入 store_id,系统自动从当前用户激活的货主平台上下文中获取。
|
||||||
|
*
|
||||||
|
* @param {Object} data 请求数据。
|
||||||
|
* @param {Object} [data.where] 动态筛选条件。
|
||||||
|
* @param {Object} [data.pagination] 分页对象。
|
||||||
|
* @param {number|string} [data.pagination.page] 页码。
|
||||||
|
* @param {number|string} [data.pagination.page_size] 每页条数。
|
||||||
|
* @return {Promise<Object>} 统一响应结果。
|
||||||
|
*/
|
||||||
|
async queryStorePrintQuantityLogs(data = {}) {
|
||||||
|
const { ctx, app, service } = this;
|
||||||
|
|
||||||
|
// 从平台激活上下文获取 store_id
|
||||||
|
const platformRows = await app.model.query(
|
||||||
|
'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' +
|
||||||
|
'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' +
|
||||||
|
'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1',
|
||||||
|
{
|
||||||
|
replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' },
|
||||||
|
type: app.Sequelize.QueryTypes.SELECT,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) {
|
||||||
|
return this.fail('未获取到货主平台激活上下文,请先切换至货主角色');
|
||||||
|
}
|
||||||
|
|
||||||
|
const storeId = platformRows[0].store_id;
|
||||||
|
const targetService = service && service.systems && service.systems.storeWarehouse;
|
||||||
|
|
||||||
|
if (!targetService || typeof targetService.queryPrintQuantityLogs !== 'function') {
|
||||||
|
return this.fail('查询面单余额变更日志失败', { code: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const requestData = normalizeStoreWarehousePayload(data);
|
||||||
|
const { where } = this.prepareWhereContext(requestData);
|
||||||
|
const rawPagination = requestData.pagination && typeof requestData.pagination === 'object'
|
||||||
|
? requestData.pagination
|
||||||
|
: {};
|
||||||
|
const { page, page_size } = rawPagination;
|
||||||
|
|
||||||
|
const result = await targetService.queryPrintQuantityLogs({
|
||||||
|
store_id: storeId,
|
||||||
|
where,
|
||||||
|
pagination: { page, page_size },
|
||||||
|
});
|
||||||
|
return this.success('ok', result);
|
||||||
|
} catch (error) {
|
||||||
|
return this.fail(error.message || '查询面单余额变更日志失败', {
|
||||||
|
code: Number(error.code) || 500,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 货主侧提交面单余额变更日志导出任务(自动从平台激活上下文获取 store_id)。
|
||||||
|
* 入参条件与 queryStorePrintQuantityLogs 的 where 语义一致,异步执行,立即返回 task_id。
|
||||||
|
*
|
||||||
|
* @param {Object} data 请求数据。
|
||||||
|
* @param {Object} [data.where] 动态筛选条件。
|
||||||
|
* @return {Promise<Object>} 统一响应结果(包含 task_id)。
|
||||||
|
*/
|
||||||
|
async exportStorePrintQuantityLogs(data = {}) {
|
||||||
|
const { ctx, app, service } = this;
|
||||||
|
|
||||||
|
// 从平台激活上下文获取 store_id
|
||||||
|
const platformRows = await app.model.query(
|
||||||
|
'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' +
|
||||||
|
'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' +
|
||||||
|
'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1',
|
||||||
|
{
|
||||||
|
replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' },
|
||||||
|
type: app.Sequelize.QueryTypes.SELECT,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) {
|
||||||
|
return this.fail('未获取到货主平台激活上下文,请先切换至货主角色');
|
||||||
|
}
|
||||||
|
|
||||||
|
const storeId = platformRows[0].store_id;
|
||||||
|
const targetService = service && service.systems && service.systems.storeWarehouse;
|
||||||
|
|
||||||
|
if (!targetService || typeof targetService.exportPrintQuantityLogs !== 'function') {
|
||||||
|
return this.fail('导出面单余额变更日志失败', { code: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const requestData = normalizeStoreWarehousePayload(data);
|
||||||
|
const { where } = this.prepareWhereContext(requestData);
|
||||||
|
|
||||||
|
const taskId = this.generateExportTaskId('store');
|
||||||
|
const taskPayload = {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'submitted',
|
||||||
|
progress: 0,
|
||||||
|
message: '货主侧导出任务已提交',
|
||||||
|
result: null,
|
||||||
|
error: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
await this.setExportTaskProgress(taskId, taskPayload);
|
||||||
|
|
||||||
|
setImmediate(async () => {
|
||||||
|
try {
|
||||||
|
await this.setExportTaskProgress(taskId, {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'running',
|
||||||
|
progress: 10,
|
||||||
|
message: '货主侧导出任务执行中',
|
||||||
|
result: null,
|
||||||
|
error: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await targetService.exportPrintQuantityLogs({
|
||||||
|
store_id: storeId,
|
||||||
|
where,
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.setExportTaskProgress(taskId, {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'success',
|
||||||
|
progress: 100,
|
||||||
|
message: '货主侧导出任务完成',
|
||||||
|
result,
|
||||||
|
error: '',
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||||
|
await this.setExportTaskProgress(taskId, {
|
||||||
|
task_id: taskId,
|
||||||
|
status: 'failed',
|
||||||
|
progress: 100,
|
||||||
|
message: '货主侧导出任务失败',
|
||||||
|
result: null,
|
||||||
|
error: errorMessage,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.success('ok', {
|
||||||
|
...taskPayload,
|
||||||
|
update_time: Date.now(),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
return this.fail(error.message || '导出面单余额变更日志失败', {
|
||||||
|
code: Number(error.code) || 500,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 货主侧查询面单余额变更日志导出任务进度。
|
||||||
|
* 复用 exportPrintQuantityLogsTaskProgress 的缓存查询逻辑。
|
||||||
|
*
|
||||||
|
* @param {Object} data 请求数据。
|
||||||
|
* @param {string} [data.task_id] 任务ID(下划线写法)。
|
||||||
|
* @param {string} [data.taskId] 任务ID(驼峰写法)。
|
||||||
|
* @return {Promise<Object>} 统一响应结果。
|
||||||
|
*/
|
||||||
|
async exportStorePrintQuantityLogsTaskProgress(data = {}) {
|
||||||
|
const taskId = this.normalizeExportTaskId(data);
|
||||||
|
if (!taskId) {
|
||||||
|
return this.success('ok', {
|
||||||
|
task_id: '',
|
||||||
|
status: 'not_found',
|
||||||
|
progress: 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,
|
||||||
|
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。
|
||||||
|
* @param {string} [prefix=''] 任务类型前缀(如 'store')
|
||||||
|
* @return {string} 导出任务ID。
|
||||||
|
*/
|
||||||
|
generateExportTaskId(prefix = '') {
|
||||||
|
const storeId = this.ctx?.user?.store_id || 'unknown';
|
||||||
|
const timestamp = Date.now();
|
||||||
|
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||||
|
const typePrefix = prefix ? `${prefix}_` : '';
|
||||||
|
return `print_qty_log_${typePrefix}export_${storeId}_${timestamp}_${randomToken}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 规范导出任务ID。
|
||||||
|
* @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 `${PRINT_QUANTITY_LOG_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 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,
|
||||||
|
message: String(safePayload.message || ''),
|
||||||
|
result: safePayload.result ?? null,
|
||||||
|
error: String(safePayload.error || ''),
|
||||||
|
update_time: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.app.setCacheAsync(cacheKey, progressPayload, PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_TTL_SECONDS);
|
||||||
|
} catch (error) {
|
||||||
|
this.ctx.logger.warn('[storeWarehouse.store.exportPrintQuantityLogs] 写入导出任务缓存失败: %s',
|
||||||
|
error && error.message ? error.message : error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取导出任务进度缓存。
|
||||||
|
* @param {string} taskId 任务ID。
|
||||||
|
* @return {Promise<Object|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) {
|
||||||
|
this.ctx.logger.warn('[storeWarehouse.store.exportPrintQuantityLogs] 读取导出任务缓存失败: %s',
|
||||||
|
error && error.message ? error.message : error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = StoreWarehouseStoreService;
|
module.exports = StoreWarehouseStoreService;
|
||||||
|
|||||||
@ -36,7 +36,8 @@ class StockWarehouseService extends Service {
|
|||||||
async getStockDetails(stockIds, options = {}) {
|
async getStockDetails(stockIds, options = {}) {
|
||||||
const { ctx, app } = this;
|
const { ctx, app } = this;
|
||||||
const { cacheTTL = DEFAULT_STOCK_DETAIL_CACHE_TTL } = options;
|
const { cacheTTL = DEFAULT_STOCK_DETAIL_CACHE_TTL } = options;
|
||||||
const warehouseId = options.warehouseId != null ? options.warehouseId : ctx.user.store_id;
|
// 用 !== undefined 代替 != null:显式传 null 表示跳过 warehouse 过滤(如货主侧查询)
|
||||||
|
const warehouseId = options.warehouseId !== undefined ? options.warehouseId : ctx.user.store_id;
|
||||||
|
|
||||||
if (!Array.isArray(stockIds) || stockIds.length === 0) {
|
if (!Array.isArray(stockIds) || stockIds.length === 0) {
|
||||||
return [];
|
return [];
|
||||||
|
|||||||
@ -71,11 +71,12 @@ class StorageManagementService extends Service {
|
|||||||
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||||
const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||||||
|
|
||||||
// 2) 查询当前仓库所有未完成储位分配的订单
|
// 2) 查询当前仓库所有未完成储位分配的订单(排除待审核 step=1)
|
||||||
const pendingOrders = await orderModel.findAll({
|
const pendingOrders = await orderModel.findAll({
|
||||||
where: {
|
where: {
|
||||||
warehouse_id: warehouseId,
|
warehouse_id: warehouseId,
|
||||||
storage_status: { [Op.ne]: 'fin' },
|
storage_status: { [Op.ne]: 'fin' },
|
||||||
|
step: { [Op.ne]: 1 },
|
||||||
delete_at: null,
|
delete_at: null,
|
||||||
},
|
},
|
||||||
attributes: [ 'id' ],
|
attributes: [ 'id' ],
|
||||||
|
|||||||
@ -353,7 +353,7 @@ class StorageReportService extends Service {
|
|||||||
if (normalizedStockIds.length > 0) {
|
if (normalizedStockIds.length > 0) {
|
||||||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||||||
normalizedStockIds,
|
normalizedStockIds,
|
||||||
{}
|
{ warehouseId } // store 模式下为 null → 跳过 warehouse 过滤
|
||||||
);
|
);
|
||||||
for (const detail of stockDetails) {
|
for (const detail of stockDetails) {
|
||||||
const sid = Number(detail.id);
|
const sid = Number(detail.id);
|
||||||
@ -515,11 +515,15 @@ class StorageReportService extends Service {
|
|||||||
* @param {string} [sort.sortField] 排序字段
|
* @param {string} [sort.sortField] 排序字段
|
||||||
* @param {string} [sort.sortOrder] 排序顺序
|
* @param {string} [sort.sortOrder] 排序顺序
|
||||||
* @param {string} [exportMode] 导出模式:'item' 导出全部(含锁定),不传/其他值则排除锁定类型记录
|
* @param {string} [exportMode] 导出模式:'item' 导出全部(含锁定),不传/其他值则排除锁定类型记录
|
||||||
|
* @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度
|
||||||
|
* @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤)
|
||||||
|
* @param {string} [keyword=''] 商品关键字(模糊匹配)
|
||||||
* @return {Promise<Object>} excel 上传结果
|
* @return {Promise<Object>} excel 上传结果
|
||||||
*/
|
*/
|
||||||
async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '') {
|
async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '', searchMode = 'warehouse', stockIds = null, keyword = '') {
|
||||||
const { ctx, app } = this;
|
const { ctx, app } = this;
|
||||||
const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort);
|
const isStoreMode = searchMode === 'store';
|
||||||
|
const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort, searchMode, stockIds, keyword);
|
||||||
if (!searchResult || searchResult.code !== 200) {
|
if (!searchResult || searchResult.code !== 200) {
|
||||||
return searchResult;
|
return searchResult;
|
||||||
}
|
}
|
||||||
@ -527,15 +531,26 @@ class StorageReportService extends Service {
|
|||||||
const summaryList = Array.isArray(searchResult.data && searchResult.data.list)
|
const summaryList = Array.isArray(searchResult.data && searchResult.data.list)
|
||||||
? searchResult.data.list
|
? searchResult.data.list
|
||||||
: [];
|
: [];
|
||||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
const rawPrimaryId = Number(ctx.user && ctx.user.store_id);
|
||||||
|
const storeId = isStoreMode ? rawPrimaryId : null;
|
||||||
|
const warehouseId = isStoreMode ? null : rawPrimaryId;
|
||||||
const startTimeMs = toTimeMs(startTime);
|
const startTimeMs = toTimeMs(startTime);
|
||||||
const endTimeMs = toTimeMs(endTime);
|
const endTimeMs = toTimeMs(endTime);
|
||||||
const normalizedStoreIds = normalizeStoreIds(storeIds);
|
const normalizedStoreIds = normalizeStoreIds(storeIds);
|
||||||
const isBySpace = normalizeBoolean(bySpace);
|
const isBySpace = normalizeBoolean(bySpace);
|
||||||
|
|
||||||
const whereClauses = [ 't.warehouse_id = :warehouseId' ];
|
// 主维度:仓库模式用 warehouse_id,货主模式用 store_id
|
||||||
|
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
|
||||||
|
const primaryDimVal = isStoreMode ? storeId : warehouseId;
|
||||||
|
const primaryDimAlias = isStoreMode ? 'storeId' : 'warehouseId';
|
||||||
|
// 辅助维度:仓库模式用 store_id(货主过滤),货主模式用 warehouse_id(仓库过滤)
|
||||||
|
const secondaryIds = normalizedStoreIds;
|
||||||
|
const secondaryDimCol = isStoreMode ? 'warehouse_id' : 'store_id';
|
||||||
|
const secondaryDimAlias = isStoreMode ? 'warehouseIds' : 'storeIds';
|
||||||
|
|
||||||
|
const whereClauses = [ `t.${primaryDimCol} = :${primaryDimAlias}` ];
|
||||||
const replacements = {
|
const replacements = {
|
||||||
warehouseId,
|
[primaryDimAlias]: primaryDimVal,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (startTimeMs !== null) {
|
if (startTimeMs !== null) {
|
||||||
@ -548,9 +563,9 @@ class StorageReportService extends Service {
|
|||||||
replacements.endTime = endTime;
|
replacements.endTime = endTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (normalizedStoreIds.length > 0) {
|
if (secondaryIds.length > 0) {
|
||||||
whereClauses.push('t.store_id IN (:storeIds)');
|
whereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||||||
replacements.storeIds = normalizedStoreIds;
|
replacements[secondaryDimAlias] = secondaryIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
const normalizedExportMode = String(exportMode || '').trim();
|
const normalizedExportMode = String(exportMode || '').trim();
|
||||||
@ -623,6 +638,8 @@ class StorageReportService extends Service {
|
|||||||
{ header: '结束时间', key: 'end_time' },
|
{ header: '结束时间', key: 'end_time' },
|
||||||
{ header: '货主ID', key: 'store_id' },
|
{ header: '货主ID', key: 'store_id' },
|
||||||
{ header: '货主名称', key: 'store_name' },
|
{ header: '货主名称', key: 'store_name' },
|
||||||
|
{ header: '仓库ID', key: 'warehouse_id' },
|
||||||
|
{ header: '仓库名称', key: 'warehouse_name' },
|
||||||
{ header: '商品库存ID', key: 'stock_id' },
|
{ header: '商品库存ID', key: 'stock_id' },
|
||||||
{ header: '商品编码', key: 'item_code' },
|
{ header: '商品编码', key: 'item_code' },
|
||||||
{ header: '商品名称', key: 'item_name' },
|
{ header: '商品名称', key: 'item_name' },
|
||||||
@ -644,6 +661,8 @@ class StorageReportService extends Service {
|
|||||||
end_time: item.end_time || '',
|
end_time: item.end_time || '',
|
||||||
store_id: toNumber(item.store_id),
|
store_id: toNumber(item.store_id),
|
||||||
store_name: item.store_name || '',
|
store_name: item.store_name || '',
|
||||||
|
warehouse_id: toNumber(item.warehouse_id),
|
||||||
|
warehouse_name: item.warehouse_name || '',
|
||||||
stock_id: toNumber(item.stock_id),
|
stock_id: toNumber(item.stock_id),
|
||||||
item_code: item.item_code || '',
|
item_code: item.item_code || '',
|
||||||
item_name: item.item_name || '',
|
item_name: item.item_name || '',
|
||||||
@ -663,10 +682,8 @@ class StorageReportService extends Service {
|
|||||||
const detailSheetRows = safeDetailRows.map(item => {
|
const detailSheetRows = safeDetailRows.map(item => {
|
||||||
const stockId = toNumber(item.stock_id);
|
const stockId = toNumber(item.stock_id);
|
||||||
const storeId = toNumber(item.store_id);
|
const storeId = toNumber(item.store_id);
|
||||||
const spaceId = toNumber(item.space_id);
|
|
||||||
const stock = maps.stockMap.get(stockId) || {};
|
const stock = maps.stockMap.get(stockId) || {};
|
||||||
const store = maps.storeMap.get(storeId) || {};
|
const store = maps.storeMap.get(storeId) || {};
|
||||||
const space = maps.spaceMap.get(spaceId) || {};
|
|
||||||
const barcodeSet = maps.barcodeMap.get(stockId);
|
const barcodeSet = maps.barcodeMap.get(stockId);
|
||||||
|
|
||||||
const entryOrderId = toNumber(item.entry_order_id);
|
const entryOrderId = toNumber(item.entry_order_id);
|
||||||
@ -691,8 +708,6 @@ class StorageReportService extends Service {
|
|||||||
item_code: stock.item_code || '',
|
item_code: stock.item_code || '',
|
||||||
item_name: stock.item_name || '',
|
item_name: stock.item_name || '',
|
||||||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||||||
space_id: spaceId,
|
|
||||||
space_name: space.custom_name || space.space_code || '',
|
|
||||||
quantity: toNumber(item.quantity),
|
quantity: toNumber(item.quantity),
|
||||||
before_quantity: toNumber(item.before_quantity),
|
before_quantity: toNumber(item.before_quantity),
|
||||||
after_quantity: toNumber(item.after_quantity),
|
after_quantity: toNumber(item.after_quantity),
|
||||||
@ -725,8 +740,6 @@ class StorageReportService extends Service {
|
|||||||
{ header: '商品编码', key: 'item_code' },
|
{ header: '商品编码', key: 'item_code' },
|
||||||
{ header: '商品名称', key: 'item_name' },
|
{ header: '商品名称', key: 'item_name' },
|
||||||
{ header: '条码', key: 'barcode' },
|
{ header: '条码', key: 'barcode' },
|
||||||
{ header: '库位ID', key: 'space_id' },
|
|
||||||
{ header: '库位名称', key: 'space_name' },
|
|
||||||
{ header: '变动数量', key: 'quantity' },
|
{ header: '变动数量', key: 'quantity' },
|
||||||
{ header: '变更前库存', key: 'before_quantity' },
|
{ header: '变更前库存', key: 'before_quantity' },
|
||||||
{ header: '变更后库存', key: 'after_quantity' },
|
{ header: '变更后库存', key: 'after_quantity' },
|
||||||
@ -750,7 +763,7 @@ class StorageReportService extends Service {
|
|||||||
|
|
||||||
return await ctx.service.systems.excel.generateAndUpload({
|
return await ctx.service.systems.excel.generateAndUpload({
|
||||||
filename: this.buildExportFilename(startTime, endTime),
|
filename: this.buildExportFilename(startTime, endTime),
|
||||||
dir: `exports/storage/report/${warehouseId || 'common'}`,
|
dir: `exports/storage/report/${warehouseId || storeId || 'common'}`,
|
||||||
category: 'document',
|
category: 'document',
|
||||||
sheets: [
|
sheets: [
|
||||||
{
|
{
|
||||||
@ -767,6 +780,66 @@ class StorageReportService extends Service {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据关键字解析匹配的 stock_id 列表。
|
||||||
|
* 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)模糊匹配。
|
||||||
|
* @param {string} keyword 搜索关键字
|
||||||
|
* @param {string} primaryDimCol 主维度列名(warehouse_id 或 store_id)
|
||||||
|
* @param {number} primaryDimVal 主维度值
|
||||||
|
* @return {Promise<number[]>} 匹配的 stock_id 列表
|
||||||
|
*/
|
||||||
|
async _resolveKeywordToStockIds(keyword, primaryDimCol, primaryDimVal) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const normalizedKeyword = String(keyword || '').trim();
|
||||||
|
if (!normalizedKeyword) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const likePattern = `%${normalizedKeyword}%`;
|
||||||
|
// 如果 keyword 为纯数字,同时支持按 stock_id(SKU ID)精确匹配
|
||||||
|
const exactStockId = /^\d+$/.test(normalizedKeyword) ? Number(normalizedKeyword) : null;
|
||||||
|
|
||||||
|
// 从 wms_stock_warehouse 按 item_code / item_name / goods_code / id(SKU) 模糊匹配
|
||||||
|
const extraIdCondition = exactStockId !== null ? 'OR sw.id = :exactStockId' : '';
|
||||||
|
const stockRows = await ctx.model.query(`
|
||||||
|
SELECT DISTINCT sw.id AS stock_id
|
||||||
|
FROM wms_stock_warehouse sw
|
||||||
|
WHERE sw.${primaryDimCol} = :primaryDimVal
|
||||||
|
AND (
|
||||||
|
sw.item_code LIKE :keyword
|
||||||
|
OR sw.item_name LIKE :keyword
|
||||||
|
OR sw.goods_code LIKE :keyword
|
||||||
|
${extraIdCondition}
|
||||||
|
)
|
||||||
|
`, {
|
||||||
|
replacements: { primaryDimVal, keyword: likePattern, exactStockId },
|
||||||
|
type: app.Sequelize.QueryTypes.SELECT,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 从 wms_stock_barcodes 按 barcode 模糊匹配
|
||||||
|
const barcodeRows = await ctx.model.query(`
|
||||||
|
SELECT DISTINCT sb.stock_id
|
||||||
|
FROM wms_stock_barcodes sb
|
||||||
|
INNER JOIN wms_stock_warehouse sw ON sw.id = sb.stock_id AND sw.${primaryDimCol} = :primaryDimVal
|
||||||
|
WHERE sb.barcode LIKE :keyword
|
||||||
|
`, {
|
||||||
|
replacements: { primaryDimVal, keyword: likePattern },
|
||||||
|
type: app.Sequelize.QueryTypes.SELECT,
|
||||||
|
});
|
||||||
|
|
||||||
|
const stockIdSet = new Set();
|
||||||
|
for (const row of stockRows) {
|
||||||
|
const sid = Number(row.stock_id);
|
||||||
|
if (sid > 0) stockIdSet.add(sid);
|
||||||
|
}
|
||||||
|
for (const row of barcodeRows) {
|
||||||
|
const sid = Number(row.stock_id);
|
||||||
|
if (sid > 0) stockIdSet.add(sid);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [ ...stockIdSet ];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询库存流水统计报表。
|
* 查询库存流水统计报表。
|
||||||
* 规则:
|
* 规则:
|
||||||
@ -779,22 +852,46 @@ class StorageReportService extends Service {
|
|||||||
* @param {string|Date|null} startTime 开始时间(闭区间下限)
|
* @param {string|Date|null} startTime 开始时间(闭区间下限)
|
||||||
* @param {string|Date|null} endTime 结束时间(闭区间上限)
|
* @param {string|Date|null} endTime 结束时间(闭区间上限)
|
||||||
* @param {boolean|string|number} [bySpace=false] 是否按库位返回
|
* @param {boolean|string|number} [bySpace=false] 是否按库位返回
|
||||||
* @param {Array<number|string>|number|string|null} [storeIds=[]] 货主ID列表
|
* @param {Array<number|string>|number|string|null} [storeIds=[]] 货主ID列表(store模式为仓库ID列表)
|
||||||
* @param {Object} [sort] 排序参数
|
* @param {Object} [sort] 排序参数
|
||||||
* @param {string} [sort.sortField] 排序字段(begin_total、inbound_total、outbound_total、end_total)
|
* @param {string} [sort.sortField] 排序字段(begin_total、inbound_total、outbound_total、end_total)
|
||||||
* @param {string} [sort.sortOrder] 排序顺序(ASC、DESC,大小写不敏感)
|
* @param {string} [sort.sortOrder] 排序顺序(ASC、DESC,大小写不敏感)
|
||||||
|
* @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度
|
||||||
|
* @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤),与 keyword 互斥
|
||||||
|
* @param {string} [keyword=''] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配),与 stockIds 互斥
|
||||||
* @return {Promise<Object>} code/data/message 结构
|
* @return {Promise<Object>} code/data/message 结构
|
||||||
*/
|
*/
|
||||||
async search(startTime, endTime, bySpace = false, storeIds = [], sort = null) {
|
async search(startTime, endTime, bySpace = false, storeIds = [], sort = null, searchMode = 'warehouse', stockIds = null, keyword = '') {
|
||||||
const { ctx, app } = this;
|
const { ctx, app } = this;
|
||||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
const isStoreMode = searchMode === 'store';
|
||||||
if (!warehouseId) {
|
const rawPrimaryId = Number(ctx.user && ctx.user.store_id);
|
||||||
|
const storeId = isStoreMode ? rawPrimaryId : null;
|
||||||
|
const warehouseId = isStoreMode ? null : rawPrimaryId;
|
||||||
|
|
||||||
|
if (!isStoreMode && !warehouseId) {
|
||||||
return {
|
return {
|
||||||
code: 400,
|
code: 400,
|
||||||
message: '用户未绑定仓库',
|
message: '用户未绑定仓库',
|
||||||
data: { list: [] },
|
data: { list: [] },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
if (isStoreMode && !storeId) {
|
||||||
|
return {
|
||||||
|
code: 400,
|
||||||
|
message: '用户未绑定货主',
|
||||||
|
data: { list: [] },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主维度:仓库模式用 warehouse_id,货主模式用 store_id
|
||||||
|
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
|
||||||
|
const primaryDimVal = isStoreMode ? storeId : warehouseId;
|
||||||
|
const primaryDimAlias = isStoreMode ? 'storeId' : 'warehouseId';
|
||||||
|
|
||||||
|
// 辅助维度:仓库模式用 store_id(货主过滤),货主模式用 warehouse_id(仓库过滤)
|
||||||
|
const secondaryIds = normalizeStoreIds(storeIds);
|
||||||
|
const secondaryDimCol = isStoreMode ? 'warehouse_id' : 'store_id';
|
||||||
|
const secondaryDimAlias = isStoreMode ? 'warehouseIds' : 'storeIds';
|
||||||
|
|
||||||
const startTimeMs = toTimeMs(startTime);
|
const startTimeMs = toTimeMs(startTime);
|
||||||
const endTimeMs = toTimeMs(endTime);
|
const endTimeMs = toTimeMs(endTime);
|
||||||
@ -824,25 +921,51 @@ class StorageReportService extends Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const isBySpace = normalizeBoolean(bySpace);
|
const isBySpace = normalizeBoolean(bySpace);
|
||||||
const normalizedStoreIds = normalizeStoreIds(storeIds);
|
|
||||||
|
// 归一化 stock_ids:优先使用 keyword 解析,其次使用显式传入的 stockIds
|
||||||
|
let resolvedStockIds = null;
|
||||||
|
const normalizedKeyword = String(keyword || '').trim();
|
||||||
|
if (normalizedKeyword) {
|
||||||
|
resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal);
|
||||||
|
if (resolvedStockIds.length === 0) {
|
||||||
|
return {
|
||||||
|
code: 200,
|
||||||
|
message: '查询成功',
|
||||||
|
data: { list: [] },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} else if (stockIds !== null && stockIds !== undefined) {
|
||||||
|
const rawIds = Array.isArray(stockIds) ? stockIds : [ stockIds ];
|
||||||
|
resolvedStockIds = [ ...new Set(
|
||||||
|
rawIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||||
|
) ];
|
||||||
|
if (resolvedStockIds.length === 0) {
|
||||||
|
return {
|
||||||
|
code: 200,
|
||||||
|
message: '查询成功',
|
||||||
|
data: { list: [] },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let baseStockRows = [];
|
let baseStockRows = [];
|
||||||
let baseStorageRows = [];
|
let baseStorageRows = [];
|
||||||
if (!isBySpace) {
|
if (!isBySpace) {
|
||||||
const baseWhereClauses = [ 'sw.warehouse_id = :warehouseId' ];
|
const baseWhereClauses = [ `sw.${primaryDimCol} = :${primaryDimAlias}` ];
|
||||||
const baseReplacements = {
|
const baseReplacements = {
|
||||||
warehouseId,
|
[primaryDimAlias]: primaryDimVal,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (normalizedStoreIds.length > 0) {
|
if (secondaryIds.length > 0) {
|
||||||
baseWhereClauses.push('sw.store_id IN (:storeIds)');
|
baseWhereClauses.push(`sw.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||||||
baseReplacements.storeIds = normalizedStoreIds;
|
baseReplacements[secondaryDimAlias] = secondaryIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
baseStockRows = await ctx.model.query(`
|
baseStockRows = await ctx.model.query(`
|
||||||
SELECT
|
SELECT
|
||||||
sw.id AS stock_id,
|
sw.id AS stock_id,
|
||||||
sw.store_id,
|
sw.store_id,
|
||||||
|
sw.warehouse_id,
|
||||||
sw.quantity
|
sw.quantity
|
||||||
FROM wms_stock_warehouse sw
|
FROM wms_stock_warehouse sw
|
||||||
WHERE ${baseWhereClauses.join(' AND ')}
|
WHERE ${baseWhereClauses.join(' AND ')}
|
||||||
@ -851,6 +974,12 @@ class StorageReportService extends Service {
|
|||||||
type: app.Sequelize.QueryTypes.SELECT,
|
type: app.Sequelize.QueryTypes.SELECT,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 如果指定了 stock_id 过滤,仅保留匹配的 stock 行
|
||||||
|
if (resolvedStockIds !== null) {
|
||||||
|
const stockIdSet = new Set(resolvedStockIds);
|
||||||
|
baseStockRows = baseStockRows.filter(row => stockIdSet.has(Number(row.stock_id)));
|
||||||
|
}
|
||||||
|
|
||||||
if (!Array.isArray(baseStockRows) || baseStockRows.length === 0) {
|
if (!Array.isArray(baseStockRows) || baseStockRows.length === 0) {
|
||||||
return {
|
return {
|
||||||
code: 200,
|
code: 200,
|
||||||
@ -859,14 +988,14 @@ class StorageReportService extends Service {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const baseWhereClauses = [ 's.warehouse_id = :warehouseId', 's.delete_at IS NULL' ];
|
const baseWhereClauses = [ `s.${primaryDimCol} = :${primaryDimAlias}`, 's.delete_at IS NULL' ];
|
||||||
const baseReplacements = {
|
const baseReplacements = {
|
||||||
warehouseId,
|
[primaryDimAlias]: primaryDimVal,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (normalizedStoreIds.length > 0) {
|
if (secondaryIds.length > 0) {
|
||||||
baseWhereClauses.push('s.store_id IN (:storeIds)');
|
baseWhereClauses.push(`s.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||||||
baseReplacements.storeIds = normalizedStoreIds;
|
baseReplacements[secondaryDimAlias] = secondaryIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
baseStorageRows = await ctx.model.query(`
|
baseStorageRows = await ctx.model.query(`
|
||||||
@ -874,21 +1003,28 @@ class StorageReportService extends Service {
|
|||||||
s.stock_id,
|
s.stock_id,
|
||||||
COALESCE(s.space_id, 0) AS space_id,
|
COALESCE(s.space_id, 0) AS space_id,
|
||||||
s.store_id,
|
s.store_id,
|
||||||
|
s.warehouse_id,
|
||||||
SUM(s.quantity) AS quantity
|
SUM(s.quantity) AS quantity
|
||||||
FROM wms_storage s
|
FROM wms_storage s
|
||||||
WHERE ${baseWhereClauses.join(' AND ')}
|
WHERE ${baseWhereClauses.join(' AND ')}
|
||||||
GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id
|
GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id, s.warehouse_id
|
||||||
`, {
|
`, {
|
||||||
replacements: baseReplacements,
|
replacements: baseReplacements,
|
||||||
type: app.Sequelize.QueryTypes.SELECT,
|
type: app.Sequelize.QueryTypes.SELECT,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 如果指定了 stock_id 过滤,仅保留匹配的 stock 行
|
||||||
|
if (resolvedStockIds !== null) {
|
||||||
|
const stockIdSet = new Set(resolvedStockIds);
|
||||||
|
baseStorageRows = baseStorageRows.filter(row => stockIdSet.has(Number(row.stock_id)));
|
||||||
|
}
|
||||||
|
|
||||||
baseStorageRows = Array.isArray(baseStorageRows) ? baseStorageRows : [];
|
baseStorageRows = Array.isArray(baseStorageRows) ? baseStorageRows : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
const rangeWhereClauses = [ 't.warehouse_id = :warehouseId' ];
|
const rangeWhereClauses = [ `t.${primaryDimCol} = :${primaryDimAlias}` ];
|
||||||
const rangeReplacements = {
|
const rangeReplacements = {
|
||||||
warehouseId,
|
[primaryDimAlias]: primaryDimVal,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (startTimeMs !== null) {
|
if (startTimeMs !== null) {
|
||||||
@ -901,9 +1037,9 @@ class StorageReportService extends Service {
|
|||||||
rangeReplacements.endTime = endTime;
|
rangeReplacements.endTime = endTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (normalizedStoreIds.length > 0) {
|
if (secondaryIds.length > 0) {
|
||||||
rangeWhereClauses.push('t.store_id IN (:storeIds)');
|
rangeWhereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||||||
rangeReplacements.storeIds = normalizedStoreIds;
|
rangeReplacements[secondaryDimAlias] = secondaryIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isBySpace) {
|
if (!isBySpace) {
|
||||||
@ -963,17 +1099,17 @@ class StorageReportService extends Service {
|
|||||||
let preStartSnapshotRows = [];
|
let preStartSnapshotRows = [];
|
||||||
if (startTimeMs !== null) {
|
if (startTimeMs !== null) {
|
||||||
const preStartWhereClauses = [
|
const preStartWhereClauses = [
|
||||||
't.warehouse_id = :warehouseId',
|
`t.${primaryDimCol} = :${primaryDimAlias}`,
|
||||||
't.created_at < :startTime',
|
't.created_at < :startTime',
|
||||||
];
|
];
|
||||||
const preStartReplacements = {
|
const preStartReplacements = {
|
||||||
warehouseId,
|
[primaryDimAlias]: primaryDimVal,
|
||||||
startTime,
|
startTime,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (normalizedStoreIds.length > 0) {
|
if (secondaryIds.length > 0) {
|
||||||
preStartWhereClauses.push('t.store_id IN (:storeIds)');
|
preStartWhereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||||||
preStartReplacements.storeIds = normalizedStoreIds;
|
preStartReplacements[secondaryDimAlias] = secondaryIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isBySpace) {
|
if (!isBySpace) {
|
||||||
@ -1039,6 +1175,7 @@ class StorageReportService extends Service {
|
|||||||
.map(row => {
|
.map(row => {
|
||||||
const stockId = Number(row.stock_id);
|
const stockId = Number(row.stock_id);
|
||||||
const storeId = Number(row.store_id);
|
const storeId = Number(row.store_id);
|
||||||
|
const whId = Number(row.warehouse_id) || 0;
|
||||||
const stockStoreKey = `${stockId}_${storeId}`;
|
const stockStoreKey = `${stockId}_${storeId}`;
|
||||||
const snapshot = edgeByStockStore.get(stockStoreKey);
|
const snapshot = edgeByStockStore.get(stockStoreKey);
|
||||||
const rangeSum = rangeSumByStockStore.get(stockStoreKey);
|
const rangeSum = rangeSumByStockStore.get(stockStoreKey);
|
||||||
@ -1059,11 +1196,13 @@ class StorageReportService extends Service {
|
|||||||
end_time: endTime || null,
|
end_time: endTime || null,
|
||||||
stock_id: stockId,
|
stock_id: stockId,
|
||||||
store_id: storeId,
|
store_id: storeId,
|
||||||
|
warehouse_id: whId,
|
||||||
begin_total: beginTotal,
|
begin_total: beginTotal,
|
||||||
end_total: endTotal,
|
end_total: endTotal,
|
||||||
inbound_total: toNumber(rangeSum && rangeSum.inbound_total),
|
inbound_total: toNumber(rangeSum && rangeSum.inbound_total),
|
||||||
outbound_total: toNumber(rangeSum && rangeSum.outbound_total),
|
outbound_total: toNumber(rangeSum && rangeSum.outbound_total),
|
||||||
store_name: '',
|
store_name: '',
|
||||||
|
warehouse_name: '',
|
||||||
item_name: '',
|
item_name: '',
|
||||||
barcode: '',
|
barcode: '',
|
||||||
item_code: '',
|
item_code: '',
|
||||||
@ -1071,16 +1210,19 @@ class StorageReportService extends Service {
|
|||||||
})
|
})
|
||||||
.filter(item => item.stock_id > 0 && item.store_id > 0);
|
.filter(item => item.stock_id > 0 && item.store_id > 0);
|
||||||
|
|
||||||
const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
|
const groupedStockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
|
||||||
const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ];
|
const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ];
|
||||||
|
const warehouseIdList = [ ...new Set(groupedList.map(item => item.warehouse_id).filter(Boolean)) ];
|
||||||
|
|
||||||
// 复用 getStockDetails 获取商品名称和条码
|
// 复用 getStockDetails 获取商品名称和条码
|
||||||
|
// store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品
|
||||||
|
const stockDetailOpts = isStoreMode ? { warehouseId: null } : {};
|
||||||
const stockMap = new Map();
|
const stockMap = new Map();
|
||||||
const barcodesByStock = new Map();
|
const barcodesByStock = new Map();
|
||||||
if (stockIds.length > 0) {
|
if (groupedStockIds.length > 0) {
|
||||||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||||||
stockIds,
|
groupedStockIds,
|
||||||
{}
|
stockDetailOpts
|
||||||
);
|
);
|
||||||
for (const detail of stockDetails) {
|
for (const detail of stockDetails) {
|
||||||
const sid = Number(detail.id);
|
const sid = Number(detail.id);
|
||||||
@ -1115,15 +1257,29 @@ class StorageReportService extends Service {
|
|||||||
|
|
||||||
const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ]));
|
const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ]));
|
||||||
|
|
||||||
|
const warehouseRows = warehouseIdList.length > 0
|
||||||
|
? await ctx.model.Store.findAll({
|
||||||
|
where: {
|
||||||
|
id: warehouseIdList,
|
||||||
|
},
|
||||||
|
attributes: [ 'id', 'company_name' ],
|
||||||
|
raw: true,
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ]));
|
||||||
|
|
||||||
const list = groupedList
|
const list = groupedList
|
||||||
.map(item => {
|
.map(item => {
|
||||||
const stock = stockMap.get(item.stock_id) || {};
|
const stock = stockMap.get(item.stock_id) || {};
|
||||||
const store = storeMap.get(item.store_id) || {};
|
const store = storeMap.get(item.store_id) || {};
|
||||||
|
const warehouse = warehouseMap.get(item.warehouse_id) || {};
|
||||||
const barcodeSet = barcodesByStock.get(item.stock_id);
|
const barcodeSet = barcodesByStock.get(item.stock_id);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...item,
|
...item,
|
||||||
store_name: store.company_name || '',
|
store_name: store.company_name || '',
|
||||||
|
warehouse_name: warehouse.company_name || '',
|
||||||
item_name: stock.item_name || '',
|
item_name: stock.item_name || '',
|
||||||
item_code: stock.item_code || '',
|
item_code: stock.item_code || '',
|
||||||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||||||
@ -1146,6 +1302,7 @@ class StorageReportService extends Service {
|
|||||||
const stockId = Number(row.stock_id);
|
const stockId = Number(row.stock_id);
|
||||||
const spaceId = Number(row.space_id) || 0;
|
const spaceId = Number(row.space_id) || 0;
|
||||||
const storeId = Number(row.store_id);
|
const storeId = Number(row.store_id);
|
||||||
|
const whId = Number(row.warehouse_id) || 0;
|
||||||
if (!stockId || !storeId) {
|
if (!stockId || !storeId) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -1155,6 +1312,7 @@ class StorageReportService extends Service {
|
|||||||
stock_id: stockId,
|
stock_id: stockId,
|
||||||
space_id: spaceId,
|
space_id: spaceId,
|
||||||
store_id: storeId,
|
store_id: storeId,
|
||||||
|
warehouse_id: whId,
|
||||||
quantity: toNumber(row.quantity),
|
quantity: toNumber(row.quantity),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -1163,6 +1321,7 @@ class StorageReportService extends Service {
|
|||||||
const stockId = Number(row.stock_id);
|
const stockId = Number(row.stock_id);
|
||||||
const spaceId = Number(row.space_id) || 0;
|
const spaceId = Number(row.space_id) || 0;
|
||||||
const storeId = Number(row.store_id);
|
const storeId = Number(row.store_id);
|
||||||
|
const whId = Number(row.warehouse_id) || 0;
|
||||||
if (!stockId || !storeId) {
|
if (!stockId || !storeId) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -1173,6 +1332,7 @@ class StorageReportService extends Service {
|
|||||||
stock_id: stockId,
|
stock_id: stockId,
|
||||||
space_id: spaceId,
|
space_id: spaceId,
|
||||||
store_id: storeId,
|
store_id: storeId,
|
||||||
|
warehouse_id: whId,
|
||||||
quantity: 0,
|
quantity: 0,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -1226,6 +1386,7 @@ class StorageReportService extends Service {
|
|||||||
const stockId = Number(row.stock_id);
|
const stockId = Number(row.stock_id);
|
||||||
const spaceId = Number(row.space_id) || 0;
|
const spaceId = Number(row.space_id) || 0;
|
||||||
const storeId = Number(row.store_id);
|
const storeId = Number(row.store_id);
|
||||||
|
const whId = Number(row.warehouse_id) || 0;
|
||||||
const baseKey = `${stockId}_${spaceId}_${storeId}`;
|
const baseKey = `${stockId}_${spaceId}_${storeId}`;
|
||||||
const snapshot = edgeByBaseKey.get(baseKey) || {
|
const snapshot = edgeByBaseKey.get(baseKey) || {
|
||||||
begin_total: 0,
|
begin_total: 0,
|
||||||
@ -1247,12 +1408,14 @@ class StorageReportService extends Service {
|
|||||||
end_time: endTime || null,
|
end_time: endTime || null,
|
||||||
stock_id: stockId,
|
stock_id: stockId,
|
||||||
store_id: storeId,
|
store_id: storeId,
|
||||||
|
warehouse_id: whId,
|
||||||
...(isBySpace ? { space_id: spaceId } : {}),
|
...(isBySpace ? { space_id: spaceId } : {}),
|
||||||
begin_total: 0,
|
begin_total: 0,
|
||||||
end_total: 0,
|
end_total: 0,
|
||||||
inbound_total: 0,
|
inbound_total: 0,
|
||||||
outbound_total: 0,
|
outbound_total: 0,
|
||||||
store_name: '',
|
store_name: '',
|
||||||
|
warehouse_name: '',
|
||||||
item_name: '',
|
item_name: '',
|
||||||
barcode: '',
|
barcode: '',
|
||||||
item_code: '',
|
item_code: '',
|
||||||
@ -1274,19 +1437,22 @@ class StorageReportService extends Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const groupedList = [ ...groupedMap.values() ];
|
const groupedList = [ ...groupedMap.values() ];
|
||||||
const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
|
const groupedStockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
|
||||||
const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ];
|
const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ];
|
||||||
|
const warehouseIdList = [ ...new Set(groupedList.map(item => item.warehouse_id).filter(Boolean)) ];
|
||||||
const spaceIds = isBySpace
|
const spaceIds = isBySpace
|
||||||
? [ ...new Set(groupedList.map(item => item.space_id).filter(id => Number(id) > 0)) ]
|
? [ ...new Set(groupedList.map(item => item.space_id).filter(id => Number(id) > 0)) ]
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
// 复用 getStockDetails 获取商品名称和条码
|
// 复用 getStockDetails 获取商品名称和条码
|
||||||
|
// store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品
|
||||||
|
const stockDetailOptsSpace = isStoreMode ? { warehouseId: null } : {};
|
||||||
const stockMap = new Map();
|
const stockMap = new Map();
|
||||||
const barcodesByStock = new Map();
|
const barcodesByStock = new Map();
|
||||||
if (stockIds.length > 0) {
|
if (groupedStockIds.length > 0) {
|
||||||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||||||
stockIds,
|
groupedStockIds,
|
||||||
{}
|
stockDetailOptsSpace
|
||||||
);
|
);
|
||||||
for (const detail of stockDetails) {
|
for (const detail of stockDetails) {
|
||||||
const sid = Number(detail.id);
|
const sid = Number(detail.id);
|
||||||
@ -1309,7 +1475,7 @@ class StorageReportService extends Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const [ storeRows, spaceRows ] = await Promise.all([
|
const [ storeRows, spaceRows, warehouseRows ] = await Promise.all([
|
||||||
storeIdList.length > 0
|
storeIdList.length > 0
|
||||||
? ctx.model.Store.findAll({
|
? ctx.model.Store.findAll({
|
||||||
where: {
|
where: {
|
||||||
@ -1328,21 +1494,33 @@ class StorageReportService extends Service {
|
|||||||
raw: true,
|
raw: true,
|
||||||
})
|
})
|
||||||
: [],
|
: [],
|
||||||
|
warehouseIdList.length > 0
|
||||||
|
? ctx.model.Store.findAll({
|
||||||
|
where: {
|
||||||
|
id: warehouseIdList,
|
||||||
|
},
|
||||||
|
attributes: [ 'id', 'company_name' ],
|
||||||
|
raw: true,
|
||||||
|
})
|
||||||
|
: [],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ]));
|
const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ]));
|
||||||
const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ]));
|
const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ]));
|
||||||
|
const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ]));
|
||||||
|
|
||||||
const list = groupedList
|
const list = groupedList
|
||||||
.map(item => {
|
.map(item => {
|
||||||
const stock = stockMap.get(item.stock_id) || {};
|
const stock = stockMap.get(item.stock_id) || {};
|
||||||
const store = storeMap.get(item.store_id) || {};
|
const store = storeMap.get(item.store_id) || {};
|
||||||
|
const warehouse = warehouseMap.get(item.warehouse_id) || {};
|
||||||
const barcodeSet = barcodesByStock.get(item.stock_id);
|
const barcodeSet = barcodesByStock.get(item.stock_id);
|
||||||
const space = isBySpace ? (spaceMap.get(Number(item.space_id)) || {}) : null;
|
const space = isBySpace ? (spaceMap.get(Number(item.space_id)) || {}) : null;
|
||||||
|
|
||||||
const merged = {
|
const merged = {
|
||||||
...item,
|
...item,
|
||||||
store_name: store.company_name || '',
|
store_name: store.company_name || '',
|
||||||
|
warehouse_name: warehouse.company_name || '',
|
||||||
item_name: stock.item_name || '',
|
item_name: stock.item_name || '',
|
||||||
item_code: stock.item_code || '',
|
item_code: stock.item_code || '',
|
||||||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||||||
|
|||||||
@ -1,6 +1,11 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const crypto = require('node:crypto');
|
const crypto = require('node:crypto');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const fsp = require('node:fs/promises');
|
||||||
|
const os = require('node:os');
|
||||||
|
const path = require('node:path');
|
||||||
|
const ExcelJS = require('exceljs');
|
||||||
const Service = require('egg').Service;
|
const Service = require('egg').Service;
|
||||||
const { Op } = require('sequelize');
|
const { Op } = require('sequelize');
|
||||||
|
|
||||||
@ -1448,12 +1453,9 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
|
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
|
||||||
const offset = (page - 1) * pageSize;
|
const offset = (page - 1) * pageSize;
|
||||||
|
|
||||||
// OR 查询两边,兼容新旧签约数据
|
// 仓库查看自己签约的货主列表:仓库在 warehouse_id 方,货主在 store_id 方
|
||||||
const where = {
|
const where = {
|
||||||
[Op.or]: [
|
warehouse_id: currentSubject.id,
|
||||||
{ store_id: currentSubject.id },
|
|
||||||
{ warehouse_id: currentSubject.id },
|
|
||||||
],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const relationId = this.resolveRelationId(data);
|
const relationId = this.resolveRelationId(data);
|
||||||
@ -1461,16 +1463,10 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
where.id = relationId;
|
where.id = relationId;
|
||||||
}
|
}
|
||||||
|
|
||||||
const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true });
|
const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.store_id, 'counterparty_id', { allowEmpty: true });
|
||||||
if (counterpartyId) {
|
if (counterpartyId) {
|
||||||
// 对方可能在 store_id 或 warehouse_id,两边都过滤
|
// 对方(货主)在 store_id 方
|
||||||
where[Op.and] = where[Op.and] || [];
|
where.store_id = counterpartyId;
|
||||||
where[Op.and].push({
|
|
||||||
[Op.or]: [
|
|
||||||
{ store_id: counterpartyId, warehouse_id: currentSubject.id },
|
|
||||||
{ warehouse_id: counterpartyId, store_id: currentSubject.id },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const authStatus = this.normalizeAuthStatus(data.auth_status);
|
const authStatus = this.normalizeAuthStatus(data.auth_status);
|
||||||
@ -1478,16 +1474,9 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
where.auth_status = authStatus;
|
where.auth_status = authStatus;
|
||||||
}
|
}
|
||||||
|
|
||||||
const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status;
|
const rawUseStatus = data.use_status !== undefined ? data.use_status : data.warehouse_use_status;
|
||||||
if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') {
|
if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') {
|
||||||
// 同时过滤 store_use_status 和 warehouse_use_status
|
where.warehouse_use_status = Number(rawUseStatus);
|
||||||
where[Op.and] = where[Op.and] || [];
|
|
||||||
where[Op.and].push({
|
|
||||||
[Op.or]: [
|
|
||||||
{ store_use_status: Number(rawUseStatus), store_id: currentSubject.id },
|
|
||||||
{ warehouse_use_status: Number(rawUseStatus), warehouse_id: currentSubject.id },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
|
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
|
||||||
@ -1568,12 +1557,9 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
|
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
|
||||||
const offset = (page - 1) * pageSize;
|
const offset = (page - 1) * pageSize;
|
||||||
|
|
||||||
// OR 查询两边,兼容新旧签约数据
|
// 货主查看自己签约的仓库列表:货主在 store_id 方,仓库在 warehouse_id 方
|
||||||
const where = {
|
const where = {
|
||||||
[Op.or]: [
|
store_id: currentSubject.id,
|
||||||
{ store_id: currentSubject.id },
|
|
||||||
{ warehouse_id: currentSubject.id },
|
|
||||||
],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const relationId = this.resolveRelationId(data);
|
const relationId = this.resolveRelationId(data);
|
||||||
@ -1583,14 +1569,8 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
|
|
||||||
const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true });
|
const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true });
|
||||||
if (counterpartyId) {
|
if (counterpartyId) {
|
||||||
// 对方可能在 store_id 或 warehouse_id,两边都过滤
|
// 对方(仓库)在 warehouse_id 方
|
||||||
where[Op.and] = where[Op.and] || [];
|
where.warehouse_id = counterpartyId;
|
||||||
where[Op.and].push({
|
|
||||||
[Op.or]: [
|
|
||||||
{ store_id: counterpartyId, warehouse_id: currentSubject.id },
|
|
||||||
{ warehouse_id: counterpartyId, store_id: currentSubject.id },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const authStatus = this.normalizeAuthStatus(data.auth_status);
|
const authStatus = this.normalizeAuthStatus(data.auth_status);
|
||||||
@ -1600,14 +1580,7 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
|
|
||||||
const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status;
|
const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status;
|
||||||
if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') {
|
if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') {
|
||||||
// 同时过滤 store_use_status 和 warehouse_use_status
|
where.store_use_status = Number(rawUseStatus);
|
||||||
where[Op.and] = where[Op.and] || [];
|
|
||||||
where[Op.and].push({
|
|
||||||
[Op.or]: [
|
|
||||||
{ store_use_status: Number(rawUseStatus), store_id: currentSubject.id },
|
|
||||||
{ warehouse_use_status: Number(rawUseStatus), warehouse_id: currentSubject.id },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
|
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
|
||||||
@ -2213,6 +2186,34 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
limit: pageSize,
|
limit: pageSize,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 收集所有需要回填姓名的操作人 ID
|
||||||
|
const accountIdSet = new Set();
|
||||||
|
for (const item of rows) {
|
||||||
|
const payload = item && typeof item.get === 'function'
|
||||||
|
? item.get({ plain: true })
|
||||||
|
: (item || {});
|
||||||
|
if (payload.operator_id) accountIdSet.add(Number(payload.operator_id));
|
||||||
|
if (payload.created_by) accountIdSet.add(Number(payload.created_by));
|
||||||
|
}
|
||||||
|
const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0);
|
||||||
|
|
||||||
|
// 批量查询账号姓名
|
||||||
|
let accountNameMap = {};
|
||||||
|
if (accountIds.length > 0) {
|
||||||
|
try {
|
||||||
|
const accounts = await ctx.model.Account.findAll({
|
||||||
|
attributes: [ 'id', 'real_name' ],
|
||||||
|
where: { id: { [Op.in]: accountIds } },
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
for (const acc of accounts) {
|
||||||
|
accountNameMap[Number(acc.id)] = acc.real_name || '';
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
ctx.logger.warn('[queryPrintQuantityLogs] 批量查询操作人姓名失败,不影响主流程: %s', err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const total = Number(count || 0);
|
const total = Number(count || 0);
|
||||||
const totalPages = total > 0 ? Math.ceil(total / pageSize) : 0;
|
const totalPages = total > 0 ? Math.ceil(total / pageSize) : 0;
|
||||||
|
|
||||||
@ -2224,6 +2225,13 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
? item.get({ plain: true })
|
? item.get({ plain: true })
|
||||||
: (item || {});
|
: (item || {});
|
||||||
|
|
||||||
|
const operatorId = payload.operator_id !== undefined && payload.operator_id !== null
|
||||||
|
? Number(payload.operator_id)
|
||||||
|
: null;
|
||||||
|
const createdBy = payload.created_by !== undefined && payload.created_by !== null
|
||||||
|
? Number(payload.created_by)
|
||||||
|
: null;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: Number(payload.id || 0),
|
id: Number(payload.id || 0),
|
||||||
contract_id: Number(payload.contract_id || 0),
|
contract_id: Number(payload.contract_id || 0),
|
||||||
@ -2242,12 +2250,10 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
balance_before: Number(payload.balance_before || 0),
|
balance_before: Number(payload.balance_before || 0),
|
||||||
balance_after: Number(payload.balance_after || 0),
|
balance_after: Number(payload.balance_after || 0),
|
||||||
reason: payload.reason || '',
|
reason: payload.reason || '',
|
||||||
operator_id: payload.operator_id !== undefined && payload.operator_id !== null
|
operator_id: operatorId,
|
||||||
? Number(payload.operator_id)
|
operator_name: operatorId ? (accountNameMap[operatorId] || '') : '',
|
||||||
: null,
|
created_by: createdBy,
|
||||||
created_by: payload.created_by !== undefined && payload.created_by !== null
|
created_by_name: createdBy ? (accountNameMap[createdBy] || '') : '',
|
||||||
? Number(payload.created_by)
|
|
||||||
: null,
|
|
||||||
created_at: payload.created_at || null,
|
created_at: payload.created_at || null,
|
||||||
updated_at: payload.updated_at || null,
|
updated_at: payload.updated_at || null,
|
||||||
};
|
};
|
||||||
@ -2264,6 +2270,182 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 导出面单余额变更日志。
|
||||||
|
* 查询所有匹配条件的记录,生成 Excel 文件上传至 COS,返回下载信息。
|
||||||
|
*
|
||||||
|
* @param {Object} data 请求数据。
|
||||||
|
* @param {number|string} data.store_id 货主ID(必填)。
|
||||||
|
* @param {Object} [data.where] 动态筛选条件,与 queryPrintQuantityLogs 的 where 语义一致。
|
||||||
|
* @return {Promise<Object>} 包含 url、fileKey、filename 的对象。
|
||||||
|
*/
|
||||||
|
async exportPrintQuantityLogs(data = {}) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const currentSubject = await this.getCurrentSubject();
|
||||||
|
const storeId = this.toPositiveNumber(data.store_id, 'store_id');
|
||||||
|
|
||||||
|
if (!currentSubject.isWarehouse && Number(currentSubject.id) !== Number(storeId)) {
|
||||||
|
throw this.createError('仅可导出当前货主的面单余额变更日志', 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
const where = {
|
||||||
|
store_id: Number(storeId),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (currentSubject.isWarehouse) {
|
||||||
|
where.warehouse_id = Number(currentSubject.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dynamicConditions = this.ctx.whereParsed && Array.isArray(this.ctx.whereParsed.dynamicConditions)
|
||||||
|
? this.ctx.whereParsed.dynamicConditions.filter(Boolean)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
if (dynamicConditions.length > 0) {
|
||||||
|
where[Op.and] = dynamicConditions;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询全部匹配记录
|
||||||
|
const rows = await ctx.model.StoreWarehousePrintQuantityLog.findAll({
|
||||||
|
where,
|
||||||
|
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 收集操作人 ID,批量查询姓名
|
||||||
|
const accountIdSet = new Set();
|
||||||
|
for (const item of rows) {
|
||||||
|
if (item.operator_id) accountIdSet.add(Number(item.operator_id));
|
||||||
|
if (item.created_by) accountIdSet.add(Number(item.created_by));
|
||||||
|
}
|
||||||
|
const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0);
|
||||||
|
const accountNameMap = {};
|
||||||
|
if (accountIds.length > 0) {
|
||||||
|
const accounts = await ctx.model.Account.findAll({
|
||||||
|
attributes: [ 'id', 'real_name' ],
|
||||||
|
where: { id: { [Op.in]: accountIds } },
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
for (const acc of accounts) {
|
||||||
|
accountNameMap[Number(acc.id)] = acc.real_name || '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成 Excel
|
||||||
|
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'print_qty_log_export_'));
|
||||||
|
const filename = `面单余额变更日志_${storeId}_${Date.now()}.xlsx`;
|
||||||
|
const filePath = path.join(tempDir, filename);
|
||||||
|
|
||||||
|
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
|
||||||
|
filename: filePath,
|
||||||
|
useStyles: true,
|
||||||
|
useSharedStrings: true,
|
||||||
|
});
|
||||||
|
const worksheet = workbook.addWorksheet('面单余额变更日志');
|
||||||
|
|
||||||
|
worksheet.columns = [
|
||||||
|
{ header: '记录ID', key: 'id', width: 10 },
|
||||||
|
{ header: '签约关系ID', key: 'contract_id', width: 14 },
|
||||||
|
{ header: '货主ID', key: 'store_id', width: 10 },
|
||||||
|
{ header: '仓库ID', key: 'warehouse_id', width: 10 },
|
||||||
|
{ header: '变更类型', key: 'change_type_label', width: 12 },
|
||||||
|
{ header: '业务来源类型', key: 'business_type_label', width: 14 },
|
||||||
|
{ header: '业务关联ID', key: 'business_id', width: 14 },
|
||||||
|
{ header: '变更数量', key: 'change_quantity', width: 12 },
|
||||||
|
{ header: '变更前余额', key: 'balance_before', width: 14 },
|
||||||
|
{ header: '变更后余额', key: 'balance_after', width: 14 },
|
||||||
|
{ header: '变更原因', key: 'reason', width: 30 },
|
||||||
|
{ header: '操作人', key: 'operator_name', width: 14 },
|
||||||
|
{ header: '创建人', key: 'created_by_name', width: 14 },
|
||||||
|
{ header: '创建时间', key: 'created_at', width: 22 },
|
||||||
|
{ header: '更新时间', key: 'updated_at', width: 22 },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const item of rows) {
|
||||||
|
const operatorId = item.operator_id !== undefined && item.operator_id !== null
|
||||||
|
? Number(item.operator_id)
|
||||||
|
: null;
|
||||||
|
const createdBy = item.created_by !== undefined && item.created_by !== null
|
||||||
|
? Number(item.created_by)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
worksheet.addRow({
|
||||||
|
id: Number(item.id || 0),
|
||||||
|
contract_id: Number(item.contract_id || 0),
|
||||||
|
store_id: Number(item.store_id || 0),
|
||||||
|
warehouse_id: Number(item.warehouse_id || 0),
|
||||||
|
change_type_label: CHANGE_TYPE_LABEL_MAP[item.change_type] || item.change_type || '',
|
||||||
|
business_type_label: item.business_type
|
||||||
|
? (BUSINESS_TYPE_LABEL_MAP[item.business_type] || item.business_type)
|
||||||
|
: '-',
|
||||||
|
business_id: item.business_id !== undefined && item.business_id !== null
|
||||||
|
? Number(item.business_id)
|
||||||
|
: '',
|
||||||
|
change_quantity: Number(item.change_quantity || 0),
|
||||||
|
balance_before: Number(item.balance_before || 0),
|
||||||
|
balance_after: Number(item.balance_after || 0),
|
||||||
|
reason: item.reason || '',
|
||||||
|
operator_name: operatorId ? (accountNameMap[operatorId] || '') : '',
|
||||||
|
created_by_name: createdBy ? (accountNameMap[createdBy] || '') : '',
|
||||||
|
created_at: item.created_at ? String(item.created_at) : '',
|
||||||
|
updated_at: item.updated_at ? String(item.updated_at) : '',
|
||||||
|
}).commit();
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheet.commit();
|
||||||
|
await workbook.commit();
|
||||||
|
|
||||||
|
// 上传至 COS
|
||||||
|
const uploadService = ctx.service && ctx.service.systems && ctx.service.systems.upload;
|
||||||
|
let uploadResult = {};
|
||||||
|
if (uploadService && typeof uploadService.uploadFile === 'function') {
|
||||||
|
const stat = await fsp.stat(filePath);
|
||||||
|
const uploadStream = fs.createReadStream(filePath);
|
||||||
|
uploadStream.filename = filename;
|
||||||
|
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||||||
|
uploadStream.fileSize = stat.size;
|
||||||
|
|
||||||
|
uploadResult = await uploadService.uploadFile(uploadStream, {
|
||||||
|
key: `export/print_quantity_log/${storeId}/${filename}`,
|
||||||
|
category: 'document',
|
||||||
|
mimetype: 'xls,xlsx,csv',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (typeof uploadService.uploadSuccessNotify === 'function') {
|
||||||
|
await uploadService.uploadSuccessNotify({
|
||||||
|
url: uploadResult.fileName,
|
||||||
|
fileKey: uploadResult.fileName,
|
||||||
|
fileName: filename,
|
||||||
|
fileType: 'document',
|
||||||
|
mimeType: uploadStream.mimeType,
|
||||||
|
fileSize: stat.size,
|
||||||
|
category: 'document',
|
||||||
|
businessType: 'printQuantityLogExport',
|
||||||
|
businessId: String(storeId),
|
||||||
|
uploaderType: ctx.user?.role || 'system_api',
|
||||||
|
uploaderDept: ctx.user?.department || '',
|
||||||
|
}).catch(err => {
|
||||||
|
ctx.logger.warn('[storeWarehouse.exportPrintQuantityLogs] 上传通知失败: %s', err.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清理临时文件
|
||||||
|
try {
|
||||||
|
await fsp.rm(tempDir, { recursive: true, force: true });
|
||||||
|
} catch (cleanErr) {
|
||||||
|
ctx.logger.warn('[storeWarehouse.exportPrintQuantityLogs] 清理临时文件失败: %s', cleanErr.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
filename,
|
||||||
|
fileKey: uploadResult.fileName || '',
|
||||||
|
url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '',
|
||||||
|
cdnUrl: uploadResult.cdnUrl || uploadResult.url || '',
|
||||||
|
cosUrl: uploadResult.cosUrl || '',
|
||||||
|
total_count: rows.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取策略配置字段。
|
* 获取策略配置字段。
|
||||||
*
|
*
|
||||||
@ -2465,12 +2647,15 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
let qimenCustomerId = null;
|
let qimenCustomerId = null;
|
||||||
let qimenWarehouseCode = null;
|
let qimenWarehouseCode = null;
|
||||||
|
|
||||||
|
// 外部入参优先,未传入时才从 qimen_app 表解析
|
||||||
|
const externalCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100);
|
||||||
|
|
||||||
if (isQimenWms) {
|
if (isQimenWms) {
|
||||||
qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100);
|
qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100);
|
||||||
if (!qimenAppKey) {
|
if (!qimenAppKey) {
|
||||||
throw this.createError('奇门接口类型下 qimen_app_key 参数不能为空', 400);
|
throw this.createError('奇门接口类型下 qimen_app_key 参数不能为空', 400);
|
||||||
}
|
}
|
||||||
qimenCustomerId = await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction });
|
qimenCustomerId = externalCustomerId || await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction });
|
||||||
qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100);
|
qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100);
|
||||||
if (!qimenWarehouseCode) {
|
if (!qimenWarehouseCode) {
|
||||||
throw this.createError('奇门接口类型下 qimen_warehouse_code 参数不能为空', 400);
|
throw this.createError('奇门接口类型下 qimen_warehouse_code 参数不能为空', 400);
|
||||||
@ -2478,9 +2663,8 @@ class SettingStoreWarehouseService extends Service {
|
|||||||
} else {
|
} else {
|
||||||
// OPEN_API: 奇门字段可选输入
|
// OPEN_API: 奇门字段可选输入
|
||||||
qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100) || null;
|
qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100) || null;
|
||||||
qimenCustomerId = qimenAppKey
|
qimenCustomerId = externalCustomerId
|
||||||
? await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction })
|
|| (qimenAppKey ? await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction }) : null);
|
||||||
: null;
|
|
||||||
qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100) || null;
|
qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100) || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user