'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} */ 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>} 策略列表(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>} 策略列表(按 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|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)); } /** * 判断策略是否为"纯货主维度"策略: * store_ids 非空,且 shop_name / prohibited_type_id / regions / exclude_regions / 重量区间全部未限定。 * * @param {Object} policy 策略行 * @return {boolean} 是否为纯货主策略 */ _isStoreOnlyPolicy(policy = {}) { const asArray = v => (Array.isArray(v) ? v : []); if (asArray(policy.store_ids).length === 0) { return false; } const hasOtherDimension = asArray(policy.shop_name).length > 0 || asArray(policy.prohibited_type_id).length > 0 || asArray(policy.regions).length > 0 || asArray(policy.exclude_regions).length > 0 || (policy.min_weight_g !== null && policy.min_weight_g !== undefined) || (policy.max_weight_g !== null && policy.max_weight_g !== undefined); return !hasOtherDimension; } /** * 按策略优先级漏斗筛选,返回命中策略的快递编码与重量段类型。 * * 筛选顺序(按 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} [params.prohibitedTypeIds] 商品违禁品类型 ID 数组 * @param {string} [params.address] 省市区详细地址(单个字符串) * @param {number} [params.weight] 重量(克) * @param {Object} [options] 匹配选项 * @param {boolean} [options.onlyStoreDimension=false] 仅匹配"纯货主维度"策略(store_ids 非空且其它维度全空) * @return {Promise<{expressCode: string|null, weightType: number|null}>} 命中策略的快递编码与重量段类型,未命中时 expressCode 为 null */ async matchPolicy(warehouseId, params = {}, options = {}) { const { storeId, customShopName, prohibitedTypeIds, address, weight, } = params; const { onlyStoreDimension = false } = options; const policies = await this.getWarehousePolicies(warehouseId); if (!Array.isArray(policies) || policies.length === 0) { return { expressCode: null, weightType: null }; } for (const policy of policies) { // 0) 维度白名单:onlyStoreDimension 开启时跳过非纯货主策略 if (onlyStoreDimension && !this._isStoreOnlyPolicy(policy)) { continue; } // 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;