【新增模块】 - app/model/store_express_binding_policy.js: 策略数据模型(17字段,JSON数组) - app/service/systems/store_express_binding_policy.js: CRUD+列表(含名称批量解析) - app/service/systems/express_policy.js: 缓存优先策略查询 + 6维漏斗匹配引擎 - app/service/systemMethods/store_express_binding_policy.js: method路由层 - database/designs/store-express-binding-policy-design.md: 设计文档 【策略漏斗匹配逻辑】 - 按priority DESC逐条匹配: store_ids→shop_name→prohibited→regions→exclude→weight - NULL/空数组=不限, 未命中自动continue到下一条 - 地区/店铺匹配使用子串包含(省/市/区/详细地址均生效) - 违禁品匹配使用数组交集 - 输出快递编码+重量类型, 未命中返回null 【订单创建链路集成】 - addOrder→addOrderLines后触发matchPolicy(weight可用) - 命中: 写入logistics/sys_logistics 4字段+weight_type+操作日志 - 未命中: 降级到resolveExpressSnapshot默认值+兜底DEFAULT_STORE_SUBJECT_CONFIG(STO) - 系统快递4字段一致, 自定义映射(express_setting)分流写入 【运单号分配优化】 - pickWaybillExpressInterface两步兜底: Step1: logistics_code仅匹配express_code(自定义编码精确) Step2: sys_logistics_code匹配全候选码(系统编码兜底) - 新增weight_type过滤器(接口NULL=通配, 设限须精确匹配) - groupedOrder.options新增sys_logistics_code/weight_type传递 【操作码翻译】 - ORDER_EXPRESS_POLICY_MATCH: '策略命中' - ORDER_EXPRESS_FALLBACK: '快递降级' - 无策略命中时写入快递降级日志 【API文档】 - methods/system.json: 策略模块4接口+响应字段(express_name/数组类型等) 【数据库迁移】 - 13个migration: 建表→字段迭代→TEXT改JSON→prohibited改数组(dev+prod均执行)
276 lines
8.9 KiB
JavaScript
276 lines
8.9 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
/**
|
||
* 快递策略内部服务。
|
||
*
|
||
* 为快递匹配链路提供策略查询能力,内置缓存加速。
|
||
* 不对外暴露 method 路由,仅供其他 service 内部调用。
|
||
*/
|
||
class ExpressPolicyService extends Service {
|
||
// -------------------- 缓存键 --------------------
|
||
|
||
/**
|
||
* 仓库维度策略列表缓存键。
|
||
* @param {number} warehouseId 仓库 ID
|
||
* @return {string} 缓存键
|
||
*/
|
||
getWarehousePolicyCacheKey(warehouseId) {
|
||
return `express_policy:warehouse:${warehouseId}`;
|
||
}
|
||
|
||
/**
|
||
* 仓库维度策略缓存过期秒数(默认 300s)。
|
||
* @return {number} 过期秒数
|
||
*/
|
||
getWarehousePolicyCacheTTL() {
|
||
return 300;
|
||
}
|
||
|
||
// -------------------- 缓存清理 --------------------
|
||
|
||
/**
|
||
* 清理指定仓库的策略缓存。
|
||
* @param {number} warehouseId 仓库 ID
|
||
* @return {Promise<void>}
|
||
*/
|
||
async clearWarehousePolicyCache(warehouseId) {
|
||
const cacheKey = this.getWarehousePolicyCacheKey(warehouseId);
|
||
if (this.app && typeof this.app.delCacheAsync === 'function') {
|
||
await this.app.delCacheAsync(cacheKey);
|
||
}
|
||
}
|
||
|
||
// -------------------- 数据查询 --------------------
|
||
|
||
/**
|
||
* 从数据库查询仓库下所有启用的策略,按优先级降序排列。
|
||
* @param {number} warehouseId 仓库 ID
|
||
* @return {Promise<Array<Object>>} 策略列表(plain object)
|
||
*/
|
||
async fetchWarehousePoliciesFromDB(warehouseId) {
|
||
const { ctx } = this;
|
||
|
||
try {
|
||
const rows = await ctx.model.StoreExpressBindingPolicy.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
is_enabled: 1,
|
||
deleted_at: null,
|
||
},
|
||
order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||
raw: true,
|
||
});
|
||
return rows;
|
||
} catch (error) {
|
||
if (ctx.logger && typeof ctx.logger.warn === 'function') {
|
||
ctx.logger.warn('[ExpressPolicyDBError]', error.message, { warehouseId });
|
||
}
|
||
return [];
|
||
}
|
||
}
|
||
|
||
// -------------------- 对外方法 --------------------
|
||
|
||
/**
|
||
* 获取仓库策略目录(缓存优先)。
|
||
*
|
||
* 查询链路:缓存命中 → 直接返回;缓存未命中 → 查库 → 写缓存 → 返回。
|
||
*
|
||
* @param {number} warehouseId 仓库 ID
|
||
* @param {Object} [options] 选项
|
||
* @param {boolean} [options.forceRefresh=false] 是否强制刷新缓存
|
||
* @return {Promise<Array<Object>>} 策略列表(按 priority DESC 排序)
|
||
*/
|
||
async getWarehousePolicies(warehouseId, options = {}) {
|
||
const { app } = this;
|
||
const { forceRefresh = false } = options;
|
||
|
||
if (!Number.isFinite(Number(warehouseId)) || Number(warehouseId) <= 0) {
|
||
return [];
|
||
}
|
||
|
||
const cacheKey = this.getWarehousePolicyCacheKey(warehouseId);
|
||
const ttl = this.getWarehousePolicyCacheTTL();
|
||
|
||
// 1) 读缓存(非强制刷新时)
|
||
if (!forceRefresh && app && typeof app.getCacheAsync === 'function') {
|
||
try {
|
||
const cached = await app.getCacheAsync(cacheKey);
|
||
if (cached && Array.isArray(cached) && cached.length > 0) {
|
||
return cached;
|
||
}
|
||
} catch (error) {
|
||
if (app.logger && typeof app.logger.warn === 'function') {
|
||
app.logger.warn('[ExpressPolicyCacheReadError]', error.message, { warehouseId });
|
||
}
|
||
}
|
||
}
|
||
|
||
// 2) 查库
|
||
const policies = await this.fetchWarehousePoliciesFromDB(warehouseId);
|
||
|
||
// 3) 写缓存
|
||
if (app && typeof app.setCacheAsync === 'function') {
|
||
try {
|
||
await app.setCacheAsync(cacheKey, policies, ttl);
|
||
} catch (error) {
|
||
if (app.logger && typeof app.logger.warn === 'function') {
|
||
app.logger.warn('[ExpressPolicyCacheWriteError]', error.message, { warehouseId });
|
||
}
|
||
}
|
||
}
|
||
|
||
return policies;
|
||
}
|
||
|
||
// -------------------- 策略匹配 --------------------
|
||
|
||
/**
|
||
* 检查 policy 中数组字段的任意值是否命中目标字符串(子串包含匹配)。
|
||
* @param {Array<string>|null} policyArray 策略中的数组字段
|
||
* @param {string} target 目标字符串(如地址、店铺名称)
|
||
* @return {boolean} 是否命中
|
||
*/
|
||
_matchAnyToken(policyArray, target) {
|
||
if (!Array.isArray(policyArray) || policyArray.length === 0) {
|
||
return true; // 未限定 = 不限制
|
||
}
|
||
const normalizedTarget = String(target || '').trim();
|
||
if (!normalizedTarget) {
|
||
return false;
|
||
}
|
||
return policyArray.some(token => {
|
||
const t = String(token || '').trim();
|
||
return t && normalizedTarget.includes(t);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 检查两个数组是否有交集。
|
||
* @param {Array<*>|null} policyArray 策略中的数组字段
|
||
* @param {Array<*>|null} inputArray 传入的数组
|
||
* @return {boolean} 是否有交集
|
||
*/
|
||
_matchAnyIntersect(policyArray, inputArray) {
|
||
if (!Array.isArray(policyArray) || policyArray.length === 0) {
|
||
return true; // 未限定 = 不限制
|
||
}
|
||
if (!Array.isArray(inputArray) || inputArray.length === 0) {
|
||
return false;
|
||
}
|
||
const policySet = new Set(policyArray.map(v => Number(v)));
|
||
return inputArray.some(v => policySet.has(Number(v)));
|
||
}
|
||
|
||
/**
|
||
* 检查传入值是否在策略数组范围内。
|
||
* @param {Array<*>|null} policyArray 策略中的数组字段
|
||
* @param {number} value 传入值
|
||
* @return {boolean} 是否命中
|
||
*/
|
||
_matchValueInArray(policyArray, value) {
|
||
if (!Array.isArray(policyArray) || policyArray.length === 0) {
|
||
return true; // 未限定 = 不限制
|
||
}
|
||
return policyArray.some(v => Number(v) === Number(value));
|
||
}
|
||
|
||
/**
|
||
* 按策略优先级漏斗筛选,返回命中策略的快递编码与重量段类型。
|
||
*
|
||
* 筛选顺序(按 priority DESC,同 priority 按 updated_at DESC):
|
||
* 1. store_ids —— 传入货主ID是否在策略限定范围内(NULL=不限)
|
||
* 2. shop_name —— 自定义店铺名称子串匹配(任意一个命中即通过)
|
||
* 3. prohibited_type_id —— 违禁品类型ID数组交集(有交集即命中)
|
||
* 4. regions —— 地址包含任意限定地区即命中
|
||
* 5. exclude_regions —— 地址包含任意排除地区则跳过该策略
|
||
* 6. min_weight_g / max_weight_g —— 重量区间
|
||
*
|
||
* @param {number} warehouseId 仓库 ID
|
||
* @param {Object} params 匹配参数
|
||
* @param {number} [params.storeId] 货主 ID
|
||
* @param {string} [params.customShopName] 自定义店铺名称
|
||
* @param {Array<number>} [params.prohibitedTypeIds] 商品违禁品类型 ID 数组
|
||
* @param {string} [params.address] 省市区详细地址(单个字符串)
|
||
* @param {number} [params.weight] 重量(克)
|
||
* @return {Promise<{expressCode: string|null, weightType: number|null}>}
|
||
*/
|
||
async matchPolicy(warehouseId, params = {}) {
|
||
const {
|
||
storeId,
|
||
customShopName,
|
||
prohibitedTypeIds,
|
||
address,
|
||
weight,
|
||
} = params;
|
||
|
||
const policies = await this.getWarehousePolicies(warehouseId);
|
||
if (!Array.isArray(policies) || policies.length === 0) {
|
||
return { expressCode: null, weightType: null };
|
||
}
|
||
|
||
for (const policy of policies) {
|
||
// 1) store_ids — 未限定(NULL)视为不限;否则传入 storeId 必须在范围内
|
||
if (!this._matchValueInArray(policy.store_ids, storeId)) {
|
||
continue;
|
||
}
|
||
|
||
// 2) shop_name — 子串包含匹配
|
||
if (!this._matchAnyToken(policy.shop_name, customShopName)) {
|
||
continue;
|
||
}
|
||
|
||
// 3) prohibited_type_id — 数组交集
|
||
if (!this._matchAnyIntersect(policy.prohibited_type_id, prohibitedTypeIds)) {
|
||
continue;
|
||
}
|
||
|
||
// 4) regions — 地址包含任意限定地区
|
||
if (!this._matchAnyToken(policy.regions, address)) {
|
||
continue;
|
||
}
|
||
|
||
// 5) exclude_regions — 地址包含任意排除地区则跳过
|
||
if (Array.isArray(policy.exclude_regions) && policy.exclude_regions.length > 0) {
|
||
const excluded = policy.exclude_regions.some(token => {
|
||
const t = String(token || '').trim();
|
||
return t && String(address || '').includes(t);
|
||
});
|
||
if (excluded) {
|
||
continue;
|
||
}
|
||
}
|
||
|
||
// 6) 重量区间
|
||
const weightNum = Number(weight);
|
||
if (Number.isFinite(weightNum)) {
|
||
if (policy.min_weight_g !== null && policy.min_weight_g !== undefined) {
|
||
if (weightNum < Number(policy.min_weight_g)) {
|
||
continue;
|
||
}
|
||
}
|
||
if (policy.max_weight_g !== null && policy.max_weight_g !== undefined) {
|
||
if (weightNum > Number(policy.max_weight_g)) {
|
||
continue;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 全部通过 → 命中
|
||
return {
|
||
expressCode: policy.express_code || null,
|
||
weightType: policy.weight_type !== undefined ? policy.weight_type : 0,
|
||
policyName: policy.custom_name || null,
|
||
policyId: policy.id || null,
|
||
};
|
||
}
|
||
|
||
// 无命中
|
||
return { expressCode: null, weightType: null };
|
||
}
|
||
}
|
||
|
||
module.exports = ExpressPolicyService;
|