'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} { 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} */ 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} */ 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(',')}` ); } /** * 校验快递接口ID数组的有效性。 * 所有ID必须在 wms_express_interface 表中存在。 * * @param {number[]} ids 快递接口ID数组。 * @return {Promise} 无效时抛出异常。 */ 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} 无效时抛出异常。 */ 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, [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} 货主售后群列表 [{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 }, }, raw: true, }); ctx.logger.info( `[inbox group] 查货主售后群 warehouse=${warehouseId} ` + `stores=[${ids.join(',')}] found=${rows.length}` ); return rows; } } module.exports = InboxGroupService;