'use strict'; const { Service } = require('egg'); /** 业务缓存 key 统一前缀(与邮箱验证码 oms:email:* 区分) */ const PREFIX = 'oms:cache'; /** 各类缓存的 key 构造器 */ const KEYS = { user: userId => `${PREFIX}:user:${userId}`, userPrincipals: userId => `${PREFIX}:user-principals:${userId}`, principalOptions: userId => `${PREFIX}:principal-options:${userId}`, principal: principalId => `${PREFIX}:principal:${principalId}`, shopBasic: shopId => `${PREFIX}:shop-basic:${shopId}`, externalPrintAccount: accountId => `${PREFIX}:external-print-account:${accountId}`, expressTemplate: (accountId, platformCode, expressCode) => `${PREFIX}:express-template:${accountId}:${platformCode}:${expressCode}`, }; /** * 业务缓存服务 * 缓存登录用户信息、用户可用主体列表、主体详情,避免高频请求反复查库。 * Redis 异常时全部降级为直接查库(只告警不抛错),保证可用性。 */ class CacheService extends Service { /** @return {Object} redis 客户端 */ get redis() { return this.app.redis; } /** @return {Object} 缓存有效期配置(秒) */ get ttls() { return this.config.cache; } /** * 读取缓存(Redis 异常时返回 null,降级为查库) * @param {String} key 缓存 key * @return {Promise} 缓存值,不存在为 null */ async read(key) { try { const raw = await this.redis.get(key); return raw ? JSON.parse(raw) : null; } catch (err) { this.logger.warn(`[cache] 读取失败,key=${key}:${err.message}`); return null; } } /** * 写入缓存(值为空时不写入,避免缓存穿透到空数据) * @param {String} key 缓存 key * @param {any} value 缓存值 * @param {Number} ttl 有效秒数 * @return {Promise} 无返回值 */ async write(key, value, ttl = 300) { if (value === null || value === undefined) return; try { await this.redis.set(key, JSON.stringify(value), 'EX', ttl); } catch (err) { this.logger.warn(`[cache] 写入失败,key=${key}:${err.message}`); } } /** * 删除若干 key * @param {Array} keys 缓存 key 列表 * @return {Promise} 无返回值 */ async forget(...keys) { const valid = keys.filter(Boolean); if (!valid.length) return; try { await this.redis.del(...valid); } catch (err) { this.logger.warn(`[cache] 删除失败,key=${valid.join(',')}:${err.message}`); } } /** * 按前缀批量删除(SCAN + DEL,用于“某类缓存全部失效”) * @param {String} prefix key 前缀 * @return {Promise} 无返回值 */ async forgetByPrefix(prefix) { try { let cursor = '0'; do { const [ next, keys ] = await this.redis.scan(cursor, 'MATCH', `${prefix}*`, 'COUNT', 200); cursor = next; if (keys && keys.length) await this.redis.del(...keys); } while (cursor !== '0'); } catch (err) { this.logger.warn(`[cache] 按前缀删除失败,prefix=${prefix}:${err.message}`); } } /** * 缓存优先取值:命中直接返回,未命中执行 loader 查库并回写缓存 * @param {String} key 缓存 key * @param {Number} ttl 有效秒数 * @param {Function} loader 未命中时的数据加载函数 * @return {Promise} 数据 */ async remember(key, ttl, loader) { const cached = await this.read(key); if (cached !== null) return cached; const value = await loader(); await this.write(key, value, ttl); return value; } // ---------- 用户信息 ---------- /** * 登录用户信息(不含 password / salt) * @param {Number} userId 用户ID * @return {Promise} 用户信息,不存在为 null */ async getUser(userId) { return await this.remember(KEYS.user(userId), this.ttls.user, async () => { const user = await this.ctx.model.User.findByPk(userId, { attributes: { exclude: [ 'password', 'salt' ] }, }); return user ? user.toJSON() : null; }); } // ---------- 用户与主体的关联 ---------- /** * 用户已绑定的主体ID列表(用于多租户数据隔离) * 只返回启用状态(principal_users.status=1)的关联:员工被停用后不再拥有该主体的任何权限 * @param {Number} userId 用户ID * @return {Promise>} 主体ID数组 */ async getUserPrincipalIds(userId) { return await this.remember(KEYS.userPrincipals(userId), this.ttls.principal, async () => { const rows = await this.ctx.model.PrincipalUser.findAll({ where: { user_id: userId, status: 1 }, attributes: [ 'principal_id' ], }); return rows.map(row => Number(row.principal_id)); }); } /** * 用户可选主体列表(头部主体切换/下拉选择用,含该主体下的角色与默认标识) * 只返回启用状态的关联:员工在某个主体下被停用后,登录后不再展示该主体; * 主体本身停用时仍返回(前端置灰不可选、标注「已停用」),并按「启用优先」排序 * @param {Number} userId 用户ID * @return {Promise>} 主体选项列表 */ async getUserPrincipalOptions(userId) { return await this.remember(KEYS.principalOptions(userId), this.ttls.principalOptions, async () => { const relations = await this.ctx.model.PrincipalUser.findAll({ where: { user_id: userId, status: 1 }, attributes: [ 'id', 'principal_id', 'role', 'is_default', 'status' ], order: [[ 'is_default', 'DESC' ], [ 'id', 'ASC' ]], }); if (!relations.length) return []; const principals = await this.ctx.model.Principal.findAll({ where: { id: relations.map(item => item.principal_id) }, attributes: [ 'id', 'name', 'type', 'status', 'contact_name', 'contact_phone' ], }); const principalMap = new Map(principals.map(item => [ Number(item.id), item ])); return relations.map(item => { const principal = principalMap.get(Number(item.principal_id)); if (!principal) return null; return { id: Number(principal.id), name: principal.name, type: principal.type, status: principal.status, contact_name: principal.contact_name, contact_phone: principal.contact_phone, role: item.role, is_default: item.is_default, relation_status: item.status, }; }) .filter(Boolean) // 启用主体排在前面,保证切换/默认选择不会落在已停用主体上 .sort((a, b) => { const enabledDiff = (Number(b.status) === 1 ? 1 : 0) - (Number(a.status) === 1 ? 1 : 0); if (enabledDiff) return enabledDiff; return Number(b.is_default) - Number(a.is_default); }); }); } /** * 已启用的主体ID列表(停用的主体不参与定时任务、推送与自动拉单) * 不做缓存:任务频率低,且主体状态变更需要立即生效 * @return {Promise>} 主体ID数组 */ async getEnabledPrincipalIds() { const rows = await this.ctx.model.Principal.findAll({ where: { status: 1 }, attributes: [ 'id' ], raw: true, }); return rows.map(row => Number(row.id)); } // ---------- 主体信息 ---------- /** * 主体详情 * @param {Number} principalId 主体ID * @return {Promise} 主体信息,不存在为 null */ async getPrincipal(principalId) { return await this.remember(KEYS.principal(principalId), this.ttls.principal, async () => { const principal = await this.ctx.model.Principal.findByPk(principalId); return principal ? principal.toJSON() : null; }); } // ---------- 店铺 / 打单平台配置(推送、取号高频读取) ---------- /** * 店铺基础资料(推送需要名称,取号需要类型与外部打单账号) * @param {Number} shopId 店铺ID * @return {Promise} 店铺基础资料,不存在为 null */ async getShopBasic(shopId) { if (!shopId) return null; return await this.remember(KEYS.shopBasic(shopId), this.ttls.shop, async () => { const shop = await this.ctx.model.Shop.findByPk(shopId, { attributes: [ 'id', 'principal_id', 'name', 'type', 'external_print_account_id' ], }); return shop ? shop.toJSON() : null; }); } /** * 外部打单账号及其平台配置(含 fetch_waybill_no,决定是否回 OMS 取号) * @param {Number} accountId 外部打单账号ID * @return {Promise} 账号与平台配置,不存在为 null */ async getExternalPrintAccount(accountId) { if (!accountId) return null; return await this.remember(KEYS.externalPrintAccount(accountId), this.ttls.platform, async () => { const account = await this.ctx.model.ExternalPrintAccount.findByPk(accountId, { attributes: [ 'id', 'principal_id', 'platform_id' ], include: [ { model: this.ctx.model.ExternalPrintPlatform, as: 'platform', attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ], }, ], }); return account ? account.toJSON() : null; }); } /** * 快递编码 → 面单模板绑定关系(未绑定的结果也缓存,避免批量取号反复穿透查库) * @param {Number} accountId 外部打单账号ID * @param {String} platformCode OMS 预设平台编码 * @param {String} expressCode 快递编码(系统或自定义) * @param {Function} loader 未命中时的查询函数 * @return {Promise} 模板记录,未绑定为 null */ async getExpressTemplate(accountId, platformCode, expressCode, loader) { const cached = await this.remember( KEYS.expressTemplate(accountId, platformCode, expressCode), this.ttls.platform, async () => ({ template: (await loader()) || null }) ); return cached ? cached.template : null; } // ---------- 失效 ---------- /** * 用户资料/状态变更后失效:用户缓存 + 该用户的主体相关缓存 * @param {Number} userId 用户ID * @return {Promise} 无返回值 */ async invalidateUser(userId) { await this.forget( KEYS.user(userId), KEYS.userPrincipals(userId), KEYS.principalOptions(userId) ); } /** * 用户与主体的绑定关系变更后失效:主体ID列表 + 可选主体列表 * @param {Number} userId 用户ID * @return {Promise} 无返回值 */ async invalidateUserPrincipals(userId) { await this.forget(KEYS.userPrincipals(userId), KEYS.principalOptions(userId)); } /** * 主体新增/更新/删除后失效:主体详情 + 所有依赖主体信息的缓存 * (主体名称与状态变化会影响任意用户的可选主体列表,故按前缀整体失效) * @param {Number} principalId 主体ID * @return {Promise} 无返回值 */ async invalidatePrincipal(principalId) { await this.forget(KEYS.principal(principalId)); await this.forgetByPrefix(`${PREFIX}:principal-options:`); await this.forgetByPrefix(`${PREFIX}:user-principals:`); } /** * 店铺资料变更后失效 * @param {Number} shopId 店铺ID * @return {Promise} 无返回值 */ async invalidateShop(shopId) { await this.forget(KEYS.shopBasic(shopId)); } /** * 外部打单账号(或其快递接口绑定)变更后失效:账号平台配置 + 该账号下所有编码绑定 * @param {Number} accountId 外部打单账号ID * @return {Promise} 无返回值 */ async invalidateExternalPrintAccount(accountId) { await this.forget(KEYS.externalPrintAccount(accountId)); // 绑定关系按(账号 + 平台 + 编码)建 key,只能按账号前缀批量清除 await this.forgetByPrefix(`${PREFIX}:express-template:${accountId}:`); } } module.exports = CacheService;