diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index dfaa61e..2dc7da3 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -1,5 +1,9 @@ 'use strict'; const MainService = require('../../main'); + +const ENTRY_EXPORT_TASK_CACHE_KEY_PREFIX = 'entry_export_task_'; +const ENTRY_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + /** * 系统方法层:storage.entry(入库单相关接口包装层)。 * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 @@ -9,9 +13,9 @@ class entryService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,get,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; - const _noNeedLog = 'list,get,getPrintData,reviewEntry,containerList'; - const _noNeedAuth = 'list,get,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; + const _noNeedRight = 'list,listStore,get,getStore,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + const _noNeedLog = 'list,listStore,get,getStore,getPrintData,reviewEntry,export,exportTaskProgress,storeExport,storeExportTaskProgress'; + const _noNeedAuth = 'list,listStore,get,getStore,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList,export,exportTaskProgress,storeExport,storeExportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -37,6 +41,40 @@ class entryService extends MainService { return this.success('ok', result); } + /** + * 货主侧入库单列表查询。 + * 与 list 共享底层逻辑,但以货主维度(store_id)过滤,不使用仓库维度(warehouse_id)。 + * 货主登录后仅能看到自己货主下的入库单。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 动态筛选条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一 success 包装 + */ + async listStore(data = {}) { + const { service } = this; + const { pagination, sort } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.storage.entry.list(where, pagination, sort, 'store'); + + // 裁剪货主侧冗余字段:货主自己的 store_name/store 关联、奇门编码 + if (result && result.data && Array.isArray(result.data.list)) { + result.data.list.forEach(item => { + delete item.store_name; + delete item.store; + delete item.qimen_owner_code; + delete item.qimen_warehouse_code; + }); + } + return this.success('ok', result); + } + /** * 查询入库单详情(与原 storage.directInbound.getItems 输出格式一致)。 * 返回入库单基本信息(id、entry_order_code、order_status、store_remask)、 @@ -53,6 +91,22 @@ class entryService extends MainService { return this.success('ok', result); } + /** + * 货主侧查询入库单详情。与 get 共享底层逻辑, + * 但以货主维度(store_id)校验权限(不使用 warehouse_id), + * 货主登录后仅能查看自己货主下的入库单明细。 + * 返回结构与 get 一致。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID(必填) + * @return {Promise} 统一 success 包装 + */ + async getStore(data = {}) { + const { service } = this; + const { id } = data || {}; + const result = await service.systems.storage.entry.get({ id }, 'store'); + return this.success('ok', result); + } + /** * 作废入库单。 * 支持传入单个 id 或批量 ids,保持透传给业务层处理。 @@ -379,5 +433,359 @@ class entryService extends MainService { return this.fail(result?.message || '审核失败', result, 400); } + /** + * 提交入库单导出任务(复用 list 的筛选语义与排序规则)。 + * 导出分为两个 sheet:Sheet1=入库单列表,Sheet2=入库单明细(按入库单分页拉取写入流)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与 list 一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async export(data = {}) { + const { service } = this; + const { where, sort } = data || {}; + + 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: 5, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.entry.exportEntryOrders({ + where: this.isPlainObject(where) ? { ...where } : {}, + sort: this.isPlainObject(sort) ? { ...sort } : {}, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + 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(), + }); + } + + /** + * 查询入库单导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async exportTaskProgress(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 `entry_${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 `${ENTRY_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入入库单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + 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, ENTRY_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.entry.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取入库单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + 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(`[storage.entry.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + + /** + * 提交货主侧入库单导出任务(复用 listStore 的筛选语义与排序规则)。 + * 导出分为两个 sheet:Sheet1=入库单列表,Sheet2=入库单明细(按入库单分页拉取写入流)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与 listStore 一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async storeExport(data = {}) { + const { service } = this; + const { where, sort } = data || {}; + + 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: 5, + message: '货主侧入库单导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.entry.exportStoreEntryOrders({ + where: this.isPlainObject(where) ? { ...where } : {}, + sort: this.isPlainObject(sort) ? { ...sort } : {}, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + message: safeProgress.message || '货主侧入库单导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + 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(), + }); + } + + /** + * 查询货主侧入库单导出任务进度。 + * 复用 exportTaskProgress 的缓存查询逻辑,任务 ID 前缀不同。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async storeExportTaskProgress(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, + }); + } + } module.exports = entryService; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 1cf6234..56c7ec0 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -1,6 +1,9 @@ 'use strict'; const MainService = require('../../main'); + +const RECEIVING_EXPORT_TASK_CACHE_KEY_PREFIX = 'receiving_export_task_'; +const RECEIVING_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; /** * 系统方法层:storage.receiving(收货单相关接口包装层)。 * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 @@ -10,9 +13,9 @@ class configService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail'; - const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail'; - const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail'; + const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress'; + const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress'; + const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -39,6 +42,55 @@ class configService extends MainService { return this.success('ok', result); } + /** + * 货主侧收货单列表查询(system method 包装层)。 + * 以当前平台激活的货主 store_id 为维度查询收货单。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数 + * @param {Object} [data.where] 筛选条件 + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应 + */ + async getStoreReceivingList(data) { + const { ctx, app } = this; + const { pagination, sort } = data; + + // 从平台激活上下文获取 store_id(使用原生查询避免 AccountPlatformActive 无 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 { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + const { service } = this; + const result = await service.systems.storage.receiving.getStoreReceivingList( + where, + storeId, + pagination, + sort + ); + + return this.success('ok', result); + } + /** * 收货单详情查询(分页返回明细)。 * @param {Object} data 请求体 @@ -280,5 +332,252 @@ class configService extends MainService { return this.success('查询成功', result.data); } + /** + * 提交收货单导出任务(复用 getStoreReceivingList 的筛选语义与排序规则)。 + * 导出分为两个 sheet:Sheet1=收货单列表,Sheet2=收货单明细。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件(与 getStoreReceivingList 一致) + * @param {Object} [data.sort] 排序参数 + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async export(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 { sort = {} } = data; + + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + 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: 5, + message: '收货单导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.receiving.exportReceivingList({ + where, + storeId, + sort, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + message: safeProgress.message || '收货单导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + 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(), + }); + } + + /** + * 查询收货单导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一成功包装响应 + */ + async exportTaskProgress(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。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const storeId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `receiving_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 `${RECEIVING_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入收货单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + 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, RECEIVING_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[storage.receiving.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取收货单导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + 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(`[storage.receiving.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + } module.exports = configService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 9817c79..7b76949 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1,9 +1,18 @@ 'use strict'; +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 { parseWhereConditions } = require('../../../lib/query_condition_parser'); const DAY_MS = 24 * 60 * 60 * 1000; +const RECEIVING_EXPORT_PAGE_SIZE = 200; +const RECEIVING_ITEMS_FETCH_BATCH_SIZE = 100; + function getStartOfDayMs(value) { const date = new Date(value); if (Number.isNaN(date.getTime())) return null; @@ -366,8 +375,8 @@ class ReceivingService extends Service { available_quantity: availableQuantity, lock_rate: parseFloat(lockRate), lock_rate_display: `${lockRate}%`, - create_at_display: item.create_at ? this.formatDate(item.create_at) : '', - update_at_display: item.update_at ? this.formatDate(item.update_at) : '', + create_at_display: item.created_at ? this.app.formatDate(item.created_at) : '', + update_at_display: item.updated_at ? this.app.formatDate(item.updated_at) : '', }; }); @@ -425,6 +434,201 @@ class ReceivingService extends Service { }; } } + /** + * 货主侧收货单列表查询。 + * 以 store_id 为维度查询收货单,支持分页、多条件筛选与排序。 + * @param {Object} where 动态筛选条件 + * @param {number} storeId 货主ID(必填) + * @param {Object} [pageParams] 分页参数 + * @param {number} [pageParams.page=1] 页码 + * @param {number} [pageParams.pageSize=20] 每页条数 + * @param {Object} [sortParams] 排序参数 + * @param {string} [sortParams.sortField='created_at'] 排序字段 + * @param {string} [sortParams.sortOrder='DESC'] 排序方向 + * @return {Promise} 列表、分页与汇总信息 + */ + async getStoreReceivingList(where, storeId, pageParams = {}, sortParams = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const { page = 1, pageSize = 20 } = pageParams; + const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams; + + try { + const queryOptions = { + where: { + [Op.and]: [ + { store_id: storeId }, + ], + }, + order: [], + attributes: { + exclude: [ 'deleted_at' ], + }, + }; + + const normalizedWhere = where && typeof where === 'object' ? where : {}; + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + if (!parsed.ok) { + return { + code: 400, + data: { + list: [], + pagination: { page: Number(page), pageSize: Number(pageSize), total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + summary: { total_quantity: 0, total_locked: 0, total_available: 0, total_items: 0 }, + }, + message: `筛选条件解析失败: ${parsed.reason}`, + }; + } + parsedResult = parsed.result; + } + + const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ]; + const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere; + + if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') { + const quickValue = String(quickWhereRaw.value).trim(); + dynamicConditions.push({ + [Op.or]: { + store_name: { [Sequelize.Op.like]: `%${quickValue}%` }, + receiving_number: { [Sequelize.Op.like]: `%${quickValue}%` }, + tracking_number: { [Sequelize.Op.like]: `%${quickValue}%` }, + creator_snapshot: { [Sequelize.Op.like]: `%${quickValue}%` }, + license_plate: { [Sequelize.Op.like]: `%${quickValue}%` }, + }, + }); + } + + if (dynamicConditions.length > 0) { + queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions }); + } + + const validSortFields = [ 'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id' ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + queryOptions.order.push([ actualSortField, actualSortOrder ]); + + const offset = (page - 1) * pageSize; + + const [ total, data ] = await Promise.all([ + ctx.model.Receiving.count({ + where: queryOptions.where, + distinct: true, + }), + ctx.model.Receiving.findAll({ + ...queryOptions, + limit: Number(pageSize), + offset: Number(offset), + distinct: true, + raw: true, + }), + ]); + + const totalPages = Math.ceil(total / pageSize); + const hasPrevious = page > 1; + const hasNext = page < totalPages; + + // 获取收货单图片 + const stockIds = data.map(item => item.id); + let images = []; + if (stockIds.length > 0) { + images = await ctx.model.FileReference.findAll({ + where: { + business_type: 'receiving', + business_id: { [Op.in]: stockIds }, + }, + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: true, + }, + ], + }); + } + + const processedData = data.map(item => { + const availableQuantity = Math.max(0, item.total_quantity || 0); + const itemImages = images + .filter(row => Number(row.business_id) === item.id) + .map(row => row.file.file_url); + // 从 creator_snapshot 解析操作人姓名 + let creatorName = ''; + try { + if (item.creator_snapshot) { + const snapshot = JSON.parse(item.creator_snapshot); + creatorName = snapshot.name || ''; + } + } catch (_) { + // ignore parse error + } + return { + ...item, + images: itemImages, + available_quantity: availableQuantity, + lock_rate: 0, + lock_rate_display: '0%', + creator_name: creatorName, + create_at_display: item.created_at ? this.app.formatDate(item.created_at) : '', + update_at_display: item.updated_at ? this.app.formatDate(item.updated_at) : '', + }; + }); + + const summary = { + total_quantity: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), + total_locked: 0, + total_available: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), + total_items: data.length, + }; + + return { + code: 200, + data: { + list: processedData, + pagination: { + page: Number(page), + pageSize: Number(pageSize), + total, + totalPages, + hasPrevious, + hasNext, + }, + summary, + queryInfo: { + conditions: normalizedWhere, + sortField: actualSortField, + sortOrder: actualSortOrder, + hasBarcodeSearch: false, + }, + }, + message: '查询成功', + }; + } catch (error) { + ctx.logger.error('[ReceivingService.getStoreReceivingList] 查询失败:', error); + return { + code: 500, + data: { + list: [], + pagination: { page: Number(page || 1), pageSize: Number(pageSize || 20), total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, + summary: { total_quantity: 0, total_locked: 0, total_available: 0, total_items: 0 }, + }, + message: `查询失败: ${error.message}`, + }; + } + } /** * 获取收货单详情(主单 + 明细分页 + 图片)。 * @param {Object} data 请求体 @@ -2904,11 +3108,11 @@ class ReceivingService extends Service { async deleteDetail(data) { const ctx = this.ctx; const { detail_id } = data; - const creator_id = ctx.user.employees_id; const warehouse_id = ctx.user.store_id; - // 验证明细是否存在 + // 验证明细是否存在(通过收货单的 warehouse_id 做权限校验,不限制 creator_id, + // 以允许同一仓库下不同操作员删除彼此创建的明细,与 get 方法行为保持一致) const detail = await ctx.model.ReceivingDetail.findOne({ - where: { id: detail_id, creator_id }, + where: { id: detail_id }, include: [ { model: ctx.model.Receiving, @@ -4507,6 +4711,433 @@ class ReceivingService extends Service { } } + /** + * 导出收货单列表(双 sheet:收货单列表 + 收货单明细)。 + * 复用 getStoreReceivingList 的筛选与排序语义,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} options 导出选项 + * @param {Object} [options.where] 筛选条件 + * @param {number} options.storeId 货主ID + * @param {Object} [options.sort] 排序参数 + * @param {Function} [options.onProgress] 进度回调 + * @return {Promise} 上传结果与统计信息 + */ + async exportReceivingList(options = {}) { + const { ctx, app } = this; + const { Sequelize } = app; + const { Op } = Sequelize; + const safeOptions = options && typeof options === 'object' ? options : {}; + const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {}; + const storeId = Number(safeOptions.storeId); + const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {}; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + + if (!storeId) { + throw new Error('货主ID不能为空,无法导出'); + } + + const sortField = sort.sortField || 'created_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const validSortFields = [ + 'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id', + ]; + const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; + + // 构建 where 条件(与 getStoreReceivingList 一致) + const queryOptions = { + where: { [Op.and]: [{ store_id: storeId }] }, + }; + + const normalizedWhere = { ...where }; + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: { + quickWhere: { bucket: 'quick' }, + }, + }); + + if (!parsed.ok) { + throw new Error(`筛选条件解析失败: ${parsed.reason}`); + } + const parsedResult = parsed.result; + + const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ]; + const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere; + + if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') { + const quickValue = String(quickWhereRaw.value).trim(); + dynamicConditions.push({ + [Op.or]: { + store_name: { [Op.like]: `%${quickValue}%` }, + receiving_number: { [Op.like]: `%${quickValue}%` }, + tracking_number: { [Op.like]: `%${quickValue}%` }, + creator_snapshot: { [Op.like]: `%${quickValue}%` }, + license_plate: { [Op.like]: `%${quickValue}%` }, + }, + }); + } + + if (dynamicConditions.length > 0) { + queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions }); + } + + // ---- 分页拉取收货单列表 ---- + const totalCount = await ctx.model.Receiving.count({ + where: queryOptions.where, + distinct: true, + }); + + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 10 : 85, + message: totalCount > 0 ? `已命中 ${totalCount} 条收货单,开始导出` : '未命中数据,开始生成空文件', + }); + + const allReceivingOrders = []; + let page = 1; + let fetchedCount = 0; + + while (fetchedCount < totalCount) { + const rows = await ctx.model.Receiving.findAll({ + where: queryOptions.where, + order: [[ actualSortField, sortOrder ]], + limit: RECEIVING_EXPORT_PAGE_SIZE, + offset: (page - 1) * RECEIVING_EXPORT_PAGE_SIZE, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + allReceivingOrders.push(...rows); + fetchedCount += rows.length; + page += 1; + + await progressHandler({ + status: 'running', + progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)), + message: `正在拉取收货单列表,已完成 ${fetchedCount}/${totalCount}`, + }); + } + + // ---- 批量拉取收货单明细 ---- + const allReceivingIds = allReceivingOrders.map(r => Number(r.id)).filter(Boolean); + /** @type {Map>} receiving_id → details */ + const detailsMap = new Map(); + + if (allReceivingIds.length > 0) { + const batchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE; + const totalBatches = Math.ceil(allReceivingIds.length / batchSize); + + for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += batchSize) { + const batchIds = allReceivingIds.slice(batchIdx, batchIdx + batchSize); + + const details = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: { [Op.in]: batchIds } }, + order: [[ 'receiving_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + for (const detail of details) { + const rid = Number(detail.receiving_id); + if (!detailsMap.has(rid)) { + detailsMap.set(rid, []); + } + detailsMap.get(rid).push(detail); + } + + const currentBatch = Math.floor(batchIdx / batchSize) + 1; + await progressHandler({ + status: 'running', + progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在拉取收货单明细,已完成批次 ${currentBatch}/${totalBatches}`, + }); + } + } + + await progressHandler({ + status: 'running', + progress: 55, + message: '正在生成 Excel 文件...', + }); + + // ---- 生成 Excel(流式写入,两个 Sheet) ---- + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-receiving-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `收货单导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + const normalizeCellValue = value => { + if (value === null || value === undefined) return ''; + if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString(); + return value; + }; + + const statusLabelMap = { + receiving: '收货中', + completed: '已完成', + cancelled: '已作废', + }; + + const detailStatusLabelMap = { + all_matched: '全部匹配', + partial_matched: '部分匹配', + unmatched: '未匹配', + }; + + const storageStatusLabelMap = { + none: '未入库', + waiting: '等待入库', + partial: '部分入库', + all: '全部入库', + }; + + const deliveryMethodLabelMap = { + truck: '货车', + express: '快递', + air_freight: '空运', + sea_freight: '海运', + other: '其他', + }; + + const loadingMethodLabelMap = { + with_pallet: '带托盘', + without_pallet: '不带托盘', + }; + + // Sheet 1: 收货单列表 + const sheet1 = workbook.addWorksheet('收货单列表'); + const receivingColumns = [ + { header: '收货单ID', key: 'id', width: 10 }, + { header: '收货单号', key: 'receiving_number', width: 22 }, + { header: '货主', key: 'store_name', width: 20 }, + { header: '收货状态', key: 'status_label', width: 12 }, + { header: '明细匹配状态', key: 'detail_status_label', width: 14 }, + { header: '入库状态', key: 'storage_status_label', width: 12 }, + { header: '来货方式', key: 'delivery_method_label', width: 12 }, + { header: '车牌号', key: 'license_plate', width: 14 }, + { header: '快递单号', key: 'tracking_number', width: 22 }, + { header: '装卸方式', key: 'loading_method_label', width: 12 }, + { header: '总商品种类', key: 'total_items', width: 12 }, + { header: '总数量', key: 'total_quantity', width: 12 }, + { header: '总箱数', key: 'total_boxes', width: 10 }, + { header: '总托盘数', key: 'total_pallets', width: 10 }, + { header: '审核状态', key: 'is_review_label', width: 10 }, + { header: '创建人', key: 'creator_name', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '收货开始时间', key: 'receiving_start_time', width: 20 }, + { header: '收货结束时间', key: 'receiving_end_time', width: 20 }, + { header: '创建时间', key: 'created_at', width: 20 }, + { header: '更新时间', key: 'updated_at', width: 20 }, + ]; + sheet1.columns = receivingColumns; + + for (const row of allReceivingOrders) { + let creatorName = ''; + try { + if (row.creator_snapshot) { + const snapshot = JSON.parse(row.creator_snapshot); + creatorName = snapshot.name || ''; + } + } catch (_) { /* ignore */ } + + sheet1.addRow({ + id: row.id, + receiving_number: normalizeCellValue(row.receiving_number), + store_name: normalizeCellValue(row.store_name), + status_label: statusLabelMap[row.status] || row.status || '', + detail_status_label: detailStatusLabelMap[row.detail_status] || row.detail_status || '', + storage_status_label: storageStatusLabelMap[row.storage_status] || row.storage_status || '', + delivery_method_label: deliveryMethodLabelMap[row.delivery_method] || row.delivery_method || '', + license_plate: normalizeCellValue(row.license_plate), + tracking_number: normalizeCellValue(row.tracking_number), + loading_method_label: loadingMethodLabelMap[row.loading_method] || row.loading_method || '', + total_items: row.total_items, + total_quantity: row.total_quantity, + total_boxes: row.total_boxes, + total_pallets: row.total_pallets, + is_review_label: row.is_review === 1 ? '已审核' : '未审核', + creator_name: creatorName, + remark: normalizeCellValue(row.remark), + receiving_start_time: normalizeCellValue(row.receiving_start_time), + receiving_end_time: normalizeCellValue(row.receiving_end_time), + created_at: normalizeCellValue(row.created_at), + updated_at: normalizeCellValue(row.updated_at), + }).commit(); + } + sheet1.commit(); + + await progressHandler({ + status: 'running', + progress: 70, + message: '正在写入收货单明细...', + }); + + // Sheet 2: 收货单明细 + const sheet2 = workbook.addWorksheet('收货单明细'); + const detailColumns = [ + { header: '收货单号', key: 'receiving_number', width: 22 }, + { header: '收货单ID', key: 'receiving_id', width: 12 }, + { header: '明细ID', key: 'detail_id', width: 10 }, + { header: '商品名称', key: 'product_name', width: 28 }, + { header: '商品条码', key: 'barcode', width: 20 }, + { header: '系统商品ID', key: 'system_product_id', width: 14 }, + { header: '实际收货数量', key: 'actual_quantity', width: 14 }, + { header: '箱数', key: 'box_quantity', width: 10 }, + { header: '托盘数', key: 'pallet_quantity', width: 10 }, + { header: '收货状态', key: 'receiving_status_label', width: 12 }, + { header: '入库状态', key: 'storage_status_label', width: 12 }, + { header: '已入库数量', key: 'stored_quantity', width: 12 }, + { header: '批次号', key: 'batch_number', width: 16 }, + { header: '生产日期', key: 'production_date', width: 14 }, + { header: '到期日期', key: 'expiry_date', width: 14 }, + { header: '备注', key: 'remark', width: 30 }, + { header: '创建时间', key: 'created_at', width: 20 }, + ]; + sheet2.columns = detailColumns; + + // 构建 receiving_number 映射 + const receivingCodeMap = new Map(); + for (const row of allReceivingOrders) { + receivingCodeMap.set(Number(row.id), row.receiving_number || ''); + } + + const detailReceivingStatusLabelMap = { + pending: '待收货', + receiving: '收货中', + completed: '已完成', + cancelled: '已作废', + }; + + const detailStorageStatusLabelMap = { + none: '未入库', + waiting: '等待入库', + partial: '部分入库', + all: '全部入库', + }; + + // 按收货单分页写入明细 + const itemBatchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE; + let itemWrittenCount = 0; + const totalReceivingOrders = allReceivingIds.length; + + for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += itemBatchSize) { + const batchIds = allReceivingIds.slice(batchIdx, batchIdx + itemBatchSize); + + for (const rid of batchIds) { + const receivingNumber = receivingCodeMap.get(rid) || ''; + const details = detailsMap.get(rid) || []; + + for (const detail of details) { + sheet2.addRow({ + receiving_number: receivingNumber, + receiving_id: rid, + detail_id: detail.id, + product_name: normalizeCellValue(detail.product_name), + barcode: normalizeCellValue(detail.barcode), + system_product_id: normalizeCellValue(detail.system_product_id), + actual_quantity: detail.actual_quantity, + box_quantity: detail.box_quantity, + pallet_quantity: detail.pallet_quantity, + receiving_status_label: detailReceivingStatusLabelMap[detail.receiving_status] || detail.receiving_status || '', + storage_status_label: detailStorageStatusLabelMap[detail.storage_status] || detail.storage_status || '', + stored_quantity: detail.stored_quantity, + batch_number: normalizeCellValue(detail.batch_number), + production_date: normalizeCellValue(detail.production_date), + expiry_date: normalizeCellValue(detail.expiry_date), + remark: normalizeCellValue(detail.remark), + created_at: normalizeCellValue(detail.created_at), + }).commit(); + } + + itemWrittenCount += 1; + } + + const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1; + const totalBatches = Math.ceil(totalReceivingOrders / itemBatchSize); + await progressHandler({ + status: 'running', + progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)), + message: `正在写入收货单明细,已完成 ${itemWrittenCount}/${totalReceivingOrders} 条收货单`, + }); + } + sheet2.commit(); + + await workbook.commit(); + + await progressHandler({ + status: 'running', + progress: 92, + message: '正在上传文件...', + }); + + // ---- 上传文件 ---- + const uploadService = ctx?.service?.systems?.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/receiving/${storeId}/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + userId: ctx.userId, + description: `收货单导出(货主${storeId}),共${totalCount}条收货单`, + }); + } + + // 清理临时文件 + try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ } + + const uploadInfo = fileRecord || uploadResult; + const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url + ? uploadInfo.url + : (typeof uploadResult === 'object' ? uploadResult.fileName : ''); + + await progressHandler({ + status: 'running', + progress: 100, + message: '导出完成', + result: { url: fileUrl, fileKey: uploadKey, total: totalCount }, + }); + + return { + url: fileUrl, + fileKey: uploadKey, + total: totalCount, + totalDetails: allReceivingIds.reduce((sum, rid) => sum + (detailsMap.get(rid) || []).length, 0), + }; + } + } module.exports = ReceivingService; diff --git a/database/migrations/20260712-add-store-receiving-permission.js b/database/migrations/20260712-add-store-receiving-permission.js new file mode 100644 index 0000000..a43e266 --- /dev/null +++ b/database/migrations/20260712-add-store-receiving-permission.js @@ -0,0 +1,163 @@ +'use strict'; + +/** + * 货主侧收货单页面权限及 API 权限迁移。 + * + * 变更内容: + * 1. 新增 web_pages 权限:收货单(货主) — 货主平台侧收货单列表页面 + * 2. 新增 api 权限:account_platform.getStoreReceivingList — 货主侧收货单查询接口 + * 3. 将上述权限授权给 货主管理员(store_admin_default, id=5) 角色 + * + * 幂等设计: + * - 先查后插(按 path + type 唯一性判断) + * - 角色权限更新使用 JSON 数组合并去重 + */ + +const TABLE_PERMISSION = 'wms_permission'; +const TABLE_ROLE = 'wms_role'; + +const STORE_ADMIN_ROLE_ID = 5; + +/** @type {{path: string, name: string|null, meta_title: string, type: string, parent_id: number|null, sort: number}[]} */ +const NEW_PERMISSIONS = [ + { + path: 'receiving_owner', + name: 'OwnerReceiving', + meta_title: '收货单(货主)', + type: 'web_pages', + parent_id: 18, // 库存 + sort: 0, + component: '@/views/storage/receiving_owner/index', + }, + { + path: 'storage.receiving.getStoreReceivingList', + name: 'storage.receiving.getStoreReceivingList', + meta_title: '货主侧收货单列表查询', + type: 'api', + parent_id: null, + sort: 0, + component: null, + }, +]; + +/** + * 获取角色当前权限 ID 数组。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @return {Promise} 权限ID数组 + */ +async function getRolePermissionIds(queryInterface, roleId) { + const [ rows ] = await queryInterface.sequelize.query( + `SELECT permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`, + { replacements: { roleId } } + ); + if (!rows || rows.length === 0) return []; + + const raw = rows[0].permissions; + if (!raw) return []; + + try { + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) { + return parsed.map(Number).filter(n => Number.isFinite(n) && n > 0); + } + } catch (_) { + // ignore + } + + return []; +} + +/** + * 保存角色权限。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {number} roleId 角色ID + * @param {number[]} permissionIds 权限ID数组 + * @return {Promise} + */ +async function saveRolePermissions(queryInterface, roleId, permissionIds) { + const unique = Array.from(new Set(permissionIds)).sort((a, b) => a - b); + const json = JSON.stringify(unique); + + await queryInterface.sequelize.query( + `UPDATE \`${TABLE_ROLE}\` SET permissions = :permissions, updated_at = NOW() WHERE id = :roleId`, + { replacements: { roleId, permissions: json } } + ); +} + +/** + * 正向迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.up = async queryInterface => { + const insertedIds = []; + + for (const perm of NEW_PERMISSIONS) { + const [ existing ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type LIMIT 1`, + { replacements: { path: perm.path, type: perm.type } } + ); + + if (existing && existing.length > 0) { + console.log(`[Migration] 权限已存在,跳过: ${perm.path} (type=${perm.type}, id=${existing[0].id})`); + insertedIds.push(existing[0].id); + continue; + } + + const [ result ] = await queryInterface.sequelize.query( + `INSERT INTO \`${TABLE_PERMISSION}\` (path, name, component, meta_title, type, parent_id, sort, status, created_at, update_at) + VALUES (:path, :name, :component, :meta_title, :type, :parent_id, :sort, 1, NOW(), NOW())`, + { replacements: { ...perm } } + ); + + const newId = result; + console.log(`[Migration] 新增权限: ${perm.path} (type=${perm.type}, id=${newId})`); + insertedIds.push(newId); + } + + // 更新 货主管理员 角色权限 + const currentIds = await getRolePermissionIds(queryInterface, STORE_ADMIN_ROLE_ID); + const mergedIds = Array.from(new Set([ ...currentIds, ...insertedIds ])).sort((a, b) => a - b); + + console.log(`[Migration] 货主管理员(id=${STORE_ADMIN_ROLE_ID}) 权限更新: [${currentIds.join(',')}] -> [${mergedIds.join(',')}]`); + await saveRolePermissions(queryInterface, STORE_ADMIN_ROLE_ID, mergedIds); + + console.log(`[Migration] 完成:新增 ${insertedIds.length} 条权限,角色权限已更新`); +}; + +/** + * 回滚迁移。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} + */ +module.exports.down = async queryInterface => { + // 1. 从角色权限中移除新增的权限 ID + const pathsToRemove = NEW_PERMISSIONS.map(p => p.path); + + const [ permRows ] = await queryInterface.sequelize.query( + `SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path IN (:paths) AND type IN (:types)`, + { + replacements: { + paths: pathsToRemove, + types: NEW_PERMISSIONS.map(p => p.type), + }, + } + ); + + const idsToRemove = permRows.map(r => r.id); + const currentIds = await getRolePermissionIds(queryInterface, STORE_ADMIN_ROLE_ID); + const filteredIds = currentIds.filter(id => !idsToRemove.includes(id)); + + await saveRolePermissions(queryInterface, STORE_ADMIN_ROLE_ID, filteredIds); + console.log(`[Migration Rollback] 角色权限已移除: ${idsToRemove.join(',')}`); + + // 2. 删除新增的权限记录 + for (const perm of NEW_PERMISSIONS) { + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type`, + { replacements: { path: perm.path, type: perm.type } } + ); + console.log(`[Migration Rollback] 已删除权限: ${perm.path}`); + } +}; diff --git a/database/migrations/20260718180000-remove-zerofill-from-wms-receiving-detail-creator-id.js b/database/migrations/20260718180000-remove-zerofill-from-wms-receiving-detail-creator-id.js new file mode 100644 index 0000000..305666e --- /dev/null +++ b/database/migrations/20260718180000-remove-zerofill-from-wms-receiving-detail-creator-id.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // 去掉 creator_id 列的 ZEROFILL 属性,避免零填充字符串导致查询匹配问题 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_receiving_detail MODIFY COLUMN creator_id bigint(20) unsigned NOT NULL' + ); + }, + + async down(queryInterface, Sequelize) { + // 回滚:恢复 ZEROFILL 属性 + await queryInterface.sequelize.query( + 'ALTER TABLE wms_receiving_detail MODIFY COLUMN creator_id bigint(20) unsigned zerofill NOT NULL' + ); + }, +};