liufumingren 8cf2c5befa 1
2026-05-20 16:31:29 +08:00

1018 lines
29 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const MainService = require('../../main');
const STOCK_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,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);
}
/**
* 归一化回收站筛选条件,兼容历史 is_deleted 字段。
* @param {Object} where 原始 where 条件
* @return {Object} 归一化后的 where 条件
*/
normalizeWarehouseRecycleWhere(where = {}) {
if (!this.isPlainObject(where)) {
return {};
}
const normalizedWhere = { ...where };
const recycleCondition = normalizedWhere.is_deleted;
if (!this.isPlainObject(recycleCondition)) {
return normalizedWhere;
}
const recycleValue = recycleCondition.value;
const isDeleted = recycleValue === true
|| recycleValue === 1
|| String(recycleValue || '').trim().toLowerCase() === 'true'
|| String(recycleValue || '').trim() === '1';
normalizedWhere.deleted_at = {
operator: isDeleted ? 'isnotnull' : 'isnull',
value: isDeleted ? 1 : 0,
};
delete normalizedWhere.is_deleted;
return normalizedWhere;
}
/**
* 仓库商品列表查询。
* @param {Object} data 请求体
* @param {Object} [data.pagination] 分页参数
* @param {Object} [data.where] 筛选条件
* @return {Promise<Object>} 统一成功包装响应
*/
async list(data = {}) {
const { service } = this;
const { pagination } = data;
if (this.isPlainObject(data)) {
const rawWhere = this.isPlainObject(data.where) ? data.where : {};
data.where = this.normalizeWarehouseRecycleWhere(rawWhere);
}
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
barcode: {
bucket: 'barcode',
},
prohibited_type: {
bucket: 'prohibited',
field: 'id',
},
},
});
const result = await service.systems.stockStore.getWarehouseStock(where, pagination);
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<Object>} 统一成功包装响应,data 为导出任务信息
*/
async export(data = {}) {
const { service } = this;
if (this.isPlainObject(data)) {
const rawWhere = this.isPlainObject(data.where) ? data.where : {};
data.where = this.normalizeWarehouseRecycleWhere(rawWhere);
}
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<Object>} 统一成功包装响应
*/
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<void>} 无返回值
*/
async setExportTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const progressPayload = {
task_id: String(taskId || '').trim(),
status: String(safePayload.status || 'submitted').trim() || 'submitted',
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
message: String(safePayload.message || ''),
result: safePayload.result ?? null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, 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<Object|null>} 任务缓存
*/
async getExportTaskProgress(taskId = '') {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[stock.warehouse.export] 读取导出任务缓存失败: ${errorMessage}`);
return null;
}
}
/**
* 查询违禁品类型列表(系统预设 + 当前仓库)。
* @return {Promise<Object>} data 为违禁品类型数组
*/
async getProhibitedType() {
const { service } = this;
const result = await service.systems.stockStore.getProhibitedType();
return this.success('ok', { data: result, code: 200 });
}
/**
* 按商品条件获取仓库商品详情。
* @param {Object} data 请求体(常见包含 id/item_code)
* @return {Promise<Object>} data 为单个商品详情对象
*/
async getInfo(data) {
const { service } = this;
const result = await service.systems.stockStore.getInfo(data);
return this.success('ok', { data: result, code: 200 });
}
/**
* 更新仓库商品资料。
* @param {Object} data 请求体(含商品主键与可编辑字段)
* @return {Promise<Object>} data 为更新结果
*/
async saveWarehouseStock(data) {
const { service } = this;
const {
id,
item_code,
item_name,
goods_code,
sku_property,
stock_unit,
packing_requirements,
length,
width,
height,
volume,
volume_cm3,
volumeCm3,
gross_weight,
net_weight,
tag_price,
retail_price,
is_sn_mgmt,
is_shelf_life_mgmt,
is_batch_mgmt,
prohibited_id,
brand_name,
managementFlags,
enable_box_spec,
box_unit,
quantity_per_box,
box_gross_weight,
box_net_weight,
box_length,
box_width,
box_height,
box_volume,
box_volume_m3,
boxVolumeM3,
box_remark,
shelf_life_days,
inbound_min_days,
outbound_min_days,
remaining_threshold_days,
} = data || {};
try {
const result = await service.systems.stockStore.saveWarehouseStock({
id,
item_code,
item_name,
goods_code,
sku_property,
stock_unit,
packing_requirements,
length,
width,
height,
volume,
volume_cm3,
volumeCm3,
gross_weight,
net_weight,
tag_price,
retail_price,
is_sn_mgmt,
is_shelf_life_mgmt,
is_batch_mgmt,
prohibited_id,
brand_name,
managementFlags,
enable_box_spec,
box_unit,
quantity_per_box,
box_gross_weight,
box_net_weight,
box_length,
box_width,
box_height,
box_volume,
box_volume_m3,
boxVolumeM3,
box_remark,
shelf_life_days,
inbound_min_days,
outbound_min_days,
remaining_threshold_days,
});
return this.success('ok', { data: result, code: 200 });
} catch (error) {
return this.fail(error.message);
}
}
/**
* 新建仓库商品资料。
* @param {Object} data 请求体(必填字段见 stockStore 校验)
* @return {Promise<Object>} data 为新建结果
*/
async createWarehouseStock(data) {
const { service } = this;
const result = await service.systems.stockStore.createWarehouseStock(data);
return this.success('ok', { data: result, code: 200 });
}
/**
* 导入仓库商品资料。
*
* 支持直接传数组,也支持从 rows、items、list、data 中提取数组。
* SKU 为空时创建,SKU 不为空时更新,并返回批量处理结果汇总。
*
* @param {Object|Array} data 导入请求体或商品数组
* @return {Promise<Object>} 导入结果汇总
*/
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<Object>} 商品数组
*/
_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 请求体(支持分页与关键字)
* @return {Promise<Object>} data 为条码分页结果
*/
async getBarcodes(data) {
const { service } = this;
const result = await service.systems.stockStore.getBarcodes(data);
return this.success('ok', { data: result, code: 200 });
}
/**
* 保存商品条码信息。
* @param {Object} data 请求体(包含 stock_id 与条码字段)
* @return {Promise<Object>} data 为保存结果
*/
async saveWarehouseStockBarcode(data) {
const { service } = this;
const result = await service.systems.stockStore.saveWarehouseStockBarcode(data);
return this.success('ok', { data: result, code: 200 });
}
/**
* 查询仓库与货主商品关联列表。
* @param {Object} data 请求体(支持筛选/分页)
* @return {Promise<Object>} data 为关联分页结果
*/
async getStoreStocks(data) {
const { service } = this;
const result = await service.systems.stockStore.getStoreStocks(data);
return this.success('ok', { data: result, code: 200 });
}
/**
* 绑定货主商品。
* @param {Object} data 请求体(关联关系参数)
* @return {Promise<Object>} 成功或失败均返回 success 包装,message 给出结果
*/
async bindItem(data) {
const { service } = this;
const { id, warehouse_stock } = data || {};
try {
const result = await service.systems.stockStore.bindItem({
id,
warehouse_stock,
});
return this.success('绑定成功', { data: result, code: 200 });
} catch (e) {
return this.success(e.message, { code: 200 });
}
}
/**
* 解绑货主商品。
* @param {Object} data 请求体(关联关系参数)
* @return {Promise<Object>} 成功或失败均返回 success 包装,message 给出结果
*/
async unbindItem(data) {
const { service } = this;
const { id } = data || {};
try {
const result = await service.systems.stockStore.unbindItem({ id });
return this.success('解绑成功', { data: result, code: 200 });
} catch (e) {
return this.success(e.message, { code: 200 });
}
}
/**
* 校验商品编码唯一性。
* @param {Object} data 请求体
* @param {number} [data.item_id] 商品ID(编辑场景,排除自身)
* @param {number} [data.id] 兼容旧字段的商品ID
* @param {string} data.item_code 商品编码
* @param {number} data.owner_id 货主ID
* @param {number} [data.store_id] 兼容旧字段的货主ID
* @param {number} data.warehouse_id 仓库ID
* @return {Promise<Object>} data.unique 为是否唯一,重复时返回提示信息
*/
async checkItemCodeUnique(data) {
const { ctx, service } = this;
const {
item_id,
id,
item_code,
owner_id,
store_id,
warehouse_id,
} = data || {};
const targetItemId = item_id || id || null;
const targetOwnerId = owner_id || store_id;
const targetWarehouseId = warehouse_id || ctx.user.store_id;
try {
if (!item_code || !targetOwnerId || !targetWarehouseId) {
return this.fail('参数错误');
}
const result = await service.systems.stockStore.checkItemCodeUnique(
targetItemId,
item_code,
targetOwnerId,
targetWarehouseId
);
return this.success('获取成功', { data: result, code: 200 });
} catch (error) {
return this.fail(error.message);
}
}
/**
* 查询库存操作日志。
* @param {Object} data 请求体(会自动注入当前 warehouseId)
* @return {Promise<Object>} data 为日志分页结果
*/
async queryStockLogs(data) {
const { ctx } = this;
try {
const { service } = this;
data.warehouseId = ctx.user.store_id;
const result = await service.systems.operationLog.queryStockLogs(data);
return this.success('ok', { data: result, code: 200 });
} catch (e) {
return this.success(e.message, { code: 200 });
}
}
/**
* 批量删除仓库商品资料(软删除)。
* @param {Object} data 请求体(含 ids)
* @return {Promise<Object>} data 为删除结果,message 为业务提示
*/
async handleBatchDelete(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.handleBatchDelete(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
return this.success(e.message, { code: 200 });
}
}
/**
* 删除库存单位。
* @param {Object} data 请求体(含单位ID)
* @return {Promise<Object>} data 为删除结果,message 为业务提示
*/
async deleteUnit(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.deleteUnit(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
return this.success(e.message, { code: 200 });
}
}
/**
* 删除违禁品类型。
* @param {Object} data 请求体(含类型ID)
* @return {Promise<Object>} data 为删除结果,message 为业务提示
*/
async deleteProhibited(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.deleteProhibited(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
return this.success(e.message, { code: 200 });
}
}
/**
* 批量修改商品资料字段。
* @param {Object} data 请求体(含 ids/method/value)
* @return {Promise<Object>} data 为修改结果,message 为业务提示
*/
async handleBatchChange(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.handleBatchChange(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
return this.success(e.message, { code: 405 });
}
}
/**
* 查询可用库存单位(系统预设 + 仓库自定义)。
* @return {Promise<Object>} data 为单位数组
*/
async getStockUnits() {
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
try {
const where = {
[ctx.app.Sequelize.Op.or]: [
{ warehouse_id: null },
{ warehouse_id },
],
};
const units = await ctx.model.StockUnit.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ],
[ 'created_at', 'DESC' ],
],
});
return this.success('ok', { data: units, code: 200 });
} catch (error) {
return this.fail(error.message);
}
}
/**
* 查询当前仓库自定义单位列表。
* @return {Promise<Object>} data 为单位数组
*/
async getUnitList() {
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
try {
const where = {
warehouse_id,
};
const units = await ctx.model.StockUnit.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ],
[ 'created_at', 'DESC' ],
],
});
return this.success('ok', { data: units, code: 200 });
} catch (error) {
return this.fail(error.message);
}
}
/**
* 新增违禁品类型。
* @param {Object} data 请求体
* @param {string} data.name 违禁品类型名称
* @return {Promise<Object|void>} 成功返回 success;参数校验失败时直接写入 ctx.body
*/
async createProhibited(data) {
const { ctx } = this;
const warehouse_id = ctx.user.store_id || null;
const { name } = data;
if (!name || name.trim() === '') {
ctx.body = {
code: 400,
message: '违禁品类型名称不能为空',
};
return;
}
const trimmedName = name.trim();
try {
const systemUnit = await ctx.model.ProhibitedType.findOne({
where: {
type_name: trimmedName,
warehouse_id: null,
},
});
if (systemUnit) {
ctx.body = {
code: 400,
message: '该违禁品类型是系统预设,不允许添加',
};
return;
}
const existUnit = await ctx.model.ProhibitedType.findOne({
where: {
type_name: trimmedName,
warehouse_id,
},
});
if (existUnit) {
ctx.body = {
code: 400,
message: '该违禁品类型名称已存在',
};
return;
}
await ctx.model.ProhibitedType.create({
type_name: trimmedName,
warehouse_id,
});
const where = {};
if (warehouse_id) {
where[ctx.app.Sequelize.Op.or] = [
{ warehouse_id: null },
{ warehouse_id },
];
} else {
where.warehouse_id = null;
}
await ctx.model.ProhibitedType.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ],
[ 'created_at', 'DESC' ],
],
});
return this.success('添加成功', { code: 200 });
} catch (error) {
return this.success('创建违禁品类型失败', { code: 405 });
}
}
/**
* 新增库存单位。
* @return {Promise<Object|void>} 成功返回 success;参数校验失败时直接写入 ctx.body
*/
async createUnit() {
const { ctx } = this;
const warehouse_id = ctx.user.store_id || null;
const { name } = ctx.request.body;
if (!name || name.trim() === '') {
ctx.body = {
code: 400,
message: '单位名称不能为空',
};
return;
}
const trimmedName = name.trim();
try {
const systemUnit = await ctx.model.StockUnit.findOne({
where: {
name: trimmedName,
warehouse_id: null,
},
});
if (systemUnit) {
ctx.body = {
code: 400,
message: '该单位是系统预设单位,不允许添加',
};
return;
}
const existUnit = await ctx.model.StockUnit.findOne({
where: {
name: trimmedName,
warehouse_id,
},
});
if (existUnit) {
ctx.body = {
code: 400,
message: '该单位名称已存在',
};
return;
}
await ctx.model.StockUnit.create({
name: trimmedName,
warehouse_id,
});
const where = {};
if (warehouse_id) {
where[ctx.app.Sequelize.Op.or] = [
{ warehouse_id: null },
{ warehouse_id },
];
} else {
where.warehouse_id = null;
}
await ctx.model.StockUnit.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ],
[ 'created_at', 'DESC' ],
],
});
return this.success('添加成功', { code: 200 });
} catch (error) {
return this.success('创建库存单位失败', { code: 200 });
}
}
/**
* 快捷搜索仓库商品。
* @param {Object} data 请求体(含 keyword)
* @return {Promise<Object>} data 为搜索结果数组
*/
async search(data) {
const { service } = this;
const result = await service.systems.stockStore.search(data);
return this.success('ok', result);
}
/**
* 查询商品库存明细(按库位/批次维度展示库存分布)。
* @param {Object} data 请求体
* @param {number} data.stock_id 商品库存ID(stock_warehouse.id)
* @param {Object} [data.pagination] 分页参数
* @return {Promise<Object>} data 为库存明细分页结果
*/
async getStockDetail(data) {
const { service } = this;
const result = await service.systems.stockStore.getStockDetail(data);
return this.success('ok', result);
}
}
module.exports = WarehouseService;