- space.js 抽取 _searchByKeyword, searchSpace 与 searchSpaces 共用同一查询口径 - searchSpaces 按 keywords 并行查询并保持传入顺序, 无记录项返回空数组 - index.searchSpaces 加入免权限/免鉴权白名单
91 lines
2.5 KiB
JavaScript
91 lines
2.5 KiB
JavaScript
'use strict';
|
||
const Service = require('egg').Service;
|
||
|
||
class spaceService extends Service {
|
||
/**
|
||
* 按关键字查询库位(单个关键字)。
|
||
*
|
||
* @param {string} [keyword] 搜索关键字,为空时返回当前仓库下前 50 条。
|
||
* @return {Promise<Array>} 库位列表(最多 50 条)。
|
||
*/
|
||
async _searchByKeyword(keyword) {
|
||
const { ctx, app } = this;
|
||
const warehouseId = ctx.user.store_id;
|
||
|
||
// 构建基础查询条件:warehouse_id 为当前仓库或 null
|
||
const baseWhere = {
|
||
[app.Sequelize.Op.or]: [
|
||
{ warehouse_id: warehouseId },
|
||
{ warehouse_id: null },
|
||
],
|
||
};
|
||
|
||
let whereCondition = baseWhere;
|
||
|
||
// 如果有关键词,添加模糊查询
|
||
if (keyword && keyword.trim()) {
|
||
const searchKeyword = `%${keyword.trim()}%`;
|
||
whereCondition = {
|
||
[app.Sequelize.Op.and]: [
|
||
baseWhere, // 仓库条件
|
||
{
|
||
[app.Sequelize.Op.or]: [
|
||
{
|
||
space_code: {
|
||
[app.Sequelize.Op.like]: searchKeyword,
|
||
},
|
||
},
|
||
{
|
||
custom_barcode: {
|
||
[app.Sequelize.Op.like]: searchKeyword,
|
||
},
|
||
},
|
||
{
|
||
custom_name: {
|
||
[app.Sequelize.Op.like]: searchKeyword,
|
||
},
|
||
},
|
||
],
|
||
},
|
||
],
|
||
};
|
||
}
|
||
|
||
return app.model.LocationSpace.findAll({
|
||
where: whereCondition,
|
||
attributes: [
|
||
'id', 'space_code', 'custom_barcode', 'custom_name',
|
||
],
|
||
order: [[ 'space_code', 'DESC' ]],
|
||
limit: 50,
|
||
subQuery: false,
|
||
});
|
||
}
|
||
|
||
async searchSpace(data) {
|
||
const { keyword } = data;
|
||
const results = await this._searchByKeyword(keyword);
|
||
|
||
return { code: 200, data: results, total: results.length };
|
||
}
|
||
|
||
/**
|
||
* 批量按关键字查询库位。
|
||
*
|
||
* @param {Object} data 请求数据。
|
||
* @param {Array<string>} data.keywords 搜索关键字数组。
|
||
* @return {Promise<Object>} data 为与 keywords 一一对应的库位列表数组,
|
||
* 无记录时对应项为空数组 []。
|
||
*/
|
||
async searchSpaces(data) {
|
||
const { keywords } = data;
|
||
const keywordList = Array.isArray(keywords) ? keywords : [];
|
||
const resultList = await Promise.all(
|
||
keywordList.map(keyword => this._searchByKeyword(keyword))
|
||
);
|
||
|
||
return { code: 200, data: resultList, total: resultList.length };
|
||
}
|
||
}
|
||
module.exports = spaceService;
|