737 lines
28 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');
// 从分组服务导入群类型定义,用于两层类型校验
const { GROUP_TYPES: INBOX_GROUP_TYPES } = require('../../inbox/groups');
/**
* 站内信群管理业务逻辑层。
* 提供群列表查询、禁用、修改等核心能力。
*/
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 };
}
/**
* 群快速查询(下拉选择用,不分页)。
* 关键词同时模糊匹配群名称与外部群ID,按创建时间倒序返回轻量字段,
* 软删除记录由 paranoid 自动排除。
* 双维度可选过滤,均不传时 where 不含这两列、返回所有仓库/货主的群:
* - store_id(货主维度)↔ wms_inbox_group.store_id 列;
* - warehouse_id(仓库维度)↔ wms_inbox_group.warehouse_id 列;
* - 两者可同时传(AND 关系),也可都不传(不加对应过滤条件)。
*
* @param {Object} data 请求数据。
* @param {number|string} [data.storeId] 货主ID(可选,来自 API 入参 store_id,映射到 wms_inbox_group.store_id 列;
* 传入时须为可解析的正整数,否则抛错「store_id 无效」;不传或为空时不加货主过滤)。
* @param {number|string} [data.warehouseId] 仓库ID(可选,来自 API 入参 warehouse_id,映射到 wms_inbox_group.warehouse_id 列;
* 传入时须为可解析的正整数,否则抛错「warehouse_id 无效」;不传或为空时不加仓库过滤)。
* @param {string} [data.keyword] 关键词,模糊匹配 group_name / group_id。
* @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。
* @param {number} [data.limit=20] 返回条数上限,最大 100。
* @return {Promise<{list: Array<{id: number, group_id: (string|null), group_name: string, group_type: (string|null), sub_type: (string|null), is_blocked: number}>}>} 群快速列表。
*/
async quickList(data = {}) {
const { ctx } = this;
const { InboxGroup } = ctx.model;
const { Op } = ctx.app.Sequelize;
const keyword = String(data.keyword || '').trim();
const groupType = String(data.groupType || '').trim();
const limit = Math.min(100, Math.max(1, Number(data.limit) || 20));
const where = {};
// store_id(货主维度,对应 wms_inbox_group.store_id 列)可选:
// 传入时校验为可解析的正整数,设置 where.store_id;不传或为空串时不加货主过滤
const storeIdRaw = String(data.storeId ?? '').trim();
if (storeIdRaw) {
const storeId = Number(storeIdRaw);
if (!Number.isInteger(storeId) || storeId <= 0) throw new Error('store_id 无效');
where.store_id = storeId;
}
// warehouse_id(仓库维度,对应 wms_inbox_group.warehouse_id 列)可选:
// 传入时校验为可解析的正整数,设置 where.warehouse_id;不传或为空串时不加仓库过滤
const warehouseIdRaw = String(data.warehouseId ?? '').trim();
if (warehouseIdRaw) {
const warehouseId = Number(warehouseIdRaw);
if (!Number.isInteger(warehouseId) || warehouseId <= 0) throw new Error('warehouse_id 无效');
where.warehouse_id = warehouseId;
}
if (groupType) where.group_type = groupType;
if (keyword) {
where[Op.or] = [
{ group_name: { [Op.like]: `%${keyword}%` } },
{ group_id: { [Op.like]: `%${keyword}%` } },
];
}
const rows = await InboxGroup.findAll({
attributes: [ 'id', 'group_id', 'group_name', 'group_type', 'sub_type', 'is_blocked' ],
where,
order: [[ 'created_at', 'DESC' ]],
limit,
raw: true,
});
return { list: rows };
}
/**
* 查询一个或多个群的成员列表(下拉选择用,多群聚合)。
* 先用内部主键数组 + 仓库批量校验群存在(软删自动排除,attributes 只取 id/group_id,
* 找不到任何匹配群抛「群不存在或无权限操作」),再收集所有群的外部群ID(去重、剔除空值),
* 按外部群ID集合在消息表中聚合去重成员:取每个 user_id 最新一条消息的 user_name
* (消息按 id 倒序,首次出现的即最新),关键词在聚合后对 user_name / user_id 做包含匹配,
* 最后截断到 limit 条。外部群ID集合为空时直接返回空列表。
* 局限说明:多群共享同一聚合池,最多取最近 500 条消息,更早消息中的成员不会出现在结果中;
* user_id 为 NULL / 空串的消息被排除;关键词匹配大小写不敏感。
*
* @param {Object} data 请求数据。
* @param {Array<number|string>} data.groupIds wms_inbox_group 内部主键ID数组(必填,非空且每个元素为正整数)。
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
* @param {string} [data.keyword] 关键词,模糊匹配 user_name / user_id。
* @param {number} [data.limit=20] 返回条数上限,最大 100。
* @return {Promise<{list: Array<{user_id: string, user_name: string}>}>} 群成员列表。
*/
async members(data = {}) {
const { ctx } = this;
const { InboxGroup, InboxMessage } = ctx.model;
const { Op } = ctx.app.Sequelize;
const warehouseId = Number(data.warehouseId);
if (!warehouseId) throw new Error('warehouseId 无效');
// groupIds 校验:非空数组且每个元素为数字或可解析数字字符串的正整数
const rawGroupIds = data.groupIds;
if (!Array.isArray(rawGroupIds) || rawGroupIds.length === 0) {
throw new Error('groupIds 无效');
}
const groupIds = rawGroupIds.map(item => {
if (typeof item !== 'number' && typeof item !== 'string') return NaN;
return Number(item);
});
if (groupIds.some(id => !Number.isInteger(id) || id <= 0)) {
throw new Error('groupIds 无效');
}
// 批量校验群存在(软删自动排除),attributes 只取 id / group_id
const groups = await InboxGroup.findAll({
attributes: [ 'id', 'group_id' ],
where: { id: { [Op.in]: groupIds }, warehouse_id: warehouseId },
raw: true,
});
if (!groups || groups.length === 0) {
throw new Error('群不存在或无权限操作');
}
// 收集所有群的外部群ID(去重、剔除空值),全部为空则没有可关联的消息成员
const externalGroupIds = [ ...new Set(
groups.map(g => String(g.group_id || '').trim()).filter(Boolean)
) ];
if (externalGroupIds.length === 0) {
return { list: [] };
}
const keyword = String(data.keyword || '').trim();
const limit = Math.min(100, Math.max(1, Number(data.limit) || 20));
// 拉取多群最近消息集合(软删除由 paranoid 自动排除),共享同一聚合池。
// 局限说明:聚合池最多取最近 500 条消息,更早消息中的成员不会出现在结果中。
// user_id 同时排除 NULL 与空串(用字段级 Op.and 避免同名键覆盖),
// 防止脏数据进入聚合池并输出 "null"/"" 成员。
const messages = await InboxMessage.findAll({
attributes: [ 'id', 'user_id', 'user_name' ],
where: {
warehouse_id: warehouseId,
group_id: { [Op.in]: externalGroupIds },
user_id: {
[Op.and]: [
{ [Op.ne]: null },
{ [Op.ne]: '' },
],
},
},
order: [[ 'id', 'DESC' ]],
limit: 500,
raw: true,
});
// 按 user_id 去重:消息已按 id 倒序,首次出现即该用户最新消息。
// JS 层兜底:跳过 null/undefined user_id,防止 String(null) 变成 "null" 输出。
const memberMap = new Map();
for (const msg of messages) {
if (msg.user_id === null || msg.user_id === undefined) continue;
const userId = String(msg.user_id).trim();
if (!userId || memberMap.has(userId)) continue;
memberMap.set(userId, String(msg.user_name || '').trim());
}
let list = Array.from(memberMap.entries())
.map(([ user_id, user_name ]) => ({ user_id, user_name }));
// 关键词在聚合结果上过滤 user_name / user_id:
// 统一转小写后做包含匹配,与 quickList 的 SQL LIKE(MySQL 默认大小写不敏感)语义一致
if (keyword) {
const lowerKeyword = keyword.toLowerCase();
list = list.filter(item => {
const userName = String(item.user_name || '').toLowerCase();
const userId = String(item.user_id || '').toLowerCase();
return userName.includes(lowerKeyword) || userId.includes(lowerKeyword);
});
}
return { list: list.slice(0, limit) };
}
/**
* 禁用 / 解禁群。
*
* @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 || '';
// 两层类型校验:subType 必须在对应 groupType 的合法子类型列表中
if (data.subType !== undefined && targetGroupType) {
const gtDef = INBOX_GROUP_TYPES.find(gt => gt.type === targetGroupType);
if (!gtDef) {
throw new Error(`无效的群类型: ${targetGroupType}`);
}
const subType = String(data.subType || '').trim();
if (subType) {
const validKeys = gtDef.subTypes.map(st => st.key);
if (!validKeys.includes(subType)) {
throw new Error(
`子类型 "${subType}" 不在群类型 "${targetGroupType}" 的合法范围内,` +
`可用值: ${validKeys.join(', ')}`
);
}
}
}
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;
} else if (data.groupType !== undefined && targetGroupType !== 'store') {
// 群类型切为非货主群(warehouse/express)且未显式传 storeId 时,
// 清空遗留的货主绑定,避免仓库群/快递群仍残留 store_id
updateData.store_id = null;
}
// 快递专属字段处理
if (isExpress) {
if (expressInterfaces !== null) {
updateData.express_interfaces = expressInterfaces || null;
}
if (systemExpressCode !== undefined) {
updateData.system_express_code = systemExpressCode || null;
}
} else if (data.groupType !== undefined) {
// 群类型切为非快递群(store/warehouse)时清空快递专属配置,
// 避免货主群/仓库群残留 express_interfaces / system_express_code
updateData.express_interfaces = null;
updateData.system_express_code = 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(',')}`
);
}
/**
* 清空群类型配置。
* 将群恢复为"仅保留创建信息"状态:清空 group_type / sub_type / store_id /
* express_interfaces / system_express_code,AI 开关重置为关闭。
* 保留群名称、群ID、仓库、来源信息、屏蔽状态与扩展数据。
*
* @param {Object} data 请求数据。
* @param {number} data.id 群记录主键ID(必填)。
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
* @return {Promise<{id: number, group_name: string, group_id: string|null}>} 被重置的群信息。
*/
async reset(data = {}) {
const { ctx } = this;
const { InboxGroup } = ctx.model;
const id = Number(data.id);
const warehouseId = Number(data.warehouseId);
if (!warehouseId) throw new Error('warehouseId 无效');
if (!id) throw new Error('群ID无效');
const where = { id, warehouse_id: warehouseId };
const group = await InboxGroup.findOne({
attributes: [ 'id', 'group_name', 'group_id' ],
where,
raw: true,
});
if (!group) throw new Error('群不存在或无权限操作');
await InboxGroup.update(
{
group_type: null,
sub_type: null,
store_id: null,
express_interfaces: null,
system_express_code: null,
ai_enabled: 0,
},
{ where }
);
ctx.logger.info(
`[inbox group] 清空群类型配置 id=${group.id} group_id=${group.group_id} warehouse_id=${warehouseId}`
);
return { id: group.id, group_name: group.group_name, group_id: group.group_id };
}
/**
* 校验快递接口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}" 不存在`);
}
}
/**
* 根据快递接口ID和快递编码,查询绑定的售后群和揽收群。
*
* 匹配规则:
* 1. group_type = 'express'
* 2. system_express_code 精确匹配 expressCode
* 3. express_interfaces 为空(未设置)→ 视为匹配所有该快递的接口
* 4. express_interfaces 不为空 → 必须包含传入的 expressInterfaceId
*
* @param {Object} params 查询参数。
* @param {number} params.expressInterfaceId 快递接口ID(wms_express_interface.id)。
* @param {string} params.expressCode 快递编码(wms_express.code)。
* @param {number} [params.warehouseId] 仓库ID,不传则查所有仓库。
* @return {Promise<{afterSalesGroups: Array, pickupGroups: Array}>} 售后群和揽收群列表。
*/
async findGroupsByExpress({ expressInterfaceId, expressCode, warehouseId }) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const eid = Number(expressInterfaceId);
const code = String(expressCode || '').trim();
if (!eid || !code) {
throw new Error('expressInterfaceId 和 expressCode 不能为空');
}
const where = {
group_type: 'express',
system_express_code: code,
is_blocked: 0,
[Op.or]: [
{ express_interfaces: { [Op.or]: [ null, '' ] } },
{ express_interfaces: { [Op.like]: `%${eid}%` } },
],
};
if (warehouseId) {
where.warehouse_id = Number(warehouseId);
}
const rows = await ctx.model.InboxGroup.findAll({
attributes: [ 'id', 'group_name', 'group_id', 'sub_type', 'express_interfaces', 'warehouse_id', 'ext_data' ],
where,
raw: true,
});
const afterSalesGroups = rows.filter(r => r.sub_type === 'after_sales');
const pickupGroups = rows.filter(r => r.sub_type === 'pickup');
ctx.logger.info(
`[inbox group] 查快递绑定群 eid=${eid} code=${code} ` +
`after_sales=${afterSalesGroups.length} pickup=${pickupGroups.length}`
);
return { afterSalesGroups, pickupGroups };
}
/**
* 根据货主ID列表,查询绑定的货主售后群。
*
* 匹配规则:
* 1. group_type = 'store'
* 2. sub_type = 'after_sales'
* 3. store_id 在传入列表中
*
* @param {Object} params 查询参数。
* @param {number[]} params.storeIds 货主ID列表。
* @param {number} params.warehouseId 仓库ID。
* @return {Promise<Array>} 货主售后群列表 [{group_id, group_name, store_id, ext_data}]。
*/
async findStoreAfterSalesGroups({ storeIds, warehouseId }) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const ids = (Array.isArray(storeIds) ? storeIds : [ storeIds ])
.map(id => Number(id))
.filter(id => Number.isFinite(id) && id > 0);
if (ids.length === 0) {
return [];
}
const rows = await ctx.model.InboxGroup.findAll({
attributes: [ 'id', 'group_name', 'group_id', 'store_id', 'ext_data' ],
where: {
warehouse_id: Number(warehouseId),
group_type: 'store',
sub_type: 'after_sales',
store_id: { [Op.in]: ids },
is_blocked: 0,
},
raw: true,
});
ctx.logger.info(
`[inbox group] 查货主售后群 warehouse=${warehouseId} ` +
`stores=[${ids.join(',')}] found=${rows.length}`
);
return rows;
}
}
module.exports = InboxGroupService;