liufumingren 35c71e13c4 feat(inbox): 群列表字段优化、where查询支持、快递接口加载及时间格式化
inbox.group.list 优化:
- 移除 warehouse_id 返回字段
- 新增 store_name(StoreWarehouse.store_remask)
- express_interfaces 改为 {id,name} 对象数组
- 新增 system_express_name(wms_express.name)
- created_at/updated_at 使用 app.formatDate 格式化
- 支持 pagination 对象 + where 结构化查询(parseWhereConditions)
- keyword 虚拟字段映射为 group_name LIKE
- groupType 驼峰映射为 group_type
- 增加 specialFieldMap 声明合法字段

新增 index.loadExpressInterfaces:
- 参考 loadStores 模式,拉取仓库下快递接口下拉列表
- 支持 systemExpressCode 入参过滤
- systemMethods/index.js 注册 + methods/system.json 文档

其他:
- delivery_order_code + store_id 联合索引迁移
2026-08-08 01:58:06 +08:00

380 lines
13 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 Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
/**
* 站内信群管理业务逻辑层。
* 提供群列表查询、禁用、修改等核心能力。
*/
class InboxGroupService extends Service {
/**
* 拉取当前仓库的群列表。
*
* @param {Object} data 请求数据。
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
* @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。
* @param {string} [data.keyword] 按群名称模糊搜索。
* @param {number} [data.page=1] 页码。
* @param {number} [data.pageSize=20] 每页条数。
* @return {Promise<Object>} { total, list }。
*/
async list(data = {}) {
const { ctx } = this;
const { InboxGroup, StoreWarehouse, ExpressInterface, Express } = ctx.model;
const { Op } = ctx.app.Sequelize;
const warehouseId = Number(data.warehouseId);
// 分页:优先取 pagination 对象,兜底扁平参数
const pag = data.pagination || {};
const page = Math.max(1, Number(pag.page || data.page) || 1);
const pageSize = Math.min(100, Math.max(1, Number(pag.pageSize || data.pageSize) || 20));
const offset = (page - 1) * pageSize;
if (!warehouseId) throw new Error('warehouseId 无效');
const where = { warehouse_id: warehouseId };
// ── 扁平参数(向后兼容)──
const groupType = String(data.groupType || '').trim();
const keyword = String(data.keyword || '').trim();
if (groupType) where.group_type = groupType;
if (keyword) where.group_name = { [Op.like]: `%${keyword}%` };
// ── 结构化 where(operator 模式)──
if (data.where && typeof data.where === 'object') {
// 从 where 中提取虚拟字段(不允许直接作为列名查询)
const whereInput = { ...data.where };
// keyword:虚拟字段 → 模糊搜索 group_name
if (whereInput.keyword !== undefined) {
const kw = whereInput.keyword;
delete whereInput.keyword;
const kwValue = kw && typeof kw === 'object' && kw.value !== undefined ? kw.value : kw;
const kwArr = Array.isArray(kwValue) ? kwValue : [ kwValue ];
const kwStr = kwArr.filter(Boolean).join('').trim();
if (kwStr && !keyword) {
where.group_name = { [Op.like]: `%${kwStr}%` };
}
}
// groupType: camelCase → group_type(优先已从扁平参数设置的 group_type)
if (whereInput.groupType !== undefined) {
const gt = whereInput.groupType;
delete whereInput.groupType;
const gtValue = gt && typeof gt === 'object' && gt.value !== undefined ? gt.value : gt;
const gtStr = String(gtValue || '').trim();
if (gtStr && !groupType) {
where.group_type = gtStr;
}
}
if (Object.keys(whereInput).length > 0) {
const parsed = parseWhereConditions({
where: whereInput,
app: ctx.app,
specialFieldMap: {
store_id: { field: 'store_id' },
group_id: { field: 'group_id' },
group_name: { field: 'group_name' },
sub_type: { field: 'sub_type' },
source_type: { field: 'source_type' },
is_blocked: { field: 'is_blocked' },
ai_enabled: { field: 'ai_enabled' },
system_express_code: { field: 'system_express_code' },
},
});
if (!parsed.ok) {
throw new Error(`where 参数解析失败: ${parsed.reason}`);
}
if (Array.isArray(parsed.result.dynamicConditions)) {
Object.assign(where, ...parsed.result.dynamicConditions);
}
}
}
const { count, rows } = await InboxGroup.findAndCountAll({
attributes: [
'id', 'group_name', 'group_id', 'store_id',
'group_type', 'sub_type', 'source_type', 'source_extra',
'is_blocked', 'ai_enabled', 'express_interfaces', 'system_express_code',
'created_at', 'updated_at',
],
where,
order: [[ 'created_at', 'DESC' ]],
limit: pageSize,
offset,
raw: true,
});
// 收集需要批量查询的 ID
const storeIds = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ];
const allExpressInterfaceIds = [];
const expressCodes = [ ...new Set(rows.map(r => r.system_express_code).filter(Boolean)) ];
rows.forEach(row => {
if (row.express_interfaces) {
const ids = row.express_interfaces.split(',').map(Number).filter(Boolean);
ids.forEach(id => allExpressInterfaceIds.push(id));
}
});
const uniqueExpressInterfaceIds = [ ...new Set(allExpressInterfaceIds) ];
// 批量查询货主仓库合约备注
let storeWarehouseMap = {};
if (storeIds.length > 0) {
const swRows = await StoreWarehouse.findAll({
attributes: [ 'store_id', 'store_remask' ],
where: {
store_id: { [Op.in]: storeIds },
warehouse_id: warehouseId,
},
raw: true,
});
storeWarehouseMap = swRows.reduce((acc, sw) => {
acc[sw.store_id] = sw.store_remask || '';
return acc;
}, {});
}
// 批量查询快递接口名称
let expressInterfaceMap = {};
if (uniqueExpressInterfaceIds.length > 0) {
const eiRows = await ExpressInterface.findAll({
attributes: [ 'id', 'name' ],
where: { id: { [Op.in]: uniqueExpressInterfaceIds } },
raw: true,
});
expressInterfaceMap = eiRows.reduce((acc, ei) => {
acc[ei.id] = ei.name || '';
return acc;
}, {});
}
// 批量查询系统快递名称
let expressNameMap = {};
if (expressCodes.length > 0) {
const expressRows = await Express.findAll({
attributes: [ 'code', 'name' ],
where: { code: { [Op.in]: expressCodes } },
raw: true,
});
expressNameMap = expressRows.reduce((acc, e) => {
acc[e.code] = e.name || '';
return acc;
}, {});
}
// 组装返回数据
const formatDate = ctx.app.formatDate;
const list = rows.map(row => ({
...row,
store_name: row.store_id ? (storeWarehouseMap[row.store_id] || '') : '',
express_interfaces: row.express_interfaces
? row.express_interfaces.split(',').map(Number).filter(Boolean)
.map(id => ({
id,
name: expressInterfaceMap[id] || '',
}))
: [],
system_express_name: row.system_express_code
? (expressNameMap[row.system_express_code] || '')
: '',
created_at: row.created_at ? formatDate(row.created_at) : '',
updated_at: row.updated_at ? formatDate(row.updated_at) : '',
}));
return { total: count, list };
}
/**
* 禁用 / 解禁群。
*
* @param {Object} data 请求数据。
* @param {number} data.id 群记录主键ID(必填)。
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
* @param {number} data.isBlocked 是否屏蔽 1=禁用 0=启用。
* @return {Promise<void>}
*/
async disable(data = {}) {
const { ctx } = this;
const { InboxGroup } = ctx.model;
const id = Number(data.id);
const warehouseId = Number(data.warehouseId);
const isBlocked = data.isBlocked === 1 ? 1 : 0;
if (!id) throw new Error('群ID无效');
if (!warehouseId) throw new Error('warehouseId 无效');
const [ affected ] = await InboxGroup.update(
{ is_blocked: isBlocked },
{ where: { id, warehouse_id: warehouseId } }
);
if (!affected) {
throw new Error('群不存在或无权限操作');
}
ctx.logger.info(
`[inbox group] ${isBlocked ? '禁用' : '启用'}群 id=${id} warehouse_id=${warehouseId}`
);
}
/**
* 修改群信息。
* 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。
* 群类型切为 express 时 system_express_code 必填,
* express_interfaces 仅在群类型为 express 时生效(非 express 类型忽略)。
*
* @param {Object} data 请求数据。
* @param {number} data.id 群记录主键ID(必填)。
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
* @param {string} [data.groupType] 群类型:store / warehouse / express。
* @param {string} [data.subType] 群子类型。
* @param {number} [data.storeId] 关联货主ID。
* @param {number[]} [data.expressInterfaces] 快递接口ID数组。
* @param {string} [data.systemExpressCode] 系统快递编码。
* @return {Promise<void>}
*/
async update(data = {}) {
const { ctx } = this;
const { InboxGroup } = ctx.model;
const id = Number(data.id);
const warehouseId = Number(data.warehouseId);
if (!id) throw new Error('群ID无效');
if (!warehouseId) throw new Error('warehouseId 无效');
// 查群是否存在
const group = await InboxGroup.findOne({
attributes: [ 'id', 'group_type', 'group_id', 'warehouse_id' ],
where: { id, warehouse_id: warehouseId },
raw: true,
});
if (!group) throw new Error('群不存在或无权限操作');
// 目标群类型(优先新值,否则保留原值)
const targetGroupType = data.groupType !== undefined
? String(data.groupType).trim()
: group.group_type || '';
const isExpress = targetGroupType === 'express';
// express_interfaces 处理
let expressInterfaces = null;
if (data.expressInterfaces !== undefined) {
if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length > 0) {
// 校验快递接口ID有效性
await this.validateExpressInterfaces(data.expressInterfaces);
expressInterfaces = data.expressInterfaces.join(',');
} else if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length === 0) {
// 空数组 = 清空 = 表示全部快递类型
expressInterfaces = '';
} else {
expressInterfaces = null; // 未传入 = 不修改
}
}
// system_express_code 校验
let systemExpressCode;
if (data.systemExpressCode !== undefined) {
const code = String(data.systemExpressCode).trim();
if (code) {
await this.validateSystemExpressCode(code);
systemExpressCode = code;
} else {
systemExpressCode = null;
}
}
// 切换为 express 类型时 system_express_code 不能为空
if (isExpress && data.groupType !== undefined) {
const finalCode = systemExpressCode !== undefined ? systemExpressCode : group.system_express_code;
if (!finalCode) {
throw new Error('群类型为快递群时,系统快递编码不能为空');
}
}
// 构建更新字段
const updateData = {};
if (data.groupType !== undefined) updateData.group_type = targetGroupType || null;
if (data.subType !== undefined) updateData.sub_type = String(data.subType || '').trim() || null;
if (data.storeId !== undefined) {
updateData.store_id = Number.isFinite(Number(data.storeId)) && Number(data.storeId) > 0
? Number(data.storeId) : null;
}
// 非 express 群类型时忽略 express 相关字段
if (isExpress && expressInterfaces !== null) {
updateData.express_interfaces = expressInterfaces || null;
}
if (isExpress && systemExpressCode !== undefined) {
updateData.system_express_code = systemExpressCode || null;
}
// AI 开关(所有群类型均支持)
if (data.aiEnabled !== undefined) {
updateData.ai_enabled = data.aiEnabled === 1 ? 1 : 0;
}
if (Object.keys(updateData).length === 0) {
throw new Error('未提供任何需要修改的字段');
}
await InboxGroup.update(updateData, { where: { id, warehouse_id: warehouseId } });
ctx.logger.info(
`[inbox group] 修改群 id=${id} fields=${Object.keys(updateData).join(',')}`
);
}
/**
* 校验快递接口ID数组的有效性。
* 所有ID必须在 wms_express_interface 表中存在。
*
* @param {number[]} ids 快递接口ID数组。
* @return {Promise<void>} 无效时抛出异常。
*/
async validateExpressInterfaces(ids) {
const { ctx } = this;
if (!Array.isArray(ids) || ids.length === 0) return;
const numericIds = ids.map(Number).filter(id => Number.isFinite(id) && id > 0);
if (numericIds.length !== ids.length) {
throw new Error('快递接口ID包含无效值');
}
const count = await ctx.model.ExpressInterface.count({
where: { id: { [ctx.app.Sequelize.Op.in]: numericIds } },
});
if (count !== numericIds.length) {
throw new Error('部分快递接口ID不存在');
}
}
/**
* 校验系统快递编码有效性。
* 必须在 wms_express 表中存在对应的 code。
*
* @param {string} code 系统快递编码。
* @return {Promise<void>} 无效时抛出异常。
*/
async validateSystemExpressCode(code) {
const { ctx } = this;
const trimmed = String(code).trim();
if (!trimmed) throw new Error('系统快递编码不能为空');
const exists = await ctx.model.Express.count({
where: { code: trimmed },
});
if (!exists) {
throw new Error(`系统快递编码 "${trimmed}" 不存在`);
}
}
}
module.exports = InboxGroupService;