From 0b781a7e7097cd8ea147e52f011412657778a1fc Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 4 Aug 2026 08:18:43 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=BA=97=E9=93=BA=E5=BF=AB=E9=80=92?= =?UTF-8?q?=E7=BB=91=E5=AE=9A=E7=AD=96=E7=95=A5=E6=A8=A1=E5=9D=97=20+=20?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=88=9B=E5=BB=BA=E9=93=BE=E8=B7=AF=E9=9B=86?= =?UTF-8?q?=E6=88=90=20+=20=E8=BF=90=E5=8D=95=E5=8F=B7=E5=88=86=E9=85=8D?= =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 【新增模块】 - 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均执行) --- app/dict/businessDict.js | 1 + app/model/store_express_binding_policy.js | 144 ++++ .../store_express_binding_policy.js | 210 ++++++ app/service/systems/delivery_order.js | 118 ++- app/service/systems/express.js | 63 +- app/service/systems/express_policy.js | 275 +++++++ .../systems/store_express_binding_policy.js | 696 ++++++++++++++++++ .../store-express-binding-policy-design.md | 138 ++++ ...create-wms-store-express-binding-policy.js | 129 ++++ ...emove-store-shop-id-from-binding-policy.js | 40 + ...dd-prohibited-type-id-to-binding-policy.js | 18 + ...e-match-condition-with-provinces-cities.js | 31 + ...0000-add-weight-range-to-binding-policy.js | 25 + ...70500-add-weight-type-to-binding-policy.js | 18 + ...0260803171000-make-weight-type-required.js | 23 + ...90000-merge-provinces-cities-to-regions.js | 30 + .../20260804091000-add-exclude-regions.js | 18 + .../20260804100000-add-shop-name.js | 18 + .../20260804101000-add-store-ids.js | 18 + .../20260804110000-change-text-to-json.js | 19 + ...0260804120000-change-prohibited-to-json.js | 21 + methods/system.json | 489 +++++++++++- 22 files changed, 2519 insertions(+), 23 deletions(-) create mode 100644 app/model/store_express_binding_policy.js create mode 100644 app/service/systemMethods/store_express_binding_policy.js create mode 100644 app/service/systems/express_policy.js create mode 100644 app/service/systems/store_express_binding_policy.js create mode 100644 database/designs/store-express-binding-policy-design.md create mode 100644 database/migrations/20260803150000-create-wms-store-express-binding-policy.js create mode 100644 database/migrations/20260803160000-remove-store-shop-id-from-binding-policy.js create mode 100644 database/migrations/20260803163000-add-prohibited-type-id-to-binding-policy.js create mode 100644 database/migrations/20260803164500-replace-match-condition-with-provinces-cities.js create mode 100644 database/migrations/20260803170000-add-weight-range-to-binding-policy.js create mode 100644 database/migrations/20260803170500-add-weight-type-to-binding-policy.js create mode 100644 database/migrations/20260803171000-make-weight-type-required.js create mode 100644 database/migrations/20260804090000-merge-provinces-cities-to-regions.js create mode 100644 database/migrations/20260804091000-add-exclude-regions.js create mode 100644 database/migrations/20260804100000-add-shop-name.js create mode 100644 database/migrations/20260804101000-add-store-ids.js create mode 100644 database/migrations/20260804110000-change-text-to-json.js create mode 100644 database/migrations/20260804120000-change-prohibited-to-json.js diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index c6c363f..a9004a9 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -68,6 +68,7 @@ module.exports = { ORDER_INTERCEPT_CONFIRM: '确认拦截', ORDER_PLATFORM_FALLBACK: '平台降级', ORDER_EXPRESS_FALLBACK: '快递降级', + ORDER_EXPRESS_POLICY_MATCH: '策略命中', ORDER_WAVE_UPDATE: '更新波次', ORDER_WAVE_ASSIGN: '分配波次', ORDER_WAVE_REMOVE: '移出波次', diff --git a/app/model/store_express_binding_policy.js b/app/model/store_express_binding_policy.js new file mode 100644 index 0000000..0f53969 --- /dev/null +++ b/app/model/store_express_binding_policy.js @@ -0,0 +1,144 @@ +'use strict'; + +/** + * 订单自定义店铺-快递绑定策略模型。 + * + * 支持在仓库维度下,为用户自定义店铺标签配置快递绑定策略, + * 按优先级匹配,可附加商品、地区、重量等条件。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, TINYINT, DATE, TEXT, JSON: JSON_TYPE } = app.Sequelize; + + const StoreExpressBindingPolicy = app.model.define('store_express_binding_policy', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '仓库ID,策略所属仓库', + }, + custom_name: { + type: STRING(100), + allowNull: false, + comment: '策略名称,便于人工识别', + }, + shop_name: { + type: JSON_TYPE, + allowNull: true, + comment: '包含店铺名称,字符串数组,如["旗舰店","奥莱店"],NULL=不限制', + }, + store_ids: { + type: JSON_TYPE, + allowNull: true, + comment: '限定货主ID,数字数组,如[1000000,1000001],NULL=不限制', + }, + express_code: { + type: STRING(50), + allowNull: false, + comment: '绑定的快递编码(wms_express.code)', + }, + priority: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先匹配', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + validate: { + isIn: { + args: [[ 0, 1 ]], + msg: '启用状态不合法,0=停用,1=启用', + }, + }, + comment: '是否启用:0=停用,1=启用', + }, + regions: { + type: JSON_TYPE, + allowNull: true, + comment: '限定地区,字符串数组,如["广东省","广州市"],NULL=不限制', + }, + exclude_regions: { + type: JSON_TYPE, + allowNull: true, + comment: '排除地区,字符串数组,如["新疆维吾尔自治区"],NULL=不排除', + }, + min_weight_g: { + type: INTEGER, + allowNull: true, + comment: '最小重量(克),NULL=不限制', + }, + max_weight_g: { + type: INTEGER, + allowNull: true, + comment: '最大重量(克),NULL=不限制', + }, + weight_type: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + validate: { isIn: { args: [[ 0, 1, 2, 3 ]], msg: '重量类型不合法,0=常规/1=轻货/2=重货/3=冷链' } }, + comment: '重量段类型:0=常规/1=轻货/2=重货/3=冷链', + }, + prohibited_type_id: { + type: JSON_TYPE, + allowNull: true, + comment: '违禁品类型ID数组(关联 wms_prohibited_type.id),如[1,2],NULL=不限制违禁品', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注说明', + }, + creator_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '创建人账户ID(accounts.id)', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_store_express_binding_policy', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '订单自定义店铺-快递绑定策略表', + indexes: [ + { + name: 'idx_warehouse_enabled', + fields: [ 'warehouse_id', 'is_enabled', 'deleted_at' ], + }, + { + name: 'idx_warehouse_express', + fields: [ 'warehouse_id', 'express_code', 'deleted_at' ], + }, + ], + }); + + return StoreExpressBindingPolicy; +}; diff --git a/app/service/systemMethods/store_express_binding_policy.js b/app/service/systemMethods/store_express_binding_policy.js new file mode 100644 index 0000000..b97258e --- /dev/null +++ b/app/service/systemMethods/store_express_binding_policy.js @@ -0,0 +1,210 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 店铺-快递绑定策略 methods 出口。 + * + * 支持以下 method 调用(通过 /system?method=storeExpressBindingPolicy.xxx): + * - storeExpressBindingPolicy.list 分页查询策略列表 + * - storeExpressBindingPolicy.add 新增策略 + * - storeExpressBindingPolicy.edit 编辑策略 + * - storeExpressBindingPolicy.del 软删除策略 + */ +class StoreExpressBindingPolicyMethodService extends MainService { + /** + * 初始化鉴权配置。 + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = '*'; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用业务服务。 + * @param {string} methodName 业务方法名 + * @param {Object} data 请求参数 + * @param {string} fallbackMessage 默认错误文案 + * @return {Promise} methods 标准返回 + */ + async callSystem(methodName, data, fallbackMessage) { + const { service } = this; + + try { + const result = await service.systems.storeExpressBindingPolicy[methodName](data); + return this.success('ok', { data: result, code: 200 }); + } catch (error) { + return this.fail(error.message || fallbackMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * storeExpressBindingPolicy.list:分页查询策略列表。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 查询结果 + */ + async list(data = {}) { + const payload = { + ...(data && typeof data === 'object' ? data : {}), + }; + + this.prepareWhereContext(payload, { + specialFieldMap: this.service.systems.storeExpressBindingPolicy.getListWhereSpecialFieldMap(), + }); + + return await this.callSystem('list', payload, '查询策略列表失败'); + } + + /** + * storeExpressBindingPolicy.add:新增策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 新增结果 + */ + async add(data = {}) { + const { + custom_name: customName, + customName: customNameCamel, + express_code: expressCode, + expressCode: expressCodeCamel, + priority, + is_enabled: isEnabled, + isEnabled: isEnabledCamel, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeId, + prohibitedTypeId: prohibitedTypeIdCamel, + remark, + creator_id: creatorId, + creatorId: creatorIdCamel, + } = data || {}; + + return await this.callSystem('add', { + custom_name: customName !== undefined ? customName : customNameCamel, + express_code: expressCode !== undefined ? expressCode : expressCodeCamel, + priority, + is_enabled: isEnabled !== undefined ? isEnabled : isEnabledCamel, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeId !== undefined ? prohibitedTypeId : prohibitedTypeIdCamel, + remark, + creator_id: creatorId !== undefined ? creatorId : creatorIdCamel, + }, '新增策略失败'); + } + + /** + * storeExpressBindingPolicy.edit:编辑策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 编辑结果 + */ + async edit(data = {}) { + const { + id, + policy_id: policyId, + policyId: policyIdCamel, + custom_name: customName, + customName: customNameCamel, + express_code: expressCode, + expressCode: expressCodeCamel, + priority, + is_enabled: isEnabled, + isEnabled: isEnabledCamel, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeId, + prohibitedTypeId: prohibitedTypeIdCamel, + remark, + creator_id: creatorId, + creatorId: creatorIdCamel, + } = data || {}; + + const payload = { + id: id !== undefined ? id : (policyId !== undefined ? policyId : policyIdCamel), + }; + + if (customName !== undefined || customNameCamel !== undefined) { + payload.custom_name = customName !== undefined ? customName : customNameCamel; + } + if (expressCode !== undefined || expressCodeCamel !== undefined) { + payload.express_code = expressCode !== undefined ? expressCode : expressCodeCamel; + } + if (priority !== undefined) { + payload.priority = priority; + } + if (isEnabled !== undefined || isEnabledCamel !== undefined) { + payload.is_enabled = isEnabled !== undefined ? isEnabled : isEnabledCamel; + } + if (regions !== undefined) { + payload.regions = regions; + } + if (shopName !== undefined) { + payload.shop_name = shopName; + } + if (storeIds !== undefined) { + payload.store_ids = storeIds; + } + if (excludeRegions !== undefined) { + payload.exclude_regions = excludeRegions; + } + if (minWeightG !== undefined) { + payload.min_weight_g = minWeightG; + } + if (maxWeightG !== undefined) { + payload.max_weight_g = maxWeightG; + } + if (weightType !== undefined) { + payload.weight_type = weightType; + } + if (prohibitedTypeId !== undefined || prohibitedTypeIdCamel !== undefined) { + payload.prohibited_type_id = prohibitedTypeId !== undefined ? prohibitedTypeId : prohibitedTypeIdCamel; + } + if (remark !== undefined) { + payload.remark = remark; + } + if (creatorId !== undefined || creatorIdCamel !== undefined) { + payload.creator_id = creatorId !== undefined ? creatorId : creatorIdCamel; + } + + return await this.callSystem('edit', payload, '编辑策略失败'); + } + + /** + * storeExpressBindingPolicy.del:软删除策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 删除结果 + */ + async del(data = {}) { + const { + id, + policy_id: policyId, + policyId: policyIdCamel, + } = data || {}; + + return await this.callSystem('del', { + id: id !== undefined ? id : (policyId !== undefined ? policyId : policyIdCamel), + }, '删除策略失败'); + } +} + +module.exports = StoreExpressBindingPolicyMethodService; diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index b545307..45f954d 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -22,6 +22,7 @@ const ORDER_OPERATION_CODES = Object.freeze({ CREATE: 'ORDER_CREATE', PLATFORM_FALLBACK: 'ORDER_PLATFORM_FALLBACK', EXPRESS_FALLBACK: 'ORDER_EXPRESS_FALLBACK', + EXPRESS_POLICY_MATCH: 'ORDER_EXPRESS_POLICY_MATCH', }); const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600; @@ -514,11 +515,12 @@ class DeliveryOrderService extends Service { || '' ).trim(); - const fallbackExpress = this.findCodeOption(expressList, defaultCode); + const fallbackExpress = this.findCodeOption(expressList, defaultCode) + || this.findCodeOption(expressList, DEFAULT_STORE_SUBJECT_CONFIG.default_express_code); const fallbackLogisticsCode = String( - fallbackExpress && (fallbackExpress.code || fallbackExpress.value || fallbackExpress.express_code || defaultCode) + fallbackExpress && (fallbackExpress.code || fallbackExpress.value || fallbackExpress.express_code || defaultCode || DEFAULT_STORE_SUBJECT_CONFIG.default_express_code) || defaultCode - || '' + || DEFAULT_STORE_SUBJECT_CONFIG.default_express_code ).trim(); const fallbackLogisticsName = this.getOptionName(fallbackExpress); const explicitEnableExternalExpressCode = info && Object.prototype.hasOwnProperty.call(info, 'enableExternalExpressCode') @@ -536,6 +538,7 @@ class DeliveryOrderService extends Service { logisticsName: fallbackLogisticsName, sysLogisticsCode: fallbackLogisticsCode, sysLogisticsName: fallbackLogisticsName, + weightType: 0, }; } @@ -554,6 +557,7 @@ class DeliveryOrderService extends Service { logisticsName: String(expressSetting.name || '').trim(), sysLogisticsCode: matchedSysLogisticsCode, sysLogisticsName: matchedSysLogisticsName, + weightType: 0, }; } @@ -570,6 +574,7 @@ class DeliveryOrderService extends Service { logisticsName: matchedLogisticsName, sysLogisticsCode: matchedLogisticsCode, sysLogisticsName: matchedLogisticsName, + weightType: 0, }; } if (fallbackExpress) { @@ -592,6 +597,7 @@ class DeliveryOrderService extends Service { logisticsName: fallbackLogisticsName, sysLogisticsCode: fallbackLogisticsCode, sysLogisticsName: fallbackLogisticsName, + weightType: 0, }; } @@ -608,6 +614,7 @@ class DeliveryOrderService extends Service { logisticsName: fallbackLogisticsName, sysLogisticsCode: fallbackLogisticsCode, sysLogisticsName: fallbackLogisticsName, + weightType: 0, }; } @@ -728,6 +735,110 @@ class DeliveryOrderService extends Service { updated_at: new Date(), }; + // ===== 快递绑定策略漏斗匹配(items 处理后 weight 可用) ===== + try { + const receiverInfo = deliveryOrder.receiverInfo; + const shopNick = deliveryOrder.shopNick; + const hasEnoughData = shopNick || (receiverInfo && (receiverInfo.province || receiverInfo.city)); + + if (hasEnoughData) { + const address = [ + receiverInfo?.province || '', + receiverInfo?.city || '', + receiverInfo?.area || '', + receiverInfo?.town || '', + receiverInfo?.detail_address || '', + ].join('').trim(); + + const matchResult = await ctx.service.systems.expressPolicy.matchPolicy( + info.warehouseId, + { + storeId: info.storeId, + customShopName: shopNick || '', + address: address || '', + weight: itemsInfo.total_weight || null, + prohibitedTypeIds: null, // TODO: 后续从商品 StockWarehouse.prohibited_id 聚合 + } + ); + + if (matchResult && matchResult.expressCode) { + const expressList = await ctx.service.systems.express.getExpressList(); + const matchedExpress = expressList.find( + item => item && String(item.code || item.value || '').trim() === String(matchResult.expressCode).trim() + ); + + let logisticsCode; + let logisticsName; + let sysLogisticsCode; + let sysLogisticsName; + + if (matchedExpress) { + if (matchedExpress.is_system_setting) { + // 自定义映射:sys 写映射的系统快递,logistics 写自定义编码 + sysLogisticsCode = String(matchedExpress.express_code || '').trim(); + const sysItem = expressList.find( + item => item && !item.is_system_setting && String(item.code || item.value || '').trim() === sysLogisticsCode + ); + sysLogisticsName = sysItem ? String(sysItem.name || sysItem.label || sysLogisticsCode).trim() : sysLogisticsCode; + logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim(); + logisticsName = String(matchedExpress.alias || matchedExpress.name || logisticsCode).trim(); + } else { + // 系统快递:4 字段一致 + logisticsCode = String(matchedExpress.code || matchedExpress.value || matchResult.expressCode).trim(); + logisticsName = String(matchedExpress.name || matchedExpress.label || logisticsCode).trim(); + sysLogisticsCode = logisticsCode; + sysLogisticsName = logisticsName; + } + } else { + // 未在列表中,fallback + logisticsCode = String(matchResult.expressCode).trim(); + logisticsName = logisticsCode; + sysLogisticsCode = logisticsCode; + sysLogisticsName = logisticsCode; + } + + stats.logistics_code = logisticsCode; + stats.logistics_name = logisticsName; + stats.sys_logistics_code = sysLogisticsCode; + stats.sys_logistics_name = sysLogisticsName; + stats.weight_type = matchResult.weightType; + stats.updated_at = new Date(); + + // 写入操作日志:命中了哪条策略 + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.EXPRESS_POLICY_MATCH, + `快递策略命中: ${matchResult.policyName || '未知'}(${matchResult.policyId || '?'}) → ${sysLogisticsName || sysLogisticsCode}` + ); + + ctx.logger.info('[ExpressPolicyMatch] 策略命中(延迟匹配)', { + orderId, + orderCode: deliveryOrder.deliveryOrderCode, + logisticsCode, + sysLogisticsCode, + weightType: matchResult.weightType, + policyName: matchResult.policyName, + policyId: matchResult.policyId, + totalWeight: itemsInfo.total_weight, + }); + } else if (hasEnoughData) { + // 策略未命中:记快递降级日志(取已落库的初始快递值) + const fallbackCode = orderData.sys_logistics_code || orderData.logistics_code; + const fallbackName = orderData.sys_logistics_name || orderData.logistics_name; + this.appendOrderOperationLog( + operationLogs, + ORDER_OPERATION_CODES.EXPRESS_FALLBACK, + `未命中快递策略,使用默认快递: ${fallbackName || fallbackCode}` + ); + } + } + } catch (policyErr) { + ctx.logger.warn('[ExpressPolicyMatch] 策略匹配异常,跳过', { + orderId, + error: policyErr.message, + }); + } + await DeliveryModel.update( stats, { @@ -1104,6 +1215,7 @@ class DeliveryOrderService extends Service { sys_logistics_code: expressSnapshot.sysLogisticsCode, sys_logistics_name: expressSnapshot.sysLogisticsName, express_code: expressCode || '', + weight_type: expressSnapshot.weightType ?? 0, logistics_area_code: logisticsAreaCode || '', is_urgency: isUrgency || 'N', invoice_flag: invoiceFlag || 'N', diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 075893a..b167287 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -1797,6 +1797,8 @@ class ExpressService extends Service { sys_platform_code: sysPlatformCode, print_platform_code: printPlatformCode, logistics_code: logisticsCode, + sys_logistics_code: String(order.sys_logistics_code || '').trim(), + weight_type: order.weight_type !== undefined ? Number(order.weight_type) : 0, sys_platform_name: order.sys_platform_name || '', logistics_name: order.logistics_name || '', store_id: order.store_id || 0, @@ -1854,10 +1856,16 @@ class ExpressService extends Service { && groupedOrder.options && groupedOrder.options.logistics_code ); - - if (!logisticsCode) { - return null; - } + const sysLogisticsCode = normalizeCode( + groupedOrder + && groupedOrder.options + && groupedOrder.options.sys_logistics_code + ); + const orderWeightType = Number( + groupedOrder + && groupedOrder.options + && groupedOrder.options.weight_type + ) || 0; const platformCode = normalizeCode( groupedOrder @@ -1871,27 +1879,44 @@ class ExpressService extends Service { && matchedPlatform.print_platform_code ); - for (const item of Array.isArray(interfaceList) ? interfaceList : []) { - if (!item || typeof item !== 'object') { - continue; - } + const enabledList = (Array.isArray(interfaceList) ? interfaceList : []) + .filter(item => item && typeof item === 'object' && Number(item.is_enabled) === 1); - // 停用的快递接口不允许分配运单号 - if (Number(item.is_enabled) !== 1) { - continue; + // 通用匹配函数 + const matchByCode = (item, targetCode, useSysCode = true) => { + if (!targetCode) return false; + const candidateCodes = [ normalizeCode(item.express_code) ]; + if (useSysCode) { + candidateCodes.push(normalizeCode(item.sys_express_code)); } - - const candidateCodes = [ - normalizeCode(item.sys_express_code), - normalizeCode(item.express_code), - ]; const expressMap = item.express && typeof item.express === 'object' ? item.express : null; if (expressMap && platformCode) { candidateCodes.push(normalizeCode(expressMap[platformCode])); } + if (!candidateCodes.some(code => code && code === targetCode)) return false; - if (candidateCodes.some(code => code && code === logisticsCode)) { - return item; + const itemWeightType = item.weight_type !== null && item.weight_type !== undefined + ? Number(item.weight_type) : null; + if (itemWeightType !== null && itemWeightType !== orderWeightType) return false; + + return true; + }; + + // 第一步:logistics_code 仅匹配 express_code + 平台码(不用 sys_express_code) + if (logisticsCode) { + for (const item of enabledList) { + if (matchByCode(item, logisticsCode, false)) { + return item; + } + } + } + + // 第二步:sys_logistics_code 匹配 sys_express_code + express_code(全放开) + if (sysLogisticsCode) { + for (const item of enabledList) { + if (matchByCode(item, sysLogisticsCode, true)) { + return item; + } } } @@ -2635,6 +2660,8 @@ class ExpressService extends Service { printPlatformCode: groupedOrder.options.print_platform_code, expressInterfacePlatformCode, logisticsCode: groupedOrder.options.logistics_code, + sysLogisticsCode: groupedOrder.options.sys_logistics_code, + weightType: groupedOrder.options.weight_type, matchedPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.code, requestPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.request_platform_code, hasExpressInterface: Boolean(expressInterface), diff --git a/app/service/systems/express_policy.js b/app/service/systems/express_policy.js new file mode 100644 index 0000000..0df2b1f --- /dev/null +++ b/app/service/systems/express_policy.js @@ -0,0 +1,275 @@ +'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)); + } + + /** + * 按策略优先级漏斗筛选,返回命中策略的快递编码与重量段类型。 + * + * 筛选顺序(按 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] 重量(克) + * @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; diff --git a/app/service/systems/store_express_binding_policy.js b/app/service/systems/store_express_binding_policy.js new file mode 100644 index 0000000..49e5104 --- /dev/null +++ b/app/service/systems/store_express_binding_policy.js @@ -0,0 +1,696 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 订单自定义店铺-快递绑定策略业务服务。 + */ +class StoreExpressBindingPolicyService extends Service { + /** + * 获取当前仓库 ID。 + * @return {number} 仓库 ID + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw this.createError('未识别到当前仓库', 400); + } + return warehouseId; + } + + /** + * 创建业务错误。 + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 规范化字符串参数。 + * @param {*} value 原始值 + * @param {string} fieldName 字段名 + * @param {Object} [options={}] 选项 + * @return {string|null} 规范化结果 + */ + normalizeText(value, fieldName, options = {}) { + const { required = false, maxLength = 255 } = options; + if (value === undefined || value === null) { + if (required) throw this.createError(`${fieldName} 不能为空`, 400); + return null; + } + const normalized = String(value).trim(); + if (!normalized) { + if (required) throw this.createError(`${fieldName} 不能为空`, 400); + return null; + } + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + /** + * 规范化整数参数。 + * @param {*} value 原始值 + * @param {string} fieldName 字段名 + * @param {Object} [options={}] 选项 + * @return {number|null} 规范化结果 + */ + normalizeInteger(value, fieldName, options = {}) { + const { required = false, min = null } = options; + if (value === undefined || value === null || value === '') { + if (required) throw this.createError(`${fieldName} 不能为空`, 400); + return null; + } + const normalized = Number(value); + if (!Number.isInteger(normalized)) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (min !== null && normalized < min) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return normalized; + } + + /** + * 规范化重量段类型。 + * @param {*} value 原始值 + * @return {number|null} NULL 或 0/1/2/3 + */ + normalizeWeightType(value) { + if (value === undefined || value === null || value === '') return 0; + const v = Number(value); + if (![ 0, 1, 2, 3 ].includes(v)) throw this.createError('weight_type 不合法,仅支持 0/1/2/3(常规/轻货/重货/冷链)', 400); + return v; + } + + /** + * 校验快递编码是否存在。 + * @param {string} expressCode 快递编码 + * @return {Promise} 标准化快递编码 + */ + normalizeJsonArray(value, fieldName) { + if (value === undefined || value === null || value === '') return null; + if (Array.isArray(value)) return value.length > 0 ? value : null; + if (typeof value === 'string') { + try { const parsed = JSON.parse(value); if (Array.isArray(parsed)) return parsed.length > 0 ? parsed : null; } catch (e) {} + } + throw this.createError(fieldName + ' 必须是字符串数组', 400); + } + + async ensureExpressExists(expressCode) { + const { ctx } = this; + const normalizedCode = this.normalizeText(expressCode, 'express_code', { + required: true, + maxLength: 50, + }); + + // 使用合并后的快递列表(含系统快递 + 仓库自定义映射) + const expressList = await ctx.service.systems.express.getExpressList(); + const found = Array.isArray(expressList) + ? expressList.find(item => item && String(item.code || item.value || '').trim() === normalizedCode) + : null; + + if (!found) { + throw this.createError(`快递编码 "${normalizedCode}" 不存在`, 400); + } + + return normalizedCode; + } + + /** + * 获取列表字段过滤映射。 + * @return {Object} specialFieldMap + */ + getListWhereSpecialFieldMap() { + return { + id: { field: 'id' }, + custom_name: { field: 'custom_name' }, + shop_name: { field: 'shop_name' }, + store_ids: { field: 'store_ids' }, + express_code: { field: 'express_code' }, + priority: { field: 'priority' }, + is_enabled: { field: 'is_enabled' }, + prohibited_type_id: { field: 'prohibited_type_id' }, + regions: { field: 'regions' }, + exclude_regions: { field: 'exclude_regions' }, + min_weight_g: { field: 'min_weight_g' }, + max_weight_g: { field: 'max_weight_g' }, + weight_type: { field: 'weight_type' }, + creator_id: { field: 'creator_id' }, + quickWhere: { bucket: 'quick' }, + }; + } + + /** + * 构建列表查询条件。 + * @param {Object} [data={}] 请求参数 + * @return {Object} where 条件 + */ + buildListWhere(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const parsedResult = ctx.whereParsed || { + dynamicConditions: [], + rawConditionsByField: {}, + }; + const whereAndConditions = [ + { warehouse_id: this.getCurrentWarehouseId() }, + { deleted_at: null }, + ]; + + const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) + ? parsedResult.dynamicConditions + : []; + + if (dynamicConditions.length > 0) { + whereAndConditions.push({ [Op.and]: dynamicConditions }); + } + + // 快速搜索:按 custom_name 模糊匹配 + const quickWhereCondition = parsedResult.rawConditionsByField + ? parsedResult.rawConditionsByField.quickWhere + : null; + const quickWhereValue = quickWhereCondition && typeof quickWhereCondition === 'object' + ? quickWhereCondition.value + : null; + const keyword = String(quickWhereValue || '').trim(); + + if (keyword) { + whereAndConditions.push({ + [Op.or]: [ + { custom_name: { [Op.like]: `%${keyword}%` } }, + { express_code: { [Op.like]: `%${keyword}%` } }, + ], + }); + } + + return { [Op.and]: whereAndConditions }; + } + + /** + * 规范化分页参数。 + * @param {Object} [data={}] 请求参数 + * @return {{ page: number, pageSize: number, offset: number }} + */ + normalizePagination(data = {}) { + const pagination = data && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined + ? pagination.page + : (data.page !== undefined ? data.page : data.currentPage); + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.pageSize !== undefined ? data.pageSize : data.page_size)); + + const page = Math.max(Number.parseInt(pageSource, 10) || 1, 1); + const pageSize = Math.min(Math.max(Number.parseInt(pageSizeSource, 10) || 20, 1), 200); + + return { page, pageSize, offset: (page - 1) * pageSize }; + } + + /** + * 规范化策略记录输出。 + * @param {Object} row 策略记录 + * @return {Object} 输出结构 + */ + formatPolicyRow(row) { + return { + id: row.id, + warehouse_id: row.warehouse_id, + custom_name: row.custom_name, + shop_name: row.shop_name, + store_ids: row.store_ids, + store_names: row._store_names || null, + express_code: row.express_code, + express_name: row._express_name || row.express_code || null, + priority: row.priority, + is_enabled: row.is_enabled, + prohibited_type_id: row.prohibited_type_id, + prohibited_type_names: row._prohibited_type_names || null, + regions: row.regions, + exclude_regions: row.exclude_regions, + min_weight_g: row.min_weight_g, + max_weight_g: row.max_weight_g, + weight_type: row.weight_type, + remark: row.remark, + creator_id: row.creator_id, + created_at: row.created_at, + updated_at: row.updated_at, + }; + } + + /** + * 查询策略分页列表。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + const { ctx } = this; + const { page, pageSize, offset } = this.normalizePagination(data); + const where = this.buildListWhere(data); + + const result = await ctx.model.StoreExpressBindingPolicy.findAndCountAll({ + where, + order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + }); + + const rows = Array.isArray(result && result.rows) ? result.rows : []; + const plainRows = rows.map(row => (row && typeof row.get === 'function' ? row.get({ plain: true }) : row)); + + // 批量解析货主名称 & 违禁品名称 + const allStoreIds = new Set(); + const allProhibitedIds = new Set(); + for (const row of plainRows) { + if (Array.isArray(row.store_ids)) { + row.store_ids.forEach(id => allStoreIds.add(id)); + } + if (Array.isArray(row.prohibited_type_id)) { + row.prohibited_type_id.forEach(id => allProhibitedIds.add(id)); + } + } + + const storeNameMap = new Map(); + if (allStoreIds.size > 0) { + const stores = await ctx.model.Store.findAll({ + where: { id: [ ...allStoreIds ] }, + attributes: [ 'id', 'company_name' ], + }); + for (const s of stores) { + storeNameMap.set(s.id, s.company_name); + } + } + + const prohibitedNameMap = new Map(); + if (allProhibitedIds.size > 0) { + const types = await ctx.model.ProhibitedType.findAll({ + where: { id: [ ...allProhibitedIds ] }, + attributes: [ 'id', 'type_name' ], + }); + for (const t of types) { + prohibitedNameMap.set(t.id, t.type_name); + } + } + + // 批量解析快递名称(含系统快递 + 自定义映射) + const allExpressCodes = new Set(); + for (const row of plainRows) { + if (row.express_code) allExpressCodes.add(row.express_code); + } + const expressNameMap = new Map(); + if (allExpressCodes.size > 0) { + try { + const expressList = await ctx.service.systems.express.getExpressList(); + for (const item of (Array.isArray(expressList) ? expressList : [])) { + const code = String(item && (item.code || item.value) || '').trim(); + if (code && allExpressCodes.has(code)) { + expressNameMap.set(code, String(item.name || item.label || code).trim()); + } + } + } catch (_) { /* 快递列表查询失败不影响列表 */ } + } + + // 将名称数组挂到临时属性上 + for (const row of plainRows) { + if (Array.isArray(row.store_ids)) { + row._store_names = row.store_ids.map(id => storeNameMap.get(id) || String(id)); + } + if (Array.isArray(row.prohibited_type_id)) { + row._prohibited_type_names = row.prohibited_type_id.map(id => prohibitedNameMap.get(id) || String(id)); + } + if (row.express_code) { + row._express_name = expressNameMap.get(row.express_code) || row.express_code; + } + } + + const list = plainRows.map(row => this.formatPolicyRow(row)); + const total = Number(result && result.count ? result.count : 0); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: pageSize > 0 ? Math.ceil(total / pageSize) : 0, + hasNext: page * pageSize < total, + hasPrevious: page > 1, + }, + }; + } + + /** + * 校验自定义名称在同仓库下唯一(排除自身)。 + * @param {Object} payload 入参 + * @return {Promise} + */ + async ensureCustomNameUnique(payload) { + const { ctx } = this; + const { Op } = this.app.Sequelize; + const { warehouseId, customName, excludeId = null } = payload; + + const where = { + warehouse_id: warehouseId, + custom_name: customName, + deleted_at: null, + }; + + if (excludeId !== null) { + where.id = { [Op.ne]: excludeId }; + } + + const existed = await ctx.model.StoreExpressBindingPolicy.findOne({ + where, + attributes: [ 'id' ], + }); + + if (existed) { + throw this.createError('同仓库下策略名称已存在', 409); + } + } + + /** + * 新增策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 新增结果 + */ + async add(data = {}) { + const { ctx } = this; + const warehouseId = this.getCurrentWarehouseId(); + + const customName = this.normalizeText( + data.custom_name !== undefined ? data.custom_name : data.customName, + 'custom_name', + { required: true, maxLength: 100 } + ); + + const expressCode = await this.ensureExpressExists( + data.express_code !== undefined ? data.express_code : data.expressCode + ); + + const priority = this.normalizeInteger( + data.priority !== undefined ? data.priority : 0, + 'priority', + { required: false } + ); + + const isEnabled = data.is_enabled !== undefined + ? Number(data.is_enabled) + : (data.isEnabled !== undefined ? Number(data.isEnabled) : 1); + if (![ 0, 1 ].includes(isEnabled)) { + throw this.createError('is_enabled 参数不合法,仅支持 0 或 1', 400); + } + + const regions = this.normalizeJsonArray( + data.regions !== undefined ? data.regions : null, + 'regions' + ); + + const shopName = this.normalizeJsonArray( + data.shop_name !== undefined ? data.shop_name : data.shopName, + 'shop_name' + ); + + const storeIds = this.normalizeJsonArray( + data.store_ids !== undefined ? data.store_ids : data.storeIds, + 'store_ids' + ); + + const excludeRegions = this.normalizeJsonArray( + data.exclude_regions !== undefined ? data.exclude_regions : data.excludeRegions, + 'exclude_regions' + ); + + const minWeightG = this.normalizeInteger( + data.min_weight_g !== undefined ? data.min_weight_g : data.minWeightG, + 'min_weight_g' + ); + + const maxWeightG = this.normalizeInteger( + data.max_weight_g !== undefined ? data.max_weight_g : data.maxWeightG, + 'max_weight_g' + ); + + const weightType = this.normalizeWeightType( + data.weight_type !== undefined ? data.weight_type : data.weightType + ); + + const prohibitedTypeIds = this.normalizeJsonArray( + data.prohibited_type_id !== undefined ? data.prohibited_type_id : data.prohibitedTypeId, + 'prohibited_type_id' + ); + + const remark = this.normalizeText( + data.remark !== undefined ? data.remark : null, + 'remark', + { maxLength: 500 } + ); + + const creatorId = this.normalizeInteger( + data.creator_id !== undefined ? data.creator_id : data.creatorId, + 'creator_id' + ); + + // 校验名称唯一性 + await this.ensureCustomNameUnique({ warehouseId, customName }); + + const created = await ctx.model.StoreExpressBindingPolicy.create({ + warehouse_id: warehouseId, + custom_name: customName, + express_code: expressCode, + priority: priority ?? 0, + is_enabled: isEnabled, + regions, + shop_name: shopName, + store_ids: storeIds, + exclude_regions: excludeRegions, + min_weight_g: minWeightG, + max_weight_g: maxWeightG, + weight_type: weightType, + prohibited_type_id: prohibitedTypeIds, + remark, + creator_id: creatorId, + }); + + // 清理当前仓库策略缓存 + try { + await ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId); + } catch (_) { + // 缓存清理失败不影响主流程 + } + + const plainRow = created && typeof created.get === 'function' + ? created.get({ plain: true }) + : created; + + return { id: plainRow.id }; + } + + /** + * 读取策略并校验仓库归属。 + * @param {*} policyId 策略 ID + * @return {Promise} 策略模型实例 + */ + async findPolicyById(policyId) { + const { ctx } = this; + const id = this.normalizeInteger(policyId, 'id', { required: true, min: 1 }); + + const policy = await ctx.model.StoreExpressBindingPolicy.findOne({ + where: { + id, + warehouse_id: this.getCurrentWarehouseId(), + deleted_at: null, + }, + }); + + if (!policy) { + throw this.createError('策略不存在', 404); + } + + return policy; + } + + /** + * 编辑策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 编辑结果 + */ + async edit(data = {}) { + const id = data.id !== undefined ? data.id : data.policy_id; + + const policy = await this.findPolicyById(id); + const warehouseId = this.getCurrentWarehouseId(); + const updateFields = {}; + + // custom_name + const customName = data.custom_name !== undefined + ? data.custom_name + : (data.customName !== undefined ? data.customName : undefined); + if (customName !== undefined) { + const normalized = this.normalizeText(customName, 'custom_name', { maxLength: 100 }); + if (normalized && normalized !== policy.custom_name) { + await this.ensureCustomNameUnique({ + warehouseId, + customName: normalized, + excludeId: Number(policy.id), + }); + } + updateFields.custom_name = normalized; + } + + // express_code + const expressCode = data.express_code !== undefined + ? data.express_code + : (data.expressCode !== undefined ? data.expressCode : undefined); + if (expressCode !== undefined) { + updateFields.express_code = await this.ensureExpressExists(expressCode); + } + + // priority + const priority = data.priority !== undefined ? data.priority : undefined; + if (priority !== undefined) { + updateFields.priority = this.normalizeInteger(priority, 'priority'); + } + + // is_enabled + const isEnabled = data.is_enabled !== undefined + ? data.is_enabled + : (data.isEnabled !== undefined ? data.isEnabled : undefined); + if (isEnabled !== undefined) { + const val = Number(isEnabled); + if (![ 0, 1 ].includes(val)) { + throw this.createError('is_enabled 参数不合法,仅支持 0 或 1', 400); + } + updateFields.is_enabled = val; + } + + // regions + const regions = data.regions !== undefined ? data.regions : undefined; + if (regions !== undefined) { + updateFields.regions = this.normalizeJsonArray(regions, 'regions'); + } + + // shop_name + const shopName = data.shop_name !== undefined + ? data.shop_name + : (data.shopName !== undefined ? data.shopName : undefined); + if (shopName !== undefined) { + updateFields.shop_name = this.normalizeJsonArray(shopName, 'shop_name'); + } + + // store_ids + const storeIds = data.store_ids !== undefined + ? data.store_ids + : (data.storeIds !== undefined ? data.storeIds : undefined); + if (storeIds !== undefined) { + updateFields.store_ids = this.normalizeJsonArray(storeIds, 'store_ids'); + } + + // exclude_regions + const excludeRegions = data.exclude_regions !== undefined + ? data.exclude_regions + : (data.excludeRegions !== undefined ? data.excludeRegions : undefined); + if (excludeRegions !== undefined) { + updateFields.exclude_regions = this.normalizeJsonArray(excludeRegions, 'exclude_regions'); + } + + // min_weight_g + const minWeightG = data.min_weight_g !== undefined + ? data.min_weight_g + : (data.minWeightG !== undefined ? data.minWeightG : undefined); + if (minWeightG !== undefined) { + updateFields.min_weight_g = this.normalizeInteger(minWeightG, 'min_weight_g'); + } + + // max_weight_g + const maxWeightG = data.max_weight_g !== undefined + ? data.max_weight_g + : (data.maxWeightG !== undefined ? data.maxWeightG : undefined); + if (maxWeightG !== undefined) { + updateFields.max_weight_g = this.normalizeInteger(maxWeightG, 'max_weight_g'); + } + + // weight_type + const weightType = data.weight_type !== undefined + ? data.weight_type + : (data.weightType !== undefined ? data.weightType : undefined); + if (weightType !== undefined) { + updateFields.weight_type = this.normalizeWeightType(weightType); + } + + // prohibited_type_id + const prohibitedTypeIds = data.prohibited_type_id !== undefined + ? data.prohibited_type_id + : (data.prohibitedTypeId !== undefined ? data.prohibitedTypeId : undefined); + if (prohibitedTypeIds !== undefined) { + updateFields.prohibited_type_id = this.normalizeJsonArray(prohibitedTypeIds, 'prohibited_type_id'); + } + + // remark + const remark = data.remark !== undefined ? data.remark : undefined; + if (remark !== undefined) { + updateFields.remark = this.normalizeText(remark, 'remark', { maxLength: 500 }); + } + + // creator_id + const creatorId = data.creator_id !== undefined + ? data.creator_id + : (data.creatorId !== undefined ? data.creatorId : undefined); + if (creatorId !== undefined) { + updateFields.creator_id = this.normalizeInteger(creatorId, 'creator_id'); + } + + if (Object.keys(updateFields).length === 0) { + throw this.createError('没有需要更新的字段', 400); + } + + await policy.update(updateFields); + + // 清理当前仓库策略缓存 + try { + await this.ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId); + } catch (_) { + // 缓存清理失败不影响主流程 + } + + const updated = policy && typeof policy.get === 'function' + ? policy.get({ plain: true }) + : policy; + + return { id: updated.id }; + } + + /** + * 软删除策略。 + * @param {Object} [data={}] 请求参数 + * @return {Promise} 删除结果 + */ + async del(data = {}) { + const id = data.id !== undefined ? data.id : data.policy_id; + + const policy = await this.findPolicyById(id); + const now = new Date(); + + await policy.update({ deleted_at: now, is_enabled: 0 }); + + // 清理当前仓库策略缓存 + try { + const warehouseId = Number(policy.warehouse_id); + if (warehouseId > 0) { + await this.ctx.service.systems.expressPolicy.clearWarehousePolicyCache(warehouseId); + } + } catch (_) { + // 缓存清理失败不影响主流程 + } + + return { id: Number(policy.id) }; + } +} + +module.exports = StoreExpressBindingPolicyService; diff --git a/database/designs/store-express-binding-policy-design.md b/database/designs/store-express-binding-policy-design.md new file mode 100644 index 0000000..4c48653 --- /dev/null +++ b/database/designs/store-express-binding-policy-design.md @@ -0,0 +1,138 @@ +# 订单自定义店铺-快递绑定策略 设计方案 + +> **状态**: 📋 设计中 +> **设计日期**: 2026-08-03 +> **模块**: 订单快递分配策略 +> **表**: 1 张 — `wms_store_express_binding_policy` + +--- + +## 一、背景与目的 + +在 WMS 系统中,订单的快递分配目前依赖以下路径: + +1. `store_warehouse.policy_config.auto_allocate_express` 控制是否自动分配 +2. `express_interface` 表提供「仓库 + 店铺 + 平台 + 快递」的接口配置映射 +3. 货主 `subject_config.default_express_code` 提供默认快递 + +**痛点**:无法根据业务场景灵活配置"某个仓库下,某店铺(或某货主)强制使用/优先使用某快递"的策略。例如: + +- 仓库 A 的拼多多店铺「旗舰店」必须走中通(ZTO),而「奥莱店」走圆通(YTO) +- 同一店铺在不同条件下(如收件省份、商品类型)使用不同快递 +- 多人同时管理时需要记录创建人、创建时间,方便追溯 + +**解决方案**:新增 `wms_store_express_binding_policy` 表,支持自定义店铺-快递绑定策略,按优先级匹配。 + +--- + +## 二、数据库表 + +### `wms_store_express_binding_policy` + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|------|------|------|--------|------| +| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 | +| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 仓库ID,策略所属仓库 | +| `custom_name` | `VARCHAR(100)` | ✅ | — | 自定义店铺标签名称(自由文本,与系统店铺无关) | +| `express_code` | `VARCHAR(50)` | ✅ | — | 绑定的快递编码(关联 wms_express.code) | +| `priority` | `INT(11)` | ✅ | 0 | 优先级,数值越大越优先匹配 | +| `is_enabled` | `TINYINT(1)` | ✅ | 1 | 是否启用:0=停用,1=启用 | +| `match_condition` | `JSON` | — | NULL | 附加匹配条件(见下方说明) | +| `remark` | `VARCHAR(500)` | — | NULL | 备注说明 | +| `creator_id` | `BIGINT UNSIGNED` | — | NULL | 创建人账户ID(关联 accounts 表) | +| `created_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP | 创建时间 | +| `updated_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP ON UPDATE | 更新时间 | +| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 | + +### 索引设计 + +| 索引名 | 字段 | 说明 | +|--------|------|------| +| `PRIMARY` | `id` | 主键 | +| `idx_warehouse_enabled` | `warehouse_id`, `is_enabled`, `deleted_at` | 按仓库查询启用策略 | +| `idx_warehouse_express` | `warehouse_id`, `express_code`, `deleted_at` | 按仓库+快递反查绑定 | + +### `match_condition` 字段说明(JSON,可选) + +用于扩展匹配条件,可进一步按以下维度过滤: + +```jsonc +{ + "platform_codes": ["PDD", "TB"], // 限定平台编码 + "provinces": ["广东省", "浙江省"], // 限定收件省份 + "cities": ["广州市", "杭州市"], // 限定收件城市 + "item_codes": ["SKU001", "SKU002"], // 限定商品编码 + "min_weight_g": 0, // 最小重量(g),NULL=不限制 + "max_weight_g": 5000, // 最大重量(g),NULL=不限制 + "min_amount": 0, // 最小金额(元),NULL=不限制 + "max_amount": 1000 // 最大金额(元),NULL=不限制 +} +``` + +## 三、匹配逻辑(伪代码) + +``` +1. 查询 wms_store_express_binding_policy + WHERE warehouse_id = :warehouseId + AND is_enabled = 1 + AND deleted_at IS NULL + ORDER BY priority DESC, id ASC + +2. 遍历结果集,对每条策略: + a. 若 match_condition 为空 → 命中,返回 express_code + b. 若 match_condition 不为空 → 逐条件判断: + - platform_codes:订单平台编码是否在列表中 + - provinces / cities:收件地址省/市是否在列表中 + - item_codes:订单商品编码是否命中 + - min/max_weight_g:订单总重量是否在范围内 + - min/max_amount:订单总金额是否在范围内 + c. 所有条件 AND 全部满足 → 命中,返回 express_code + +3. 若未命中任何策略 → 回退到原有默认逻辑 + (express_interface 匹配 → subject_config.default_express_code) +``` + +## 四、与现有表的关系 + +``` +wms_store_express_binding_policy + ├─ warehouse_id → stores.id(逻辑关联,不做物理外键) + ├─ express_code → wms_express.code(逻辑关联) + └─ creator_id → accounts.id(逻辑关联) +``` + +## 五、典型使用场景 + +### 场景1:按自定义店铺标签绑定快递 + +```sql +INSERT INTO wms_store_express_binding_policy + (warehouse_id, custom_name, express_code, priority, creator_id) +VALUES + (1000000, '旗舰店-中通', 'ZTO', 10, 10001); +``` + +### 场景2:按自定义店铺标签+省份绑定快递(偏远地区走邮政) + +```sql +INSERT INTO wms_store_express_binding_policy + (warehouse_id, custom_name, express_code, priority, match_condition, creator_id) +VALUES + (1000000, '偏远地区邮政', 'EMS', 20, + '{"provinces":["新疆维吾尔自治区","西藏自治区","青海省"]}', 10001); +``` + +### 场景3:全局默认快递 + +```sql +INSERT INTO wms_store_express_binding_policy + (warehouse_id, custom_name, express_code, priority, creator_id) +VALUES + (1000000, '全局顺丰', 'SF', 5, 10001); +``` + +## 六、后续扩展 + +- 策略命中日志:记录每次快递分配命中了哪条策略,便于分析调整 +- 策略生效时间段:增加 `start_time` / `end_time` 支持定时策略(如大促期间切换快递) +- 策略复制:支持跨仓库复制策略配置 diff --git a/database/migrations/20260803150000-create-wms-store-express-binding-policy.js b/database/migrations/20260803150000-create-wms-store-express-binding-policy.js new file mode 100644 index 0000000..0fe917b --- /dev/null +++ b/database/migrations/20260803150000-create-wms-store-express-binding-policy.js @@ -0,0 +1,129 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + /** + * 创建订单自定义店铺-快递绑定策略表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID,策略所属仓库', + }, + custom_name: { + type: Sequelize.STRING(100), + allowNull: false, + comment: '自定义策略名称,便于人工识别', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID(stores.id),NULL=适用所有货主', + }, + shop_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '店铺ID(shops.id),NULL=适用所有店铺', + }, + express_code: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '绑定的快递编码(wms_express.code)', + }, + priority: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '优先级,数值越大越优先匹配', + }, + is_enabled: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用,1=启用', + }, + match_condition: { + type: Sequelize.JSON, + allowNull: true, + comment: '附加匹配条件(JSON):platform_codes/provinces/cities/item_codes/min_weight_g/max_weight_g/min_amount/max_amount', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注说明', + }, + creator_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人账户ID(accounts.id)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '订单自定义店铺-快递绑定策略表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + // 索引:按仓库查询启用策略 + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_enabled', + fields: [ 'warehouse_id', 'is_enabled', 'deleted_at' ], + }); + + // 索引:按仓库+货主+店铺精确匹配 + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_store_shop', + fields: [ 'warehouse_id', 'store_id', 'shop_id', 'deleted_at' ], + }); + + // 索引:按仓库+快递反查绑定店铺 + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_express', + fields: [ 'warehouse_id', 'express_code', 'deleted_at' ], + }); + }, + + /** + * 回滚:删除表。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + down: async (queryInterface, Sequelize) => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260803160000-remove-store-shop-id-from-binding-policy.js b/database/migrations/20260803160000-remove-store-shop-id-from-binding-policy.js new file mode 100644 index 0000000..dc79c57 --- /dev/null +++ b/database/migrations/20260803160000-remove-store-shop-id-from-binding-policy.js @@ -0,0 +1,40 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + /** + * 移除冗余字段 store_id / shop_id 及其索引。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + up: async (queryInterface, Sequelize) => { + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_store_shop'); + await queryInterface.removeColumn(TABLE_NAME, 'store_id'); + await queryInterface.removeColumn(TABLE_NAME, 'shop_id'); + }, + + /** + * 回滚:恢复 store_id / shop_id 列及索引。 + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 迁移执行结果。 + */ + down: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'store_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '货主ID(stores.id),NULL=适用所有货主', + }); + await queryInterface.addColumn(TABLE_NAME, 'shop_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '店铺ID(shops.id),NULL=适用所有店铺', + }); + await queryInterface.addIndex(TABLE_NAME, { + name: 'idx_warehouse_store_shop', + fields: [ 'warehouse_id', 'store_id', 'shop_id', 'deleted_at' ], + }); + }, +}; diff --git a/database/migrations/20260803163000-add-prohibited-type-id-to-binding-policy.js b/database/migrations/20260803163000-add-prohibited-type-id-to-binding-policy.js new file mode 100644 index 0000000..dd485a9 --- /dev/null +++ b/database/migrations/20260803163000-add-prohibited-type-id-to-binding-policy.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'prohibited_type_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '违禁品类型ID(关联 wms_prohibited_type.id),NULL=不限制违禁品', + after: 'match_condition', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'prohibited_type_id'); + }, +}; diff --git a/database/migrations/20260803164500-replace-match-condition-with-provinces-cities.js b/database/migrations/20260803164500-replace-match-condition-with-provinces-cities.js new file mode 100644 index 0000000..9453a0a --- /dev/null +++ b/database/migrations/20260803164500-replace-match-condition-with-provinces-cities.js @@ -0,0 +1,31 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'match_condition'); + await queryInterface.addColumn(TABLE_NAME, 'provinces', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定省份,逗号分隔,如"广东省,浙江省",NULL=不限制', + after: 'is_enabled', + }); + await queryInterface.addColumn(TABLE_NAME, 'cities', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定城市,逗号分隔,如"广州市,杭州市",NULL=不限制', + after: 'provinces', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'cities'); + await queryInterface.removeColumn(TABLE_NAME, 'provinces'); + await queryInterface.addColumn(TABLE_NAME, 'match_condition', { + type: Sequelize.JSON, + allowNull: true, + comment: '附加匹配条件(JSON)', + }); + }, +}; diff --git a/database/migrations/20260803170000-add-weight-range-to-binding-policy.js b/database/migrations/20260803170000-add-weight-range-to-binding-policy.js new file mode 100644 index 0000000..5c2073d --- /dev/null +++ b/database/migrations/20260803170000-add-weight-range-to-binding-policy.js @@ -0,0 +1,25 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'min_weight_g', { + type: Sequelize.INTEGER, + allowNull: true, + comment: '最小重量(克),NULL=不限制', + after: 'cities', + }); + await queryInterface.addColumn(TABLE_NAME, 'max_weight_g', { + type: Sequelize.INTEGER, + allowNull: true, + comment: '最大重量(克),NULL=不限制', + after: 'min_weight_g', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'max_weight_g'); + await queryInterface.removeColumn(TABLE_NAME, 'min_weight_g'); + }, +}; diff --git a/database/migrations/20260803170500-add-weight-type-to-binding-policy.js b/database/migrations/20260803170500-add-weight-type-to-binding-policy.js new file mode 100644 index 0000000..4dd20d5 --- /dev/null +++ b/database/migrations/20260803170500-add-weight-type-to-binding-policy.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'weight_type', { + type: Sequelize.TINYINT(1), + allowNull: true, + comment: '重量段类型:NULL=不限制/0=常规/1=轻货/2=重货/3=冷链', + after: 'max_weight_g', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'weight_type'); + }, +}; diff --git a/database/migrations/20260803171000-make-weight-type-required.js b/database/migrations/20260803171000-make-weight-type-required.js new file mode 100644 index 0000000..7e6f6e7 --- /dev/null +++ b/database/migrations/20260803171000-make-weight-type-required.js @@ -0,0 +1,23 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'weight_type', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '重量段类型:0=常规/1=轻货/2=重货/3=冷链', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'weight_type', { + type: Sequelize.TINYINT(1), + allowNull: true, + defaultValue: null, + comment: '重量段类型:NULL=不限制/0=常规/1=轻货/2=重货/3=冷链', + }); + }, +}; diff --git a/database/migrations/20260804090000-merge-provinces-cities-to-regions.js b/database/migrations/20260804090000-merge-provinces-cities-to-regions.js new file mode 100644 index 0000000..b7d5945 --- /dev/null +++ b/database/migrations/20260804090000-merge-provinces-cities-to-regions.js @@ -0,0 +1,30 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'cities'); + await queryInterface.removeColumn(TABLE_NAME, 'provinces'); + await queryInterface.addColumn(TABLE_NAME, 'regions', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定地区,逗号分隔,如"广东省,广州市,深圳市",NULL=不限制', + after: 'is_enabled', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'regions'); + await queryInterface.addColumn(TABLE_NAME, 'provinces', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定省份', + }); + await queryInterface.addColumn(TABLE_NAME, 'cities', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定城市', + }); + }, +}; diff --git a/database/migrations/20260804091000-add-exclude-regions.js b/database/migrations/20260804091000-add-exclude-regions.js new file mode 100644 index 0000000..77285cf --- /dev/null +++ b/database/migrations/20260804091000-add-exclude-regions.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'exclude_regions', { + type: Sequelize.TEXT, + allowNull: true, + comment: '排除地区,逗号分隔,如"新疆维吾尔自治区,西藏自治区",NULL=不排除', + after: 'regions', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'exclude_regions'); + }, +}; diff --git a/database/migrations/20260804100000-add-shop-name.js b/database/migrations/20260804100000-add-shop-name.js new file mode 100644 index 0000000..c1dbe5b --- /dev/null +++ b/database/migrations/20260804100000-add-shop-name.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'shop_name', { + type: Sequelize.TEXT, + allowNull: true, + comment: '包含店铺名称,逗号分隔,NULL=不限制', + after: 'custom_name', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'shop_name'); + }, +}; diff --git a/database/migrations/20260804101000-add-store-ids.js b/database/migrations/20260804101000-add-store-ids.js new file mode 100644 index 0000000..2e9aabb --- /dev/null +++ b/database/migrations/20260804101000-add-store-ids.js @@ -0,0 +1,18 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn(TABLE_NAME, 'store_ids', { + type: Sequelize.TEXT, + allowNull: true, + comment: '限定货主ID,逗号分隔,NULL=不限制', + after: 'shop_name', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn(TABLE_NAME, 'store_ids'); + }, +}; diff --git a/database/migrations/20260804110000-change-text-to-json.js b/database/migrations/20260804110000-change-text-to-json.js new file mode 100644 index 0000000..95722c1 --- /dev/null +++ b/database/migrations/20260804110000-change-text-to-json.js @@ -0,0 +1,19 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'regions', { type: Sequelize.JSON, allowNull: true, comment: '限定地区,字符串数组' }); + await queryInterface.changeColumn(TABLE_NAME, 'exclude_regions', { type: Sequelize.JSON, allowNull: true, comment: '排除地区,字符串数组' }); + await queryInterface.changeColumn(TABLE_NAME, 'shop_name', { type: Sequelize.JSON, allowNull: true, comment: '包含店铺名称,字符串数组' }); + await queryInterface.changeColumn(TABLE_NAME, 'store_ids', { type: Sequelize.JSON, allowNull: true, comment: '限定货主ID,数字数组' }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'regions', { type: Sequelize.TEXT, allowNull: true, comment: '限定地区,逗号分隔' }); + await queryInterface.changeColumn(TABLE_NAME, 'exclude_regions', { type: Sequelize.TEXT, allowNull: true, comment: '排除地区,逗号分隔' }); + await queryInterface.changeColumn(TABLE_NAME, 'shop_name', { type: Sequelize.TEXT, allowNull: true, comment: '包含店铺名称,逗号分隔' }); + await queryInterface.changeColumn(TABLE_NAME, 'store_ids', { type: Sequelize.TEXT, allowNull: true, comment: '限定货主ID,逗号分隔' }); + }, +}; diff --git a/database/migrations/20260804120000-change-prohibited-to-json.js b/database/migrations/20260804120000-change-prohibited-to-json.js new file mode 100644 index 0000000..f2b1f9b --- /dev/null +++ b/database/migrations/20260804120000-change-prohibited-to-json.js @@ -0,0 +1,21 @@ +'use strict'; + +const TABLE_NAME = 'wms_store_express_binding_policy'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'prohibited_type_id', { + type: Sequelize.JSON, + allowNull: true, + comment: '违禁品类型ID数组(关联 wms_prohibited_type.id),如[1,2],NULL=不限制违禁品', + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.changeColumn(TABLE_NAME, 'prohibited_type_id', { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: true, + comment: '违禁品类型ID(关联 wms_prohibited_type.id),NULL=不限制违禁品', + }); + }, +}; diff --git a/methods/system.json b/methods/system.json index 720d335..679e87a 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.9", - "updatedAt": "2026-08-03", + "version": "0.3.17", + "updatedAt": "2026-08-04", "headers": [ { "name": "platform", @@ -32454,6 +32454,491 @@ ] } ] + }, + { + "groupName": "店铺快递绑定策略模块", + "module": "storeExpressBindingPolicy", + "list": [ + { + "method": "storeExpressBindingPolicy.list", + "description": "分页查询策略列表,按priority DESC updated_at DESC排序", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,兼容pagination.page/currentPage" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页大小,兼容page_size/pagination.page_size,最大200" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "字段兼容id/custom_name/shop_name(数组)/store_ids(数组)/express_code/priority/is_enabled/regions(数组)/exclude_regions(数组)/prohibited_type_id(数组)/weight_type/min_weight_g/max_weight_g/creator_id/quickWhere" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "策略数组shop_name/store_ids/regions/exclude_regions/prohibited_type_id均为JSON数组,附带store_names/prohibited_type_names文本数组,express_name为快递名称" + }, + { + "name": "data.list[].store_names", + "type": "array", + "required": false, + "description": "货主名称文本数组,与store_ids一一对应" + }, + { + "name": "data.list[].prohibited_type_names", + "type": "array", + "required": false, + "description": "违禁品类型名称文本数组,与prohibited_type_id一一对应" + }, + { + "name": "data.list[].express_name", + "type": "string", + "required": false, + "description": "快递名称(含系统快递和自定义映射)" + }, + { + "name": "data.pagination", + "type": "object", + "required": true, + "description": "业务状态码" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 401, + "message": "未认证" + } + ] + }, + { + "method": "storeExpressBindingPolicy.add", + "description": "新增策略。必填custom_name+express_code。weight_type默认0。同仓库custom_name唯一", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "custom_name", + "type": "string", + "required": true, + "source": "body", + "description": "策略名称同仓库唯一兼容customName" + }, + { + "name": "shop_name", + "type": "array", + "required": false, + "source": "body", + "description": "包含店铺名称字符串数组兼容shopName" + }, + { + "name": "store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "限定货主ID数字数组兼容storeIds" + }, + { + "name": "express_code", + "type": "string", + "required": true, + "source": "body", + "description": "快递编码兼容expressCode" + }, + { + "name": "priority", + "type": "number", + "required": false, + "source": "body", + "description": "优先级默认0" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "0停用1启用默认1兼容isEnabled" + }, + { + "name": "regions", + "type": "array", + "required": false, + "source": "body", + "description": "限定地区字符串数组" + }, + { + "name": "exclude_regions", + "type": "array", + "required": false, + "source": "body", + "description": "排除地区字符串数组兼容excludeRegions" + }, + { + "name": "min_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "最小重量克兼容minWeightG" + }, + { + "name": "max_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "最大重量克兼容maxWeightG" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "source": "body", + "description": "0常规1轻货2重货3冷链默认0兼容weightType" + }, + { + "name": "prohibited_type_id", + "type": "array", + "required": false, + "source": "body", + "description": "违禁品类型ID数字数组兼容prohibitedTypeId" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注最大500字符" + }, + { + "name": "creator_id", + "type": "number", + "required": false, + "source": "body", + "description": "创建人账户ID兼容creatorId" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "策略ID" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 401, + "message": "未认证" + }, + { + "code": 409, + "message": "同仓库策略名已存在" + } + ] + }, + { + "method": "storeExpressBindingPolicy.edit", + "description": "编辑策略必填id仅更新传入字段", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "策略ID兼容policy_id/policyId" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "兼容customName" + }, + { + "name": "shop_name", + "type": "array", + "required": false, + "source": "body", + "description": "包含店铺名称字符串数组兼容shopName" + }, + { + "name": "store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "限定货主ID数字数组兼容storeIds" + }, + { + "name": "express_code", + "type": "string", + "required": false, + "source": "body", + "description": "兼容expressCode" + }, + { + "name": "priority", + "type": "number", + "required": false, + "source": "body", + "description": "优先级" + }, + { + "name": "is_enabled", + "type": "number", + "required": false, + "source": "body", + "description": "兼容isEnabled" + }, + { + "name": "regions", + "type": "array", + "required": false, + "source": "body", + "description": "限定地区字符串数组" + }, + { + "name": "exclude_regions", + "type": "array", + "required": false, + "source": "body", + "description": "排除地区字符串数组兼容excludeRegions" + }, + { + "name": "min_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "兼容minWeightG" + }, + { + "name": "max_weight_g", + "type": "number", + "required": false, + "source": "body", + "description": "兼容maxWeightG" + }, + { + "name": "weight_type", + "type": "number", + "required": false, + "source": "body", + "description": "兼容weightType" + }, + { + "name": "prohibited_type_id", + "type": "array", + "required": false, + "source": "body", + "description": "违禁品类型ID数字数组兼容prohibitedTypeId" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + }, + { + "name": "creator_id", + "type": "number", + "required": false, + "source": "body", + "description": "兼容creatorId" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "策略ID" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 401, + "message": "未认证" + }, + { + "code": 404, + "message": "策略不存在" + }, + { + "code": 409, + "message": "同仓库策略名已存在" + } + ] + }, + { + "method": "storeExpressBindingPolicy.del", + "description": "软删除策略", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "策略ID兼容policy_id/policyId" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "调用成功为success" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务状态码" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "策略ID" + } + ], + "errors": [ + { + "code": 400, + "message": "id为空" + }, + { + "code": 401, + "message": "未认证" + }, + { + "code": 404, + "message": "策略不存在" + } + ] + } + ] } ] }