'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 快递编码 * @param value * @param fieldName * @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;