oms/backend/app/service/cache.js
liufumingren eaf957ed14 feat(express): 外部打单快递接口、自定义快递编码与回 OMS 取号
- 外部打单平台快递接口:按账号同步平台模板、绑定快递编码、查看模板明细;打开列表只读库,仅「从平台同步数据」时拉取
- 系统管理新增自定义快递编码字典,订单改快递 / 物流下拉合并系统与自定义编码,推送奇门沿用订单上的编码
- 新增 OpenAPI deliveryorder.getwaybill:WMS 批量回取号(单次≤100、并发4、逐单结果),快递编码只取 WMS 报文,取消/作废/归档返回失败,已取号直接复用
- 新增 openapi_request_idempotency 请求级幂等:request_id 回放、报文摘要校验、30 分钟 stale 接管、7 天定时清理
- 外部打单平台订单按平台 fetch_waybill_no 下发 need_oms_waybill,推送时实时判定并回写单据
- 店铺、打单账号平台配置与「平台+编码→模板」绑定走 Redis 缓存,绑定/账号变更主动失效,避免批量推送与取号逐单查库

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-04 04:10:37 +08:00

314 lines
11 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');
/** 业务缓存 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<any>} 缓存值,不存在为 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<void>} 无返回值
*/
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<String>} keys 缓存 key 列表
* @return {Promise<void>} 无返回值
*/
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<void>} 无返回值
*/
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<any>} 数据
*/
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<Object>} 用户信息,不存在为 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列表(用于多租户数据隔离)
* @param {Number} userId 用户ID
* @return {Promise<Array<Number>>} 主体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 },
attributes: [ 'principal_id' ],
});
return rows.map(row => Number(row.principal_id));
});
}
/**
* 用户可选主体列表(头部主体切换/下拉选择用,含该主体下的角色与默认标识)
* @param {Number} userId 用户ID
* @return {Promise<Array<Object>>} 主体选项列表
*/
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 },
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);
});
}
// ---------- 主体信息 ----------
/**
* 主体详情
* @param {Number} principalId 主体ID
* @return {Promise<Object>} 主体信息,不存在为 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<Object>} 店铺基础资料,不存在为 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<Object>} 账号与平台配置,不存在为 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<Object|null>} 模板记录,未绑定为 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<void>} 无返回值
*/
async invalidateUser(userId) {
await this.forget(
KEYS.user(userId),
KEYS.userPrincipals(userId),
KEYS.principalOptions(userId)
);
}
/**
* 用户与主体的绑定关系变更后失效:主体ID列表 + 可选主体列表
* @param {Number} userId 用户ID
* @return {Promise<void>} 无返回值
*/
async invalidateUserPrincipals(userId) {
await this.forget(KEYS.userPrincipals(userId), KEYS.principalOptions(userId));
}
/**
* 主体新增/更新/删除后失效:主体详情 + 所有依赖主体信息的缓存
* (主体名称与状态变化会影响任意用户的可选主体列表,故按前缀整体失效)
* @param {Number} principalId 主体ID
* @return {Promise<void>} 无返回值
*/
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<void>} 无返回值
*/
async invalidateShop(shopId) {
await this.forget(KEYS.shopBasic(shopId));
}
/**
* 外部打单账号(或其快递接口绑定)变更后失效:账号平台配置 + 该账号下所有编码绑定
* @param {Number} accountId 外部打单账号ID
* @return {Promise<void>} 无返回值
*/
async invalidateExternalPrintAccount(accountId) {
await this.forget(KEYS.externalPrintAccount(accountId));
// 绑定关系按(账号 + 平台 + 编码)建 key,只能按账号前缀批量清除
await this.forgetByPrefix(`${PREFIX}:express-template:${accountId}:`);
}
}
module.exports = CacheService;