diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index c853004..c968be1 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -2,13 +2,16 @@ const MainService = require('../../main'); +const STOCK_WAREHOUSE_EXPORT_TASK_CACHE_KEY_PREFIX = 'stock_warehouse_export_task_'; +const STOCK_WAREHOUSE_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + class WarehouseService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail'; - const _noNeedLog = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; - const _noNeedAuth = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; + const _noNeedRight = 'list,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 _noNeedAuth = 'list,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -37,6 +40,233 @@ class WarehouseService extends MainService { return this.success('ok', result); } + /** + * 提交仓库商品导出任务(复用 list 的筛选语义与排序规则)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 筛选条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @return {Promise} 统一成功包装响应,data 为导出任务信息 + */ + async export(data = {}) { + const { service } = this; + const { where, whereValue = {} } = this.prepareWhereContext(data, { + specialFieldMap: { + barcode: { + bucket: 'barcode', + }, + prohibited_type: { + bucket: 'prohibited', + field: 'id', + }, + }, + }); + + const { sort = {} } = data; + const sortField = sort.sortField || sort.sort_field || whereValue.sortField || whereValue.sort_field; + const sortOrder = sort.sortOrder || sort.sort_order || whereValue.sortOrder || whereValue.sort_order; + const sortParams = { + ...(sortField ? { sortField } : {}), + ...(sortOrder ? { sortOrder } : {}), + }; + + 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 service.systems.stockStore.exportWarehouseStock(where, sortParams); + + 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.cndUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成仓库商品导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `stock_warehouse_export_${warehouseId}_${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 `${STOCK_WAREHOUSE_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, STOCK_WAREHOUSE_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[stock.warehouse.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(`[stock.warehouse.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + /** * 查询违禁品类型列表(系统预设 + 当前仓库)。 * @return {Promise} data 为违禁品类型数组 @@ -84,6 +314,163 @@ class WarehouseService extends MainService { return this.success('ok', { data: result, code: 200 }); } + /** + * 导入仓库商品资料。 + * + * 支持直接传数组,也支持从 rows、items、list、data 中提取数组。 + * SKU 为空时创建,SKU 不为空时更新,并返回批量处理结果汇总。 + * + * @param {Object|Array} data 导入请求体或商品数组 + * @return {Promise} 导入结果汇总 + */ + async import(data = {}) { + const { service } = this; + const rows = this._normalizeWarehouseImportRows(data); + const summary = { + total_count: rows.length, + created_count: 0, + updated_count: 0, + fail_count: 0, + created_ids: [], + updated_ids: [], + fail_items: [], + }; + + if (rows.length === 0) { + return this.fail('导入数据不能为空', summary); + } + + for (let index = 0; index < rows.length; index += 1) { + const sourceRow = rows[index]; + const normalizedRow = this._normalizeWarehouseImportRow(sourceRow); + + if (!normalizedRow) { + summary.fail_count += 1; + summary.fail_items.push({ + index, + row: sourceRow, + error: '导入行数据无效', + }); + continue; + } + + try { + const hasSku = String(normalizedRow.id ?? '').trim() !== ''; + let result; + + if (hasSku) { + result = await service.systems.stockStore.saveWarehouseStock(normalizedRow); + summary.updated_count += 1; + if (result && result.id != null) { + summary.updated_ids.push(result.id); + } else { + summary.updated_ids.push(normalizedRow.id); + } + } else { + result = await service.systems.stockStore.createWarehouseStock(normalizedRow); + summary.created_count += 1; + if (result && result.id != null) { + summary.created_ids.push(result.id); + } + } + } catch (error) { + summary.fail_count += 1; + summary.fail_items.push({ + index, + row: normalizedRow, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + if (summary.created_count + summary.updated_count === 0) { + return this.fail('导入失败', summary); + } + + return this.success('导入完成', summary); + } + + /** + * 归一化仓库商品导入数据列表。 + * + * @param {Object|Array} data 导入请求体或商品数组 + * @return {Array} 商品数组 + */ + _normalizeWarehouseImportRows(data = {}) { + if (Array.isArray(data)) { + return data; + } + + if (!this.isPlainObject(data)) { + return []; + } + + const candidates = [ data.rows, data.items, data.list, data.data ]; + for (const candidate of candidates) { + if (Array.isArray(candidate)) { + return candidate; + } + } + + return []; + } + + /** + * 归一化单条仓库商品导入数据。 + * + * @param {Object} row 原始导入行 + * @return {Object|null} 归一化后的数据行 + */ + _normalizeWarehouseImportRow(row) { + if (!this.isPlainObject(row)) { + return null; + } + + const pickValue = (keys) => { + for (const key of keys) { + if (!Object.prototype.hasOwnProperty.call(row, key)) { + continue; + } + + const value = row[key]; + if (value === undefined || value === null) { + continue; + } + + if (typeof value === 'string' && value.trim() === '') { + continue; + } + + return value; + } + return undefined; + }; + + const sku = pickValue([ 'SKU', 'sku', 'id', 'item_id', 'itemId', 'stock_id', 'stockId' ]); + const itemCode = pickValue([ '商品编码', 'item_code', 'itemCode' ]) ?? ''; + const goodsCode = pickValue([ '货物编码', 'goods_code', 'goodsCode', 'cargo_code', 'cargoCode' ]) ?? ''; + const itemName = pickValue([ '商品名称', 'item_name', 'itemName' ]) + ?? itemCode + ?? goodsCode + ?? ''; + const storeId = pickValue([ 'store_id', 'storeId' ]) ?? this.ctx?.user?.store_id; + + return { + ...row, + id: sku, + store_id: storeId, + item_code: itemCode, + goods_code: goodsCode, + item_name: itemName, + sku_property: pickValue([ 'SKU规格', 'sku_property', 'skuProperty' ]) ?? '', + stock_unit: pickValue([ '库存单位', 'stock_unit', 'stockUnit' ]) ?? '', + brand_name: pickValue([ '品牌', 'brand_name', 'brandName' ]) ?? '', + gross_weight: pickValue([ '毛重', 'gross_weight', 'grossWeight' ]), + tag_price: pickValue([ '标价', 'tag_price', 'tagPrice' ]), + retail_price: pickValue([ '零售价', 'retail_price', 'retailPrice' ]), + }; + } + /** * 查询商品条码列表。 * @param {Object} data 请求体(支持分页与关键字) diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index b5a2682..a153f94 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -151,7 +151,7 @@ class configService extends MainService { } /** - * 新增一条收货明细(默认空模板)。 + * 新增一条收货明细(支持可选 item)。 * @param {Object} data 请求体 * @return {Promise} 统一成功包装响应 */ diff --git a/app/service/systemMethods/warehouse.js b/app/service/systemMethods/warehouse.js index 1f1d775..7c5afc5 100644 --- a/app/service/systemMethods/warehouse.js +++ b/app/service/systemMethods/warehouse.js @@ -369,6 +369,12 @@ class warehouseService extends MainService { } } + /** + * 获取仓位详情。 + * @param {Object} data 请求参数 + * @param {number|string} data.id 仓位ID + * @return {Promise} 标准响应结果 + */ async getSpaceInfo(data) { const { service } = this; const { id } = data; @@ -376,6 +382,9 @@ class warehouseService extends MainService { const data = await service.systems.locationZone.getSpaceInfo(id); return this.success('获取成功', { data, code: 200 }); } catch (error) { + if (error.message === '仓位不存在' || error.message === '仓位不属于当前仓库') { + return this.fail(error.message, { code: 0 }); + } return this.fail('获取失败' + error.message, { code: 0 }); } } diff --git a/app/service/systems/location_zone.js b/app/service/systems/location_zone.js index 0e73513..17fdd80 100644 --- a/app/service/systems/location_zone.js +++ b/app/service/systems/location_zone.js @@ -1226,22 +1226,49 @@ class LocationZoneService extends Service { return `为货架 ${rack.zone_code} 补齐 ${retryMissingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`; } } + /** + * 获取仓位信息(优先当前仓库,未命中时校验全局归属)。 + * @param {number|string} id 仓位ID + * @return {Promise} 仓位信息 + * @throws {Error} 仓位不存在 + * @throws {Error} 仓位不属于当前仓库 + */ async getSpaceInfo(id) { const { ctx } = this; + const warehouseId = ctx.user.store_id; + const attributes = [ 'id', 'location_type_id', 'space_code', 'custom_name', 'custom_barcode', 'space_status', 'pick_sequence' ]; try { - const space = await ctx.model.LocationSpace.findOne({ + const currentWarehouseSpace = await ctx.model.LocationSpace.findOne({ where: { id, - warehouse_id: ctx.user.store_id, + warehouse_id: warehouseId, deleted_at: null, }, - attributes: [ 'id', 'location_type_id', 'space_code', 'custom_name', 'custom_barcode', 'space_status', 'pick_sequence' ], + attributes, }); - if (!space) { + + if (currentWarehouseSpace) { + return currentWarehouseSpace; + } + + const globalSpace = await ctx.model.LocationSpace.findOne({ + where: { + id, + deleted_at: null, + }, + attributes: [ 'id', 'warehouse_id' ], + }); + + if (!globalSpace) { throw new Error('仓位不存在'); } - return space; + + if (Number(globalSpace.warehouse_id) !== Number(warehouseId)) { + throw new Error('仓位不属于当前仓库'); + } + + throw new Error('仓位不存在'); } catch (error) { ctx.logger.error('获取分区路径失败:', error); throw error; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index d844abc..ed66248 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1796,6 +1796,129 @@ class stockStoreService extends Service { } } + /** + * 导出仓库商品列表。 + * 说明:复用 getWarehouseStock 的筛选与排序语义,分页拉取全量数据后生成 Excel 并上传。 + * @param {Object} where 筛选条件 + * @param {Object} sortParams 排序参数 + * @param {string} [sortParams.sortField] 排序字段 + * @param {string} [sortParams.sortOrder] 排序方向(ASC|DESC) + * @return {Promise} 导出上传结果(含 url/fileKey 等) + */ + async exportWarehouseStock(where = {}, sortParams = {}) { + const { ctx } = this; + const warehouseId = ctx.user && ctx.user.store_id ? ctx.user.store_id : 'common'; + const pageSize = 500; + let page = 1; + let hasNext = true; + const rows = []; + + while (hasNext) { + const pageResult = await this.getWarehouseStock(where, { + page, + pageSize, + }, sortParams); + + if (!pageResult || pageResult.code !== 200) { + throw new Error(pageResult && pageResult.message ? pageResult.message : '导出仓库商品失败'); + } + + const list = pageResult.data && Array.isArray(pageResult.data.list) ? pageResult.data.list : []; + + // 收集可能的 storeIds,用于回退查询 store_remask(优先取 item.store_id,其次 item['store_warehouse.store_id']) + const storeIds = []; + for (const item of list) { + const sid = item.store_id || item['store_warehouse.store_id']; + if (sid && !storeIds.includes(Number(sid))) { + storeIds.push(Number(sid)); + } + } + + // 查询 StoreWarehouse 获取 store_remask(如果可用) + const storeMap = new Map(); + try { + if (storeIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) { + const { Op } = ctx.app.Sequelize; + const storeRows = await ctx.model.StoreWarehouse.findAll({ + attributes: ['store_id', 'store_remask'], + where: { + store_id: { [Op.in]: storeIds }, + warehouse_id: warehouseId, + }, + raw: true, + }); + for (const r of storeRows || []) { + storeMap.set(Number(r.store_id), r.store_remask); + } + } + } catch (e) { + // 查询失败不影响导出,记录日志并继续 + ctx && ctx.logger && ctx.logger.warn && ctx.logger.warn('[exportWarehouseStock] 查询 StoreWarehouse 失败', e && e.message); + } + + for (const item of list) { + const storeId = Number(item.store_id || item['store_warehouse.store_id'] || 0); + const store_remask = item.store_remask || item['store_warehouse.store_remask'] || storeMap.get(storeId) || ''; + rows.push({ + id: item.id, + item_code: item.item_code, + goods_code: item.goods_code || '', + item_name: item.item_name, + brand_name: item.brand_name || '', + sku_property: item.sku_property || '', + stock_unit: item.stock_unit || '', + tag_price: item.tag_price || '', + retail_price: item.retail_price || '', + gross_weight: item.gross_weight || '', + store_remask, + barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '', + quantity: item.quantity, + locked_quantity: item.locked_quantity, + available_quantity: item.available_quantity, + lock_rate_display: item.lock_rate_display, + create_at_display: item.create_at_display, + update_at_display: item.update_at_display, + }); + } + + hasNext = Boolean(pageResult.data && pageResult.data.pagination && pageResult.data.pagination.hasNext); + page += 1; + } + + 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')}${String(now.getMilliseconds()).padStart(3, '0')}`; + + return await ctx.service.systems.excel.generateAndUpload({ + filename: `仓库商品导出_${dateToken}.xlsx`, + dir: `exports/stock/warehouse/${warehouseId}`, + category: 'document', + sheets: [{ + name: '仓库商品', + columns: [ + { header: 'SKU', key: 'id' }, + { header: '商品编码', key: 'item_code' }, + { header: '货物编码', key: 'goods_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '品牌', key: 'brand_name' }, + { header: '规格', key: 'sku_property' }, + { header: '库存单位', key: 'stock_unit' }, + { header: '标价', key: 'tag_price' }, + { header: '零售价', key: 'retail_price' }, + { header: '毛重', key: 'gross_weight' }, + { header: '货主', key: 'store_remask' }, + { header: '条码', key: 'barcodes' }, + { header: '库存', key: 'quantity' }, + { header: '锁定库存', key: 'locked_quantity' }, + { header: '可用库存', key: 'available_quantity' }, + { header: '锁定率', key: 'lock_rate_display' }, + { header: '创建时间', key: 'create_at_display' }, + { header: '更新时间', key: 'update_at_display' }, + ], + rows, + }], + }); + } + /** * 构建Sequelize查询条件 * @param {string} fieldKey - 字段键名 @@ -2357,13 +2480,6 @@ class stockStoreService extends Service { } } - /** - * 获取仓库商品详情。 - * - * @param {object} data - 查询参数。 - * @param {number|string} data.id - 商品 ID。 - * @return {Promise} 商品详情。 - */ /** * 查询库存商品详情。 * @@ -2392,6 +2508,7 @@ class stockStoreService extends Service { 'is_batch_mgmt', 'is_shelf_life_mgmt', 'is_sn_mgmt', + 'goods_code', 'item_code', 'item_name', 'length', @@ -2434,7 +2551,7 @@ class stockStoreService extends Service { const { ctx, service } = this; const warehouseId = ctx.user.store_id; const { - item_code, item_name, sku_property, stock_unit, + item_code, item_name, goods_code, sku_property, stock_unit, packing_requirements, length, width, height, volume, gross_weight, net_weight, tag_price, retail_price, is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt, @@ -2497,6 +2614,7 @@ class stockStoreService extends Service { const updateData = { item_code, item_name, + goods_code, sku_property, stock_unit, packing_requirements, @@ -2586,7 +2704,7 @@ class stockStoreService extends Service { const { ctx, service } = this; const warehouseId = ctx.user.store_id; const { - item_code, store_id, item_name, sku_property, stock_unit, + item_code, store_id, item_name, goods_code, sku_property, stock_unit, packing_requirements, length, width, height, volume, gross_weight, net_weight, tag_price, retail_price, is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt, @@ -2610,6 +2728,7 @@ class stockStoreService extends Service { const insertData = { item_code, item_name, + goods_code, sku_property, stock_unit, packing_requirements, @@ -2648,9 +2767,15 @@ class stockStoreService extends Service { try { // 2. 开启事务 const createdRecord = await ctx.model.StockWarehouse.create(insertData, transaction); - const barcodes_arr = barcode.split(';'); + const barcodes_arr = Array.isArray(barcode) + ? barcode + : typeof barcode === 'string' + ? barcode.split(';') + : []; const existingFileIds = []; - const toCreate = barcodes_arr.filter(item => !existingFileIds.includes(item)); + const toCreate = barcodes_arr + .map(item => String(item || '').trim()) + .filter(item => item && !existingFileIds.includes(item)); // 批量操作 const promises = []; if (toCreate.length > 0) { diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index fd84cc6..6394d41 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -2052,14 +2052,19 @@ class ReceivingService extends Service { } /** - * 向收货单新增一条默认明细。 + * 向收货单新增一条收货明细。 * @param {Object} data 请求体 * @param {number} data.receiving_id 收货单ID + * @param {Object} [data.item] 可选的明细字段 * @return {Promise} 明细列表与默认选中ID + * @description 未传 `item` 时,保持原有空白明细创建行为;传入 `item` 时,合并默认值后交由 Sequelize 校验与写入,并由服务端覆盖 `receiving_id` 与 `creator_id`。 */ async addDetail(data) { const ctx = this.ctx; const { receiving_id } = data; + const item = data && data.item && typeof data.item === 'object' && !Array.isArray(data.item) + ? data.item + : {}; // 获取当前用户信息 const creator_id = ctx.user.employees_id; @@ -2085,8 +2090,7 @@ class ReceivingService extends Service { } try { - // 创建默认的收货明细 - const newDetail = await ctx.model.ReceivingDetail.create({ + const defaultDetail = { receiving_id, product_name: '新商品', barcode: '', @@ -2103,6 +2107,14 @@ class ReceivingService extends Service { remark: '', space_id: 1, creator_id, + }; + + // 允许前端传入可选明细字段,但服务端字段始终覆盖。 + const newDetail = await ctx.model.ReceivingDetail.create({ + ...defaultDetail, + ...item, + receiving_id, + creator_id, }); // 获取更新后的明细列表 diff --git a/methods/changes/system.json b/methods/changes/system.json index 5c2b740..5bc6ad9 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,104 @@ [ + { + "version": "2026.05.17-system-09", + "date": "2026-05-17", + "summary": "为 storage.receiving.deleteDetail 文档补充约束:收货单已完成/已取消时禁止删除明细", + "methods": [ + "storage.receiving.deleteDetail" + ], + "notes": [ + "在 storage.receiving.deleteDetail 的 description 中补充:若关联收货单状态为 completed(已完成)或 cancelled(已取消),接口会返回删除失败(400),不允许删除明细。", + "在 errors 中补充或合并 400 描述以明确禁止删除已完成/已取消的收货单明细。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.05.17-system-08", + "date": "2026-05-17", + "summary": "完善 storage.receiving.deleteDetail 文档:补充入参/返回/错误说明,明确用户上下文来源及删除约束", + "methods": [ + "storage.receiving.deleteDetail" + ], + "notes": [ + "补充 storage.receiving.deleteDetail 的参数说明:detail_id(来自请求体,必填);说明 creator_id 与 warehouse_id 来源于当前登录用户(ctx.user.employees_id / ctx.user.store_id)。", + "补充返回结构:成功时返回 code/message/data,data 包含 details(删除后剩余明细)和 selectId(建议选中ID);product_snapshot 若存在将被解析为对象或 null。", + "补充常见错误码:404(明细不存在或无权访问),400(收货单状态/已入库/删除失败),500(服务器异常)。", + "仅文档更新,不修改任何业务实现。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.05.17-system-05", + "date": "2026-05-17", + "summary": "移除 storage.receiving.addItem(方法已下线/实现不存在)", + "methods": [ + "storage.receiving.addItem" + ], + "notes": [ + "仅同步文档:从 methods/system.json 中移除 storage.receiving.addItem,未修改任何业务代码或实现。", + "该方法已下线或实现不存在;请以当前 methods/system.json 的 SSOT 为准。" + ], + "type": "removed" + }, + { + "version": "2026.05.17-system-04", + "date": "2026-05-17", + "summary": "新增 stock.warehouse.import:仓库商品批量 JSON 导入(数组导入),SKU 为空创建/非空更新,支持 goods_code/货物编码 导入,更新写操作日志", + "methods": [ + "stock.warehouse.import" + ], + "notes": [ + "支持直接传入商品数组 JSON(主方式为数组,兼容 rows/items/list/data 包装)。", + "每项仅需传商品相关字段;SKU 为空时创建新商品,SKU 非空时为更新操作。", + "更新操作会写入操作日志以便审计。", + "支持导入 goods_code(货物编码)字段别名。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "added" + }, + { + "version": "2026.05.17-system-03", + "date": "2026-05-17", + "summary": "完善 stock.warehouse.handleBatchChange 文档:补充入参/出参/错误示例", + "methods": [ + "stock.warehouse.handleBatchChange" + ], + "notes": [ + "补充方法入参说明:ids/method/value 的字段类型、是否必填、来源与示例;完善响应结构示例与常见错误码说明。", + "仅文档更新,不改业务实现或语义。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-02", + "date": "2026-05-17", + "summary": "stock.warehouse.export 由同步改为异步任务并新增进度查询 exportTaskProgress", + "methods": [ + "stock.warehouse.export", + "stock.warehouse.exportTaskProgress" + ], + "notes": [ + "stock.warehouse.export 改为异步提交导出任务:接口返回 task_id 与受理信息,后端异步生成导出文件。", + "新增 stock.warehouse.exportTaskProgress:按 task_id 查询任务状态与进度;当 status=success 时返回 download_url 供客户端下载;未找到时 status=not_found。", + "调用方式:先调用 stock.warehouse.export 获取 task_id,然后轮询 stock.warehouse.exportTaskProgress 直到 status=success 并获取 download_url。" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-01", + "date": "2026-05-17", + "summary": "新增 stock.warehouse.export:仓库商品导出(支持 where/sort),返回文件下载信息", + "methods": [ + "stock.warehouse.export" + ], + "notes": [ + "新增方法:stock.warehouse.export。复用 stock.warehouse.list 的 where/sort 过滤语义(支持 operator/value/type 标准 where 结构与历史简写)。", + "响应返回导出结果(示例字段:file_key、url),表示生成的 Excel 已上传并可下载/查询。" + ], + "type": "added" + }, { "version": "2026.05.16-system-01", "date": "2026-05-16", @@ -1785,5 +1885,47 @@ "同步约束变化:不再因同仓快递编码重复或平台重复直接返回 409;当 express_code 无法匹配系统快递编码时返回 400,文案为 express_code 未匹配到系统快递编码。" ], "type": "updated" + }, + { + "version": "2026.05.17-system-05", + "date": "2026-05-17", + "summary": "同步 storage.receiving.addDetail 的参数与返回值(从实现提取)", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "补充 receiving_id 入参说明", + "补充返回的 details 数组与 selectId 字段", + "补充可能的错误码:404/400/500" + ], + "type": "updated" + } + + , + { + "version": "2026.05.17-system-06", + "date": "2026-05-17", + "summary": "重新同步 addDetail 文档", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "再次从实现代码核对并补充参数/返回值/错误码,确保文档与实现一致", + "仅同步文档,不修改业务代码" + ], + "type": "updated" + }, + { + "version": "2026.05.17-system-07", + "date": "2026-05-17", + "summary": "addDetail 新增可选 item 入参并兼容空白创建链路", + "methods": [ + "storage.receiving.addDetail" + ], + "notes": [ + "item 有值时按传入字段创建(服务端覆盖 receiving_id 与 creator_id)", + "兼容不传 item 的空白创建链路;item.children 需覆盖关键字段(有则写、无则补齐)。" + ], + "type": "updated" } ] diff --git a/methods/system.json b/methods/system.json index 7760579..b4ae260 100644 --- a/methods/system.json +++ b/methods/system.json @@ -96,9 +96,110 @@ "description": "Bearer token" } ], - "params": [], - "response": [], - "errors": [] + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "要批量修改的仓库商品记录 ID 数组(stock_warehouse.id)", + "children": [ + { + "name": "id", + "type": "number", + "description": "单个记录 ID" + } + ] + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "body", + "description": "要修改的字段名,可选值:brand_name、prohibited_id、gross_weight、packing_requirements、managementFlags、stock_unit" + }, + { + "name": "value", + "type": "string|number|object", + "required": true, + "source": "body", + "description": "修改值,类型依 method 而定:brand_name/packing_requirements/stock_unit 为 string(<=255 字符);prohibited_id 为 number(整数);gross_weight 为 number(正数,可含小数);managementFlags 为 object,必须包含 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt,值为 'Y' 或 'N'" + }, + { + "name": "values", + "type": "any", + "required": false, + "source": "body", + "description": "兼容字段:当前实现以 `value` 为准,不使用 `values`。若客户端历史使用 `values`,请切换为 `value`。" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功;405 表示参数/权限校验不通过;500 表示服务器错误" + }, + { + "name": "message", + "type": "string", + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "description": "成功时返回的结果对象", + "children": [ + { + "name": "affectedRows", + "type": "number", + "description": "被更新的记录数" + }, + { + "name": "ids", + "type": "array", + "description": "请求中传入的 ids 数组" + } + ] + } + ], + "errors": [ + { + "code": "405", + "description": "请选择要修改的商品(缺少 ids 或 ids 为空)" + }, + { + "code": "405", + "description": "不支持修改的字段: {method}" + }, + { + "code": "405", + "description": "修改值不能为空" + }, + { + "code": "405", + "description": "违禁品类型必须是数字" + }, + { + "code": "405", + "description": "毛重必须是有效的正数" + }, + { + "code": "405", + "description": "管理标识必须是对象格式 / 管理标识缺少字段 / 管理标识字段值必须是 'Y' 或 'N'" + }, + { + "code": "405", + "description": "部分商品不存在或无权修改: " + }, + { + "code": "405", + "description": "缺少仓库信息" + }, + { + "code": "500", + "description": "内部错误:批量修改失败" + } + ] } ] }, @@ -10357,6 +10458,186 @@ "response": [], "errors": [] }, + { + "method": "stock.warehouse.export", + "description": "提交导出任务,返回 task_id/status/progress/message/result/error/update_time", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象,与 stock.warehouse.list 的 where 语义一致;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象,支持 sortField/sortOrder 与 sort_field/sort_order 下划线别名兼容。" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段(兼容 sort.sortField)。" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名(兼容 sort.sort_field)。" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向(ASC/DESC,大小写不敏感)。" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名(兼容 sort.sort_order)。" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "任务 ID(后端生成的唯一标识)" + }, + { + "name": "status", + "type": "string", + "description": "任务状态,枚举:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "description": "进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "description": "额外提示信息或受理消息" + }, + { + "name": "result", + "type": "object", + "description": "任务成功时返回的结果对象(可选)" + }, + { + "name": "error", + "type": "string", + "description": "失败时的错误信息(可选)" + }, + { + "name": "update_time", + "type": "string", + "description": "最近一次状态更新时间,ISO8601 字符串(可选)" + } + ], + "errors": [ + { + "code": 400, + "message": "参数格式不正确或 where 条件非法" + }, + { + "code": 500, + "message": "导出任务提交失败" + } + ] + }, + { + "method": "stock.warehouse.exportTaskProgress", + "description": "按 task_id 查询导出任务进度,未找到时 status=not_found", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID,兼容 taskId" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "任务 ID" + }, + { + "name": "status", + "type": "string", + "description": "任务状态:submitted/running/success/failed/not_found" + }, + { + "name": "progress", + "type": "number", + "description": "进度百分比(0-100)" + }, + { + "name": "message", + "type": "string", + "description": "额外提示信息" + }, + { + "name": "result", + "type": "object", + "description": "任务成功时返回的结果对象(可选)" + }, + { + "name": "error", + "type": "string", + "description": "失败时的错误信息(可选)" + }, + { + "name": "download_url", + "type": "string", + "description": "任务完成后可直接下载的文件地址(若有)" + }, + { + "name": "update_time", + "type": "string", + "description": "最近一次状态更新时间,ISO8601 字符串(可选)" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + }, + { + "code": 500, + "message": "查询失败或内部错误" + } + ] + }, { "method": "stock.warehouse.getProhibitedType", "description": "查询违禁品类型列表(系统预设+仓库自定义)", @@ -10481,6 +10762,138 @@ "response": [], "errors": [] }, + { + "method": "stock.warehouse.import", + "description": "批量导入或更新仓库商品。请求体优先直接传入商品数据数组 JSON(主方式为数组);也兼容以 rows/items/list/data 包装。每项仅需包含商品相关字段;当 SKU 为空时创建新商品,SKU 非空时为更新操作;更新会写操作日志以便审计。未传 store_id 时默认使用当前上下文仓库/主体(ctx.user.store_id)。", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "items / rows / list / data", + "type": "array", + "required": true, + "source": "body", + "description": "商品数组(主方式为直接传数组 []),也兼容对象包装:{ rows: [...] } / { items: [...] } / { list: [...] } / { data: [...] }。每项可使用下列字段别名:", + "children": [ + { + "name": "SKU / sku / id / item_id / itemId", + "type": "string|number", + "description": "SKU 或商品 ID(编辑/更新使用;为空时创建)" + }, + { + "name": "商品编码 / item_code / itemCode", + "type": "string", + "description": "商品编码" + }, + { + "name": "货物编码 / goods_code / goodsCode", + "type": "string", + "description": "货物编码(支持导入)" + }, + { + "name": "SKU规格 / sku_property / skuProperty", + "type": "string", + "description": "规格信息" + }, + { + "name": "库存单位 / stock_unit / stockUnit", + "type": "string", + "description": "库存单位" + }, + { + "name": "品牌 / brand_name / brandName", + "type": "string", + "description": "品牌" + }, + { + "name": "毛重 / gross_weight / grossWeight", + "type": "number", + "description": "毛重(数值,单位与系统一致)" + }, + { + "name": "标价 / tag_price / tagPrice", + "type": "number", + "description": "标价" + }, + { + "name": "零售价 / retail_price / retailPrice", + "type": "number", + "description": "零售价" + }, + { + "name": "store_id / storeId", + "type": "number", + "required": false, + "source": "body", + "description": "可选,货主/仓库 ID;未传入时使用当前上下文(ctx.user.store_id)" + } + ] + } + ], + "response": [ + { + "name": "total_count", + "type": "number", + "description": "解析到的总条目数" + }, + { + "name": "created_count", + "type": "number", + "description": "成功创建的新商品数" + }, + { + "name": "updated_count", + "type": "number", + "description": "成功更新的商品数" + }, + { + "name": "fail_count", + "type": "number", + "description": "导入失败数" + }, + { + "name": "created_ids", + "type": "array", + "description": "创建成功的商品 ID 列表" + }, + { + "name": "updated_ids", + "type": "array", + "description": "更新成功的商品 ID 列表" + }, + { + "name": "fail_items", + "type": "array", + "description": "失败项明细数组,每项包含原始输入与错误信息" + } + ], + "errors": [ + { + "code": "400", + "description": "导入数据不能为空" + }, + { + "code": "400", + "description": "缺少仓库上下文" + }, + { + "code": "400", + "description": "导入行数据无效" + }, + { + "code": "500", + "description": "导入失败" + } + ] + }, { "method": "stock.warehouse.getBarcodes", "description": "查询商品条码列表", @@ -10732,9 +11145,110 @@ "description": "Bearer token" } ], - "params": [], - "response": [], - "errors": [] + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "要批量修改的仓库商品记录 ID 数组(stock_warehouse.id)", + "children": [ + { + "name": "id", + "type": "number", + "description": "单个记录 ID" + } + ] + }, + { + "name": "method", + "type": "string", + "required": true, + "source": "body", + "description": "要修改的字段名,可选值:brand_name、prohibited_id、gross_weight、packing_requirements、managementFlags、stock_unit" + }, + { + "name": "value", + "type": "string|number|object", + "required": true, + "source": "body", + "description": "修改值,类型依 method 而定:brand_name/packing_requirements/stock_unit 为 string(<=255 字符);prohibited_id 为 number(整数);gross_weight 为 number(正数,可含小数);managementFlags 为 object,必须包含 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt,值为 'Y' 或 'N'" + }, + { + "name": "values", + "type": "any", + "required": false, + "source": "body", + "description": "兼容字段:当前实现以 `value` 为准,不使用 `values`。若客户端历史使用 `values`,请切换为 `value`。" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功;405 表示参数/权限校验不通过;500 表示服务器错误" + }, + { + "name": "message", + "type": "string", + "description": "业务提示信息" + }, + { + "name": "data", + "type": "object", + "description": "成功时返回的结果对象", + "children": [ + { + "name": "affectedRows", + "type": "number", + "description": "被更新的记录数" + }, + { + "name": "ids", + "type": "array", + "description": "请求中传入的 ids 数组" + } + ] + } + ], + "errors": [ + { + "code": "405", + "description": "请选择要修改的商品(缺少 ids 或 ids 为空)" + }, + { + "code": "405", + "description": "不支持修改的字段: {method}" + }, + { + "code": "405", + "description": "修改值不能为空" + }, + { + "code": "405", + "description": "违禁品类型必须是数字" + }, + { + "code": "405", + "description": "毛重必须是有效的正数" + }, + { + "code": "405", + "description": "管理标识必须是对象格式 / 管理标识缺少字段 / 管理标识字段值必须是 'Y' 或 'N'" + }, + { + "code": "405", + "description": "部分商品不存在或无权修改: " + }, + { + "code": "405", + "description": "缺少仓库信息" + }, + { + "code": "500", + "description": "内部错误:批量修改失败" + } + ] }, { "method": "stock.warehouse.getStockUnits", @@ -12156,38 +12670,7 @@ } ] }, - { - "method": "storage.receiving.addItem", - "description": "storage.receiving.addItem 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - }, - { - "name": "item", - "type": "object", - "required": false, - "source": "body", - "description": "item 参数" - } - ], - "response": [], - "errors": [] - }, + { "method": "storage.receiving.removeItem", "description": "storage.receiving.removeItem 接口", @@ -12413,7 +12896,7 @@ }, { "method": "storage.receiving.addDetail", - "description": "storage.receiving.addDetail 接口", + "description": "支持新增可选入参 item;item 有值时按传入字段创建明细(服务端会覆盖 receiving_id 与 creator_id);item 无值时沿原链路创建空白明细。返回的 selectId 与 data.details 语义不变(仍返回新创建明细的 selectId 与更新后的明细列表)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -12424,13 +12907,168 @@ "description": "Bearer token" } ], - "params": [], - "response": [], - "errors": [] + "params": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + }, + { + "name": "item", + "type": "object", + "required": false, + "source": "body", + "description": "可选:按传入字段创建明细;不传则创建空白明细。item.children 需覆盖以下字段(有则写、无则补齐):actual_quantity, box_quantity, boxes_per_pallet, space_id, system_product_id, box_width, box_height, box_length, box_remainder, box_weight, weight, barcode, product_name, pallet_quantity, receiving_time, production_date, expiry_date, remark, batch_number, product_snapshot。若传入 item,服务端仍会覆盖 receiving_id 与 creator_id。", + "children": [ + { + "name": "actual_quantity", + "type": "number", + "description": "实收数量" + }, + { + "name": "box_quantity", + "type": "number", + "description": "箱数量" + }, + { + "name": "boxes_per_pallet", + "type": "number", + "description": "每托盘箱数" + }, + { + "name": "space_id", + "type": "number", + "description": "库位 ID" + }, + { + "name": "system_product_id", + "type": "number", + "description": "系统商品 ID" + }, + { + "name": "box_width", + "type": "number", + "description": "箱宽(单位同系统)" + }, + { + "name": "box_height", + "type": "number", + "description": "箱高" + }, + { + "name": "box_length", + "type": "number", + "description": "箱长" + }, + { + "name": "box_remainder", + "type": "number", + "description": "箱内剩余数量/零散数量" + }, + { + "name": "box_weight", + "type": "number", + "description": "箱重" + }, + { + "name": "weight", + "type": "number", + "description": "商品重量" + }, + { + "name": "barcode", + "type": "string", + "description": "商品条码" + }, + { + "name": "product_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "pallet_quantity", + "type": "number", + "description": "托盘数量" + }, + { + "name": "receiving_time", + "type": "string", + "description": "收货时间(ISO 字符串)" + }, + { + "name": "production_date", + "type": "string", + "description": "生产日期(ISO 或 YYYY-MM-DD)" + }, + { + "name": "expiry_date", + "type": "string", + "description": "有效期/失效日期(ISO 或 YYYY-MM-DD)" + }, + { + "name": "remark", + "type": "string", + "description": "备注" + }, + { + "name": "batch_number", + "type": "string", + "description": "批次号" + }, + { + "name": "product_snapshot", + "type": "object", + "description": "商品快照,具体结构以实现为准" + } + ] + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码,200 表示添加成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "结果描述,成功时为 '添加成功'" + }, + { + "name": "data.details", + "type": "array", + "required": true, + "description": "收货单明细数组(每项为明细对象)" + }, + { + "name": "data.selectId", + "type": "number", + "required": true, + "description": "新创建的明细ID,用于前端选中" + } + ], + "errors": [ + { + "code": "400", + "description": "收货单状态不允许添加明细" + }, + { + "code": "404", + "description": "收货单不存在" + }, + { + "code": "500", + "description": "服务器错误或添加失败(数据库写入异常等)" + } + ] }, { "method": "storage.receiving.deleteDetail", - "description": "storage.receiving.deleteDetail 接口", + "description": "删除收货单明细并回算统计。仅允许明细创建者在收货中状态删除未入库的明细;服务端从登录用户上下文获取 creator_id(ctx.user.employees_id)与 warehouse_id(ctx.user.store_id)。若关联收货单状态为 completed(已完成)或 cancelled(已取消),接口会返回删除失败(400),不允许删除明细。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -12441,9 +13079,56 @@ "description": "Bearer token" } ], - "params": [], - "response": [], - "errors": [] + "params": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单明细 ID(必填)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功,400/404/500 表示失败" + }, + { + "name": "message", + "type": "string", + "description": "简短的错误或成功信息" + }, + { + "name": "data", + "type": "object", + "description": "成功时返回的结果对象" + }, + { + "name": "data.details", + "type": "array", + "description": "删除后收货单剩余的明细数组。每项字段与 storage.receiving.getReceivingDetail 返回的明细项一致;product_snapshot 为解析后的对象或 null" + }, + { + "name": "data.selectId", + "type": "number|null", + "description": "删除后建议前端选中的明细 ID;无剩余明细时为 null" + } + ], + "errors": [ + { + "code": "404", + "description": "明细不存在(或非创建者/仓库无权访问)" + }, + { + "code": "400", + "description": "收货单已完成或已取消,禁止删除明细;或该明细已入库或已被占用,删除失败" + }, + { + "code": "500", + "description": "服务器内部错误或删除异常(含数据库写入/事务异常)" + } + ] }, { "method": "storage.receiving.detailChange", @@ -15943,13 +16628,22 @@ { "name": "id", "type": "number", - "required": false, + "required": true, "source": "body", "description": "id 参数" } ], "response": [], - "errors": [] + "errors": [ + { + "code": "0", + "description": "仓位不存在" + }, + { + "code": "0", + "description": "仓位不属于当前仓库" + } + ] }, { "method": "warehouse.updateSpaceInfo", diff --git a/test/app/service/systemMethods/stock.warehouse.export.test.js b/test/app/service/systemMethods/stock.warehouse.export.test.js new file mode 100644 index 0000000..22cc816 --- /dev/null +++ b/test/app/service/systemMethods/stock.warehouse.export.test.js @@ -0,0 +1,118 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const WarehouseMethodService = require('../../../../app/service/systemMethods/stock/warehouse'); + +function createHarness() { + const captured = { + where: null, + sortParams: null, + callCount: 0, + cacheWrites: [], + }; + + const cacheStore = new Map(); + + const ctx = { + app: { + config: { + jwt: {}, + }, + Sequelize: {}, + async setCacheAsync(key, payload, ttl) { + captured.cacheWrites.push({ key, payload, ttl }); + cacheStore.set(key, payload); + }, + async getCacheAsync(key) { + return cacheStore.get(key) || null; + }, + }, + logger: { + warn() {}, + }, + service: { + systems: { + stockStore: { + async exportWarehouseStock(where, sortParams) { + captured.callCount += 1; + captured.where = where; + captured.sortParams = sortParams; + return { + url: 'https://cdn.example.com/export.xlsx', + fileKey: 'exports/stock/warehouse/100001/export.xlsx', + }; + }, + }, + }, + }, + }; + + const service = new WarehouseMethodService(ctx); + service.prepareWhereContext = function prepareWhereContext() { + return { + where: { + item_code: { + operator: 'like', + value: 'SKU', + }, + }, + whereValue: { + sort_field: 'item_code', + sort_order: 'desc', + }, + }; + }; + + return { + service, + captured, + }; +} + +describe('test/app/service/systemMethods/stock.warehouse.export.test.js', () => { + it('should return submitted task and write task cache when export called', async () => { + const { service, captured } = createHarness(); + + const result = await service.export({ + sort: { + sortField: 'quantity', + sortOrder: 'asc', + }, + where: { + ignored: true, + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '导出任务已提交'); + assert.equal(typeof result.task_id, 'string'); + assert.ok(result.task_id.length > 0); + assert.equal(result.status, 'submitted'); + const submittedCacheWrite = captured.cacheWrites.find(item => item?.payload?.status === 'submitted'); + assert.ok(submittedCacheWrite); + assert.equal(submittedCacheWrite.ttl, 1800); + }); + + it('should return cached status and download_url in exportTaskProgress', async () => { + const { service } = createHarness(); + const taskId = 'task-001'; + await service.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result: { + cndUrl: 'https://cdn.example.com/export-from-cnd.xlsx', + }, + error: '', + }); + + const result = await service.exportTaskProgress({ task_id: taskId }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '导出任务完成'); + assert.equal(result.task_id, taskId); + assert.equal(result.status, 'success'); + assert.equal(result.download_url, 'https://cdn.example.com/export-from-cnd.xlsx'); + }); +}); diff --git a/test/app/service/systemMethods/stock.warehouse.import.test.js b/test/app/service/systemMethods/stock.warehouse.import.test.js new file mode 100644 index 0000000..ca1da91 --- /dev/null +++ b/test/app/service/systemMethods/stock.warehouse.import.test.js @@ -0,0 +1,140 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const WarehouseMethodService = require('../../../../app/service/systemMethods/stock/warehouse'); + +function createHarness() { + const calls = { + createArgs: [], + saveArgs: [], + }; + + const ctx = { + user: { + store_id: 100000, + }, + app: { + config: { + jwt: {}, + }, + }, + service: { + systems: { + stockStore: { + async createWarehouseStock(data) { + calls.createArgs.push(data); + return { + ...data, + id: `create-${calls.createArgs.length}`, + }; + }, + async saveWarehouseStock(data) { + calls.saveArgs.push(data); + return { + id: data.id, + ...data, + }; + }, + }, + }, + }, + }; + + return { + service: new WarehouseMethodService(ctx), + calls, + ctx, + }; +} + +describe('test/app/service/systemMethods/stock.warehouse.import.test.js', () => { + it('should import direct array rows and route create/update by SKU with normalized fields', async () => { + const { service, calls, ctx } = createHarness(); + + const result = await service.import([ + { + itemCode: 'SKU-CREATE', + goodsCode: 'G-CREATE', + skuProperty: '规格A', + stockUnit: '件', + brandName: '品牌A', + grossWeight: 1.2, + tagPrice: 11, + retailPrice: 22, + }, + { + SKU: '99', + item_code: 'SKU-UPDATE', + goods_code: 'G-UPDATE', + sku_property: '规格B', + stock_unit: '箱', + brand_name: '品牌B', + gross_weight: 2.3, + tag_price: 33, + retail_price: 44, + }, + ]); + + assert.equal(result.flag, 'success'); + assert.equal(result.total_count, 2); + assert.equal(result.created_count, 1); + assert.equal(result.updated_count, 1); + assert.equal(result.fail_count, 0); + assert.deepEqual(result.created_ids, [ 'create-1' ]); + assert.deepEqual(result.updated_ids, [ '99' ]); + assert.deepEqual(result.fail_items, []); + + assert.equal(calls.createArgs.length, 1); + assert.equal(calls.saveArgs.length, 1); + + assert.equal(calls.createArgs[0].store_id, ctx.user.store_id); + assert.equal(calls.createArgs[0].item_code, 'SKU-CREATE'); + assert.equal(calls.createArgs[0].goods_code, 'G-CREATE'); + assert.equal(calls.createArgs[0].item_name, 'SKU-CREATE'); + assert.equal(calls.createArgs[0].sku_property, '规格A'); + assert.equal(calls.createArgs[0].stock_unit, '件'); + assert.equal(calls.createArgs[0].brand_name, '品牌A'); + assert.equal(calls.createArgs[0].gross_weight, 1.2); + assert.equal(calls.createArgs[0].tag_price, 11); + assert.equal(calls.createArgs[0].retail_price, 22); + + assert.equal(calls.saveArgs[0].id, '99'); + assert.equal(calls.saveArgs[0].store_id, ctx.user.store_id); + assert.equal(calls.saveArgs[0].item_code, 'SKU-UPDATE'); + assert.equal(calls.saveArgs[0].goods_code, 'G-UPDATE'); + assert.equal(calls.saveArgs[0].item_name, 'SKU-UPDATE'); + assert.equal(calls.saveArgs[0].sku_property, '规格B'); + assert.equal(calls.saveArgs[0].stock_unit, '箱'); + assert.equal(calls.saveArgs[0].brand_name, '品牌B'); + assert.equal(calls.saveArgs[0].gross_weight, 2.3); + assert.equal(calls.saveArgs[0].tag_price, 33); + assert.equal(calls.saveArgs[0].retail_price, 44); + }); + + it('should update by stock_id and map cargo_code to goods_code', async () => { + const { service, calls, ctx } = createHarness(); + + const result = await service.import([ + { + stock_id: '321', + cargo_code: 'CARGO-321', + item_code: 'ITEM-321', + }, + ]); + + assert.equal(result.flag, 'success'); + assert.equal(result.total_count, 1); + assert.equal(result.updated_count, 1); + assert.equal(result.created_count, 0); + assert.equal(result.fail_count, 0); + assert.deepEqual(result.updated_ids, [ '321' ]); + assert.deepEqual(result.created_ids, []); + + assert.equal(calls.saveArgs.length, 1); + assert.equal(calls.createArgs.length, 0); + assert.equal(calls.saveArgs[0].store_id, ctx.user.store_id); + assert.equal(calls.saveArgs[0].id, '321'); + assert.equal(calls.saveArgs[0].goods_code, 'CARGO-321'); + assert.equal(calls.saveArgs[0].item_code, 'ITEM-321'); + }); +}); diff --git a/test/app/service/systems/location_zone.getSpaceInfo.test.js b/test/app/service/systems/location_zone.getSpaceInfo.test.js new file mode 100644 index 0000000..87b63f8 --- /dev/null +++ b/test/app/service/systems/location_zone.getSpaceInfo.test.js @@ -0,0 +1,96 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const LocationZoneService = require('../../../../app/service/systems/location_zone'); + +function createHarness({ storeId = 1, spaces = [] } = {}) { + const rows = spaces.map(item => ({ + ...item, + deleted_at: item.deleted_at || null, + })); + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: storeId, + }, + logger: { + error() {}, + }, + model: { + LocationSpace: { + async findOne({ where = {}, attributes } = {}) { + const matched = rows.find(row => { + if (Number(row.id) !== Number(where.id)) { + return false; + } + + if (Object.prototype.hasOwnProperty.call(where, 'deleted_at') && where.deleted_at === null && row.deleted_at !== null) { + return false; + } + + if (Object.prototype.hasOwnProperty.call(where, 'warehouse_id') && Number(row.warehouse_id) !== Number(where.warehouse_id)) { + return false; + } + + return true; + }); + + if (!matched) { + return null; + } + + if (!Array.isArray(attributes) || attributes.length === 0) { + return { ...matched }; + } + + return attributes.reduce((acc, key) => { + acc[key] = matched[key]; + return acc; + }, {}); + }, + }, + }, + }; + + return { + service: new LocationZoneService(ctx), + }; +} + +describe('test/app/service/systems/location_zone.getSpaceInfo.test.js', () => { + it('存在但不属于当前仓库时应返回仓位不属于当前仓库', async () => { + const { service } = createHarness({ + storeId: 1, + spaces: [ + { + id: 1001, + warehouse_id: 2, + location_type_id: 1, + space_code: 'A01-01-01', + custom_name: null, + custom_barcode: null, + space_status: 1, + pick_sequence: 1, + }, + ], + }); + + await assert.rejects(async () => { + await service.getSpaceInfo(1001); + }, /仓位不属于当前仓库/); + }); + + it('全局不存在时应返回仓位不存在', async () => { + const { service } = createHarness({ + storeId: 1, + spaces: [], + }); + + await assert.rejects(async () => { + await service.getSpaceInfo(99999); + }, /仓位不存在/); + }); +}); diff --git a/test/app/service/systems/stock_store.exportWarehouseStock.test.js b/test/app/service/systems/stock_store.exportWarehouseStock.test.js new file mode 100644 index 0000000..3b6ebd2 --- /dev/null +++ b/test/app/service/systems/stock_store.exportWarehouseStock.test.js @@ -0,0 +1,122 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StockStoreService = require('../../../../app/service/systems/stock_store'); + +function createHarness() { + const captured = { + getWarehouseStockCalls: [], + uploadOptions: null, + storeWarehouseFindAllOptions: null, + }; + + const ctx = { + app: { + config: {}, + Sequelize: { Op: { in: 'in' } }, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + excel: { + async generateAndUpload(options) { + captured.uploadOptions = options; + return { + url: 'https://cdn.example.com/export.xlsx', + fileKey: 'exports/stock/warehouse/100000/export.xlsx', + }; + }, + }, + }, + }, + }; + + // mock model.StoreWarehouse + ctx.model = { + StoreWarehouse: { + async findAll(options) { + captured.storeWarehouseFindAllOptions = options; + return [{ store_id: 100000, store_remask: '测试货主' }]; + }, + }, + }; + + ctx.logger = ctx.app.logger || ctx.logger; + + const service = new StockStoreService(ctx); + + service.getWarehouseStock = async function getWarehouseStock(where, pageParams, sortParams) { + captured.getWarehouseStockCalls.push({ where, pageParams, sortParams }); + return { + code: 200, + data: { + list: [ + { + id: 1, + item_code: 'SKU-001', + goods_code: 'GC-001', + item_name: '测试商品', + brand_name: '测试品牌', + sku_property: '10kg/箱', + stock_unit: '箱', + tag_price: '99.90', + retail_price: '89.90', + gross_weight: '12.5', + store_id: 100000, + barcodes: [ '690000000001' ], + quantity: 10, + locked_quantity: 2, + available_quantity: 8, + lock_rate_display: '20%', + create_at_display: '2026-05-17 10:00:00', + update_at_display: '2026-05-17 11:00:00', + }, + ], + pagination: { + hasNext: false, + }, + }, + }; + }; + + return { + service, + captured, + }; +} + +describe('test/app/service/systems/stock_store.exportWarehouseStock.test.js', () => { + it('should include goods_code, brand_name, sku_property and gross_weight in export rows and columns', async () => { + const { service, captured } = createHarness(); + + const result = await service.exportWarehouseStock({ item_code: 'SKU-001' }, { sortField: 'item_code', sortOrder: 'desc' }); + + assert.equal(result.url, 'https://cdn.example.com/export.xlsx'); + assert.equal(captured.getWarehouseStockCalls.length, 1); + assert.deepEqual(captured.getWarehouseStockCalls[0].where, { item_code: 'SKU-001' }); + assert.deepEqual(captured.getWarehouseStockCalls[0].sortParams, { sortField: 'item_code', sortOrder: 'desc' }); + assert.equal(captured.uploadOptions.sheets[0].rows[0].goods_code, 'GC-001'); + assert.equal(captured.uploadOptions.sheets[0].rows[0].brand_name, '测试品牌'); + assert.equal(captured.uploadOptions.sheets[0].rows[0].sku_property, '10kg/箱'); + assert.equal(captured.uploadOptions.sheets[0].rows[0].stock_unit, '箱'); + assert.equal(captured.uploadOptions.sheets[0].rows[0].tag_price, '99.90'); + assert.equal(captured.uploadOptions.sheets[0].rows[0].retail_price, '89.90'); + assert.equal(captured.uploadOptions.sheets[0].rows[0].gross_weight, '12.5'); + assert.equal(captured.uploadOptions.sheets[0].rows[0].store_remask, '测试货主'); + assert.deepEqual(captured.storeWarehouseFindAllOptions.where.store_id, { in: [ 100000 ] }); + assert.equal(captured.storeWarehouseFindAllOptions.where.warehouse_id, 100000); + assert.deepEqual( + captured.uploadOptions.sheets[0].columns.map(column => column.key), + [ 'id', 'item_code', 'goods_code', 'item_name', 'brand_name', 'sku_property', 'stock_unit', 'tag_price', 'retail_price', 'gross_weight', 'store_remask', 'barcodes', 'quantity', 'locked_quantity', 'available_quantity', 'lock_rate_display', 'create_at_display', 'update_at_display' ] + ); + assert.equal(captured.uploadOptions.sheets[0].columns[0].header, 'SKU'); + assert.equal(captured.uploadOptions.sheets[0].columns[2].header, '货物编码'); + }); +}); \ No newline at end of file diff --git a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js index e469840..991f810 100644 --- a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js +++ b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js @@ -9,6 +9,9 @@ function createTestContext(options = {}) { findArgs: null, findOneArgs: null, updateArgs: null, + createArgs: null, + createOptions: null, + bulkCreateArgs: null, barcodeCalls: [], fileRefArgs: null, transactionCount: 0, @@ -72,12 +75,27 @@ function createTestContext(options = {}) { }, async findOne(args) { calls.findOneArgs = args; - return options.stockInfo || null; + const where = args && args.where ? args.where : {}; + if (options.stockInfo && Object.prototype.hasOwnProperty.call(where, 'id') && Number(where.id) === Number(options.stockInfo.id)) { + return options.stockInfo; + } + if (options.uniqueConflict) { + return options.uniqueConflict; + } + return null; }, async update(args) { calls.updateArgs = args; return [ 1 ]; }, + async create(args, optionsArg) { + calls.createArgs = args; + calls.createOptions = optionsArg; + return { + ...args, + id: options.createdId || 123, + }; + }, }, StockBarcode: { async findAll(args) { @@ -94,6 +112,10 @@ function createTestContext(options = {}) { } return [{ stock_id: 1, barcode: 'BC-1' }]; }, + async bulkCreate(args) { + calls.bulkCreateArgs = args; + return args; + }, }, FileReference: { async findAll(args) { @@ -453,6 +475,7 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js const { service, calls } = createServiceHarness({ stockInfo: { id: 1, + goods_code: 'G-1', item_code: 'SKU-1', shelf_life_days: 10, inbound_min_days: 3, @@ -467,6 +490,7 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js }); assert.equal(result.id, 1); + assert.equal(result.goods_code, 'G-1'); assert.equal(result.shelf_life_days, 10); assert.equal(result.inbound_min_days, 3); assert.equal(result.outbound_min_days, 5); @@ -541,6 +565,7 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js assert.equal(calls.updateArgs.inbound_min_days, 3); assert.equal(calls.updateArgs.outbound_min_days, 5); assert.equal(calls.updateArgs.remaining_threshold_days, 7); + assert.equal(calls.updateArgs.goods_code, undefined); assert.equal(calls.operationLogCalls.length, 1); }); @@ -599,4 +624,104 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js assert.equal(calls.updateArgs, null); assert.equal(calls.operationLogCalls.length, 0); }); + + it('should write goods_code on update and persist create without barcode', async () => { + const { service, calls } = createServiceHarness({ + stockInfo: { + id: 12, + deleted_at: null, + store_id: 100000, + warehouse_id: 100000, + }, + createdId: 88, + }); + + service.getInfo = async ({ id }) => ({ + id, + goods_code: 'G-12', + }); + + const updateResult = await service.saveWarehouseStock({ + id: 12, + item_code: 'SKU-12', + goods_code: 'G-12', + item_name: '商品十二号', + sku_property: '默认规格', + stock_unit: '件', + packing_requirements: '', + length: 10, + width: 11, + height: 12, + volume: 13, + gross_weight: 14, + net_weight: 15, + tag_price: 16, + retail_price: 17, + is_sn_mgmt: 'N', + is_shelf_life_mgmt: 'N', + is_batch_mgmt: 'N', + prohibited_id: null, + brand_name: '品牌十二', + managementFlags: '', + enable_box_spec: false, + box_unit: '', + quantity_per_box: 0, + box_gross_weight: 0, + box_net_weight: 0, + box_length: 0, + box_width: 0, + box_height: 0, + box_volume: 0, + box_remark: '', + }); + + assert.equal(updateResult.id, 12); + assert.equal(calls.updateArgs.goods_code, 'G-12'); + + service.checkItemCodeUnique = async () => ({ + isUnique: true, + }); + service.getInfo = async ({ id }) => ({ + id, + goods_code: 'G-99', + }); + + const createResult = await service.createWarehouseStock({ + item_code: 'SKU-99', + goods_code: 'G-99', + item_name: '商品九十九号', + sku_property: '默认规格', + stock_unit: '件', + packing_requirements: '', + length: 10, + width: 11, + height: 12, + volume: 13, + gross_weight: 14, + net_weight: 15, + tag_price: 16, + retail_price: 17, + is_sn_mgmt: 'N', + is_shelf_life_mgmt: 'N', + is_batch_mgmt: 'N', + prohibited_id: null, + brand_name: '品牌九十九', + managementFlags: '', + enable_box_spec: false, + box_unit: '', + quantity_per_box: 0, + box_gross_weight: 0, + box_net_weight: 0, + box_length: 0, + box_width: 0, + box_height: 0, + box_volume: 0, + box_remark: '', + barcode: '', + }); + + assert.equal(createResult.id, 88); + assert.equal(calls.createArgs.goods_code, 'G-99'); + assert.equal(calls.bulkCreateArgs, null); + }); });