'use strict'; const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); const { buildNotDeletedShopWhere } = require('../../../lib/shop_soft_delete'); const DEFAULT_CACHE_TTL_SECONDS = 600; class SettingExpressInterfaceService extends Service { /** * 创建业务错误对象。 * * @param {string} message 错误信息 * @param {number} [code=500] 错误码 * @return {Error} 业务错误对象 */ createError(message, code = 500) { const error = new Error(message); error.code = code; return error; } /** * 获取当前仓库主体 ID。 * * @return {number} 当前仓库主体 ID */ getCurrentStoreId() { const storeId = Number(this.ctx.user && this.ctx.user.store_id); if (!Number.isFinite(storeId) || storeId <= 0) { throw this.createError('未识别到当前主体,无法操作快递接口', 400); } return storeId; } /** * 生成仓库与平台维度的快递接口缓存键。 * * @param {number|string} warehouseId 仓库 ID * @param {string} platformCode 平台代码 * @return {string} 缓存键 */ getWarehousePlatformCacheKey(warehouseId, platformCode) { const normalizedWarehouseId = Number(warehouseId || 0); const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); return `express_interface:warehouse:${normalizedWarehouseId}:platform:${normalizedPlatformCode}`; } /** * 删除指定缓存键。 * * @param {string} cacheKey 缓存键 * @return {Promise} */ async deleteCacheByKey(cacheKey) { if (!cacheKey) { return; } const { app } = this; if (app && typeof app.delCacheAsync === 'function') { await app.delCacheAsync(cacheKey); return; } if (app && typeof app.setCacheAsync === 'function') { await app.setCacheAsync(cacheKey, null, 0); } } /** * 清理当前仓库与平台维度的快递接口缓存。 * * @param {number|string} warehouseId 仓库 ID * @param {string} platformCode 平台代码 * @return {Promise} */ async clearWarehousePlatformCache(warehouseId, platformCode) { await this.deleteCacheByKey(this.getWarehousePlatformCacheKey(warehouseId, platformCode)); } /** * 规范化平台代码。 * * @param {string} value 原始值 * @param {string} fieldName 字段名称 * @param {number} [maxLength=20] 最大长度 * @return {string} 规范化后的平台代码 */ normalizePlatformCode(value, fieldName, maxLength = 20) { const normalized = this.normalizeText(value, fieldName, maxLength).toUpperCase(); if (!normalized) { throw this.createError(`${fieldName} 参数不能为空`, 400); } return normalized; } /** * 规范化文本值。 * * @param {string} value 原始值 * @param {string} fieldName 字段名称 * @param {number} [maxLength=255] 最大长度 * @return {string} 规范化后的文本 */ normalizeText(value, fieldName, maxLength = 255) { if (value === undefined || value === null) { return ''; } const normalized = String(value).trim(); if (normalized.length > maxLength) { throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); } return normalized; } /** * 规范化可选文本值。 * * @param {string} value 原始值 * @param {string} fieldName 字段名称 * @param {number} [maxLength=255] 最大长度 * @return {string|null} 规范化后的文本 */ normalizeOptionalText(value, fieldName, maxLength = 255) { if (value === undefined || value === null) { return null; } const normalized = String(value).trim(); if (normalized.length > maxLength) { throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); } return normalized; } /** * 规范化可选 JSON 值。 * * @param {*} value 原始值 * @param {string} fieldName 字段名称 * @return {*|null} 规范化后的 JSON 值 */ normalizeOptionalJson(value, fieldName) { if (value === undefined || value === null || value === '') { return null; } if (typeof value === 'string') { const normalized = value.trim(); if (!normalized) { return null; } try { return this.clonePlainValue(JSON.parse(normalized)); } catch (error) { throw this.createError(`${fieldName} 必须是合法 JSON`, 400); } } return this.clonePlainValue(value); } /** * 规范化整数值。 * * @param {number|string} value 原始值 * @param {string} fieldName 字段名称 * @param {Object} [options] 额外选项 * @param {boolean} [options.allowEmpty=false] 是否允许空值 * @param {number|null} [options.min=null] 最小值 * @param {number|null} [options.max=null] 最大值 * @return {number|null} 规范化后的整数 */ normalizeInteger(value, fieldName, options = {}) { const { allowEmpty = false, min = null, max = null, } = options; if (value === undefined || value === null || value === '') { if (allowEmpty) { return null; } throw this.createError(`${fieldName} 参数不能为空`, 400); } const normalized = Number(value); if (!Number.isInteger(normalized)) { throw this.createError(`${fieldName} 参数不合法`, 400); } if (min !== null && normalized < min) { throw this.createError(`${fieldName} 参数不合法`, 400); } if (max !== null && normalized > max) { throw this.createError(`${fieldName} 参数不合法`, 400); } return normalized; } /** * 规范化布尔标记。 * * @param {number|string} value 原始值 * @param {string} fieldName 字段名称 * @param {number|null} [defaultValue=null] 默认值 * @return {number|null} 规范化后的标记 */ normalizeFlag(value, fieldName, defaultValue = null) { if (value === undefined || value === null || value === '') { return defaultValue; } const normalized = Number(value); if (normalized === 0 || normalized === 1) { return normalized; } throw this.createError(`${fieldName} 参数不合法`, 400); } /** * 规范化分页参数。 * * @param {number|string} value 原始值 * @param {string} fieldName 字段名称 * @param {number} defaultValue 默认值 * @param {number} maxValue 最大值 * @return {number} 规范化后的分页值 */ normalizePage(value, fieldName, defaultValue, maxValue) { if (value === undefined || value === null || value === '') { return defaultValue; } const normalized = Number(value); if (!Number.isFinite(normalized) || normalized <= 0) { throw this.createError(`${fieldName} 参数不合法`, 400); } return Math.min(Math.floor(normalized), maxValue); } /** * 获取列表查询字段映射。 * * @return {Object} 字段映射 */ getListWhereSpecialFieldMap() { return { id: { field: 'id', }, name: { field: 'name', }, express_code: { field: 'express_code', }, sys_express_code: { field: 'sys_express_code', }, platform_code: { field: 'platform_code', }, shop_id: { field: 'shop_id', }, template_id: { field: 'template_id', }, brandno: { field: 'brandno', }, sender_name: { field: 'sender_name', }, sender_tel: { field: 'sender_tel', }, viewer: { field: 'viewer', }, client_id: { field: 'client_id', }, share_id: { field: 'share_id', }, site_code: { field: 'site_code', }, product_type: { field: 'product_type', }, template_url: { field: 'template_url', }, shop_name: { field: 'shop_name', }, quickWhere: { bucket: 'quick', }, }; } /** * 解析列表查询条件。 * * @param {Object} data 请求参数 * @return {Object} 查询条件信息 */ resolveListWhere(data = {}) { const { ctx, app } = this; const normalizedWhere = ctx.where && typeof ctx.where === 'object' ? { ...ctx.where } : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); let parsedResult = ctx.whereParsed; if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { const parsed = parseWhereConditions({ where: normalizedWhere, app, specialFieldMap: this.getListWhereSpecialFieldMap(), }); if (!parsed.ok) { throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); } parsedResult = parsed.result; } return { normalizedWhere, parsedResult, }; } /** * 获取快递接口联查配置。 * * @param {Object} [options={}] 查询选项 * @return {Array} Sequelize 关联配置。 */ getInterfaceInclude(options = {}) { const { ctx } = this; const { full = false } = options; const includes = [{ model: ctx.model.Express, as: 'express', required: false, }]; if (!full) { includes[0].attributes = [ 'code', 'name' ]; } if (full && ctx.model && ctx.model.Shop) { includes.push({ model: ctx.model.Shop, as: 'shop', required: false, }); } return includes; } /** * 获取快递接口模型的全量字段。 * * @return {Array} 模型字段列表 */ getInterfaceFullAttributes() { const rawAttributes = this.ctx && this.ctx.model && this.ctx.model.ExpressInterface && this.ctx.model.ExpressInterface.rawAttributes; if (!rawAttributes || typeof rawAttributes !== 'object') { return []; } return Object.keys(rawAttributes); } /** * 校验模型字段是否存在。 * * @param {Object} model Sequelize 模型 * @param {string} fieldName 字段名 * @param {string} modelName 模型名称 * @return {boolean} 字段是否存在 */ ensureModelFieldExists(model, fieldName, modelName) { const rawAttributes = model && model.rawAttributes; if (!rawAttributes || !Object.prototype.hasOwnProperty.call(rawAttributes, fieldName)) { throw this.createError(`${modelName}.${fieldName} 字段不存在,无法继续处理`, 500); } return true; } /** * 根据店铺 ID 解析要同步的店铺与 token 信息。 * * @param {number|null} shopId 规范化后的店铺 ID * @return {Promise} 同步后的店铺绑定信息 */ async resolveShopBinding(shopId) { this.ensureModelFieldExists(this.ctx.model.Shop, 'access_token', 'Shop'); this.ensureModelFieldExists(this.ctx.model.ExpressInterface, 'token', 'ExpressInterface'); if (shopId === null) { return { shopId: null, token: null, }; } const currentStoreId = this.getCurrentStoreId(); const shop = await this.ctx.model.Shop.findOne({ where: { id: shopId, warehouse_id: currentStoreId, ...buildNotDeletedShopWhere(this.app), }, attributes: [ 'id', 'warehouse_id', 'access_token' ], }); if (!shop) { throw this.createError('当前仓库下未找到对应店铺,无法同步快递接口 token', 404); } const plainShop = shop && typeof shop.get === 'function' ? shop.get({ plain: true }) : shop; const normalizedToken = this.normalizeOptionalText(plainShop.access_token, 'access_token', 255); return { shopId: Number(plainShop.id), token: normalizedToken || null, }; } /** * 复制普通对象或数组,避免缓存对象被外部修改。 * * @param {*} value 待复制的值 * @return {*} 复制后的值 */ clonePlainValue(value) { if (Array.isArray(value)) { return value.map(item => this.clonePlainValue(item)); } if (value && typeof value === 'object') { const cloned = {}; for (const [ key, item ] of Object.entries(value)) { cloned[key] = this.clonePlainValue(item); } return cloned; } return value; } /** * 规范化系统快递记录。 * * @param {Object} row 数据库记录 * @return {Object|null} 规范化后的系统快递信息 */ normalizeExpressRow(row) { if (!row || typeof row !== 'object') { return null; } return { code: this.normalizeOptionalText(row.code, 'express.code', 50), name: this.normalizeOptionalText(row.name, 'express.name', 255), polyapi_code: this.normalizeOptionalText(row.polyapi_code, 'express.polyapi_code', 255), polyapi_extra_info: row.polyapi_extra_info === undefined ? null : row.polyapi_extra_info, pdd_code: this.normalizeOptionalText(row.PDD !== undefined ? row.PDD : row.pdd_code, 'express.pdd_code', 255), ks_code: this.normalizeOptionalText(row.KS !== undefined ? row.KS : row.ks_code, 'express.ks_code', 255), dyxd_code: this.normalizeOptionalText(row.DY !== undefined ? row.DY : row.dyxd_code, 'express.dyxd_code', 255), }; } /** * 判断列表项中的快递编码是否为系统快递编码。 * * @param {Object} row 快递接口记录 * @param {Object|null} express 系统快递信息 * @return {number} 是系统快递编码返回 1,否则返回 0 */ resolveIsSystemExpressCodeFlag(row, express) { const expressCode = this.normalizeOptionalText(row && row.express_code, 'express_code', 255); const systemExpressCode = this.normalizeOptionalText( row && (row.sys_express_code !== undefined && row.sys_express_code !== null ? row.sys_express_code : (express && express.code)), 'sys_express_code', 50 ); if (!expressCode || !systemExpressCode) { return 0; } return expressCode.toUpperCase() === systemExpressCode.toUpperCase() ? 1 : 0; } /** * 获取平台自建快递编码字段名。 * * @param {string} platformCode 平台编码 * @return {string|null} 平台字段名 */ getPlatformExpressColumn(platformCode) { const normalizedPlatformCode = this.normalizePlatformCode(platformCode, 'platform_code', 20); const fieldMap = { KS: 'KS', KSAPP: 'KS', PDD: 'PDD', DYXD: 'DY', DY: 'DY', DOUYIN: 'DY', }; return fieldMap[normalizedPlatformCode] || null; } /** * 校验系统快递编码是否存在。 * * @param {string} sysExpressCode 系统快递编码 * @return {Promise} 系统快递编码 */ async ensureSystemExpressCodeExists(sysExpressCode) { const normalizedSysExpressCode = this.normalizeText(sysExpressCode, 'sys_express_code', 50).toUpperCase(); const express = await this.ctx.model.Express.findOne({ where: { code: normalizedSysExpressCode, }, attributes: [ 'code' ], }); if (!express) { throw this.createError('sys_express_code 未匹配到系统快递编码', 400); } return normalizedSysExpressCode; } /** * 校验打印平台编码是否存在。 * * 当运行环境尚未注册 `PrintPlatform` 模型时跳过校验,保持旧测试桩兼容; * 已注册模型时统一校验 `wms_print_platform.platform_code`。 * * @param {string} platformCode 打印平台编码。 * @return {Promise} 规范化后的打印平台编码。 */ async ensurePrintPlatformExists(platformCode) { const normalizedPlatformCode = this.normalizePlatformCode(platformCode, 'platform_code', 20); const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; if (!printPlatformModel || typeof printPlatformModel.findOne !== 'function') { return normalizedPlatformCode; } const printPlatform = await printPlatformModel.findOne({ where: { platform_code: normalizedPlatformCode, }, attributes: [ 'platform_code' ], }); if (!printPlatform) { throw this.createError('platform_code 未匹配到打印平台编码', 400); } return normalizedPlatformCode; } /** * 规范化打印平台记录。 * * 返回结构尽量与现有平台/下拉列表风格保持一致。 * * @param {Object} row 打印平台记录。 * @return {Object|null} 规范化后的打印平台数据。 */ normalizePrintPlatformRow(row) { if (!row || typeof row !== 'object') { return null; } const platformCode = this.normalizeOptionalText(row.platform_code, 'platform_code', 20); if (!platformCode) { return null; } const platformName = this.normalizeOptionalText(row.platform_name, 'platform_name', 100); const platid = row.platid === undefined || row.platid === null || row.platid === '' ? null : String(row.platid); return { id: row.id === undefined || row.id === null ? null : Number(row.id), code: platformCode, name: platformName || platformCode, value: platformCode, label: platformName || platformCode, platform_code: platformCode, platform_name: platformName, platid, status: this.normalizeOptionalText(row.status, 'status', 20) || 'ACTIVE', remark: this.normalizeOptionalText(row.remark, 'remark', 255), need_callback_url: this.normalizeOptionalText(row.need_callback_url, 'need_callback_url', 500), }; } /** * 获取打印平台全量列表。 * * 仅返回未删除且状态为启用的打印平台,供快递接口配置页下拉选择使用。 * * @return {Promise>} 打印平台列表。 */ async getPrintPlatformList() { const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function') { return []; } const rows = await printPlatformModel.findAll({ attributes: [ 'id', 'platform_code', 'platform_name', 'platid', 'status', 'remark', 'need_callback_url' ], where: { deleted: 0, status: 'ACTIVE', }, order: [[ 'platform_name', 'ASC' ], [ 'id', 'ASC' ]], }); if (!Array.isArray(rows)) { return []; } return rows .map(row => (row && typeof row.get === 'function' ? row.get({ plain: true }) : row)) .map(row => this.normalizePrintPlatformRow(row)) .filter(Boolean); } /** * 根据外部快递编码解析系统快递编码。 * * @param {Object} data 输入参数 * @param {string} data.expressCode 外部快递编码 * @param {string} data.platformCode 平台编码 * @param {string} [data.sysExpressCode] 显式系统快递编码 * @return {Promise} 系统快递编码 */ async resolveSysExpressCode(data = {}) { const expressCode = this.normalizeText(data.expressCode, 'express_code', 255).toUpperCase(); const platformCode = this.normalizePlatformCode(data.platformCode, 'platform_code', 20); const inputSysExpressCode = data.sysExpressCode; if (inputSysExpressCode !== undefined && inputSysExpressCode !== null && String(inputSysExpressCode).trim() !== '') { return await this.ensureSystemExpressCodeExists(inputSysExpressCode); } const matchedBySystemCode = await this.ctx.model.Express.findOne({ where: { code: expressCode, }, attributes: [ 'code' ], }); if (matchedBySystemCode) { return this.normalizeText(matchedBySystemCode.code, 'sys_express_code', 50).toUpperCase(); } const platformColumn = this.getPlatformExpressColumn(platformCode); if (platformColumn) { const matchedByPlatformCode = await this.ctx.model.Express.findOne({ where: { [platformColumn]: expressCode, }, attributes: [ 'code' ], }); if (matchedByPlatformCode) { return this.normalizeText(matchedByPlatformCode.code, 'sys_express_code', 50).toUpperCase(); } } throw this.createError('express_code 未匹配到系统快递编码', 400); } /** * 规范化快递接口记录。 * * @param {Object} row 数据库记录 * @param {Object} [options={}] 规范化选项 * @return {Object|null} 规范化后的记录 */ normalizeInterfaceRow(row, options = {}) { if (!row || typeof row !== 'object') { return null; } const { includeSystemExpressFlag = false } = options; const express = this.normalizeExpressRow(row.express && typeof row.express === 'object' ? row.express : null); const normalizedRow = { id: row.id === undefined || row.id === null ? null : Number(row.id), name: this.normalizeOptionalText(row.name, 'name', 255), express_code: this.normalizeOptionalText(row.express_code, 'express_code', 255), sys_express_code: this.normalizeOptionalText(row.sys_express_code, 'sys_express_code', 50), warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), shop_id: row.shop_id === undefined || row.shop_id === null ? null : Number(row.shop_id), platform_shop_id: row.platform_shop_id === undefined || row.platform_shop_id === null ? null : Number(row.platform_shop_id), template_id: this.normalizeOptionalText(row.template_id, 'template_id', 50), paymode: row.paymode === undefined || row.paymode === null ? null : Number(row.paymode), brandno: this.normalizeOptionalText(row.brandno, 'brandno', 255), providertype: this.normalizeOptionalText(row.providertype, 'providertype', 50), providerid: row.providerid === undefined || row.providerid === null ? null : Number(row.providerid), platform_code: this.normalizeOptionalText(row.platform_code, 'platform_code', 20), sender_name: this.normalizeOptionalText(row.sender_name, 'sender_name', 50), sender_tel: this.normalizeOptionalText(row.sender_tel, 'sender_tel', 11), weight: row.weight === undefined || row.weight === null ? null : Number(row.weight), weight_type: row.weight_type === undefined || row.weight_type === null ? null : Number(row.weight_type), viewer: this.normalizeOptionalText(row.viewer, 'viewer', 50), client_id: this.normalizeOptionalText(row.client_id, 'client_id', 50), is_share: row.is_share === undefined || row.is_share === null ? null : Number(row.is_share), ispickup: row.ispickup === undefined || row.ispickup === null ? null : Number(row.ispickup), shipperno: this.normalizeOptionalText(row.shipperno, 'shipperno', 255), template_url: this.normalizeOptionalText(row.template_url, 'template_url', 500), ext_data: this.clonePlainValue(row.ext_data === undefined ? null : row.ext_data), province_name: this.normalizeOptionalText(row.province_name, 'province_name', 255), city_name: this.normalizeOptionalText(row.city_name, 'city_name', 255), district_name: this.normalizeOptionalText(row.district_name, 'district_name', 255), address: this.normalizeOptionalText(row.address, 'address', 255), town_name: this.normalizeOptionalText(row.town_name, 'town_name', 255), site_code: this.normalizeOptionalText(row.site_code, 'site_code', 255), product_type: this.normalizeOptionalText(row.product_type, 'product_type', 50), shop_name: this.normalizeOptionalText(row.shop_name, 'shop_name', 255), express, express_name: express ? express.name : null, express_polyapi_extra_info: express ? express.polyapi_extra_info : null, express_pdd_code: express ? express.pdd_code : null, }; if (includeSystemExpressFlag) { normalizedRow.is_system_express_code = this.resolveIsSystemExpressCodeFlag(row, express); } return normalizedRow; } /** * 规范化快递接口的全量记录。 * * @param {Object} row 数据库记录 * @return {Object|null} 规范化后的全量记录 */ normalizeFullInterfaceRow(row) { if (!row || typeof row !== 'object') { return null; } const attributes = this.getInterfaceFullAttributes(); const normalized = {}; const keys = attributes.length > 0 ? attributes : Object.keys(row); for (const key of keys) { if (Object.prototype.hasOwnProperty.call(row, key)) { normalized[key] = this.clonePlainValue(row[key]); } } if (Object.prototype.hasOwnProperty.call(row, 'express')) { normalized.express = this.clonePlainValue(row.express); } if (Object.prototype.hasOwnProperty.call(row, 'shop')) { normalized.shop = this.clonePlainValue(row.shop); } return normalized; } /** * 判断缓存中的仓库平台快递接口数据是否包含店铺联查字段。 * * @param {Array} rows 快递接口列表 * @return {boolean} 是否可直接使用缓存 */ hasWarehousePlatformShopData(rows) { if (!Array.isArray(rows) || rows.length === 0) { return true; } return rows.every(row => { if (!row || typeof row !== 'object') { return false; } if (!Object.prototype.hasOwnProperty.call(row, 'shop_id')) { return true; } const shopId = row.shop_id; if (shopId === null || shopId === undefined) { return true; } return Object.prototype.hasOwnProperty.call(row, 'shop'); }); } /** * 规范化快递接口的全量记录数组,并按 weight / id 排序。 * * @param {Array|Object} rows 数据库记录数组或单条记录 * @return {Array} 规范化后的全量记录数组 */ normalizeFullInterfaceRows(rows) { const sourceRows = Array.isArray(rows) ? rows : rows ? [ rows ] : []; return sourceRows .map(row => this.normalizeFullInterfaceRow(row)) .filter(row => row) .sort((left, right) => { const leftWeight = left.weight === undefined || left.weight === null ? Number.POSITIVE_INFINITY : Number(left.weight); const rightWeight = right.weight === undefined || right.weight === null ? Number.POSITIVE_INFINITY : Number(right.weight); if (leftWeight !== rightWeight) { return leftWeight - rightWeight; } const leftId = left.id === undefined || left.id === null ? Number.POSITIVE_INFINITY : Number(left.id); const rightId = right.id === undefined || right.id === null ? Number.POSITIVE_INFINITY : Number(right.id); return leftId - rightId; }); } /** * 解析仓库与平台代码查询条件。 * * @param {Object} data 请求参数 * @return {Object} 归一化后的仓库与平台信息 */ resolveWarehousePlatformTarget(data = {}) { const warehouseValue = data.warehouse_id !== undefined ? data.warehouse_id : data.warehouseId; const platformValue = data.platform_code !== undefined ? data.platform_code : data.platformCode; const warehouseId = warehouseValue === undefined ? this.getCurrentStoreId() : this.normalizeInteger(warehouseValue, 'warehouse_id', { min: 1 }); const platformCode = this.normalizePlatformCode(platformValue, 'platform_code', 20); return { warehouseId, platformCode, }; } /** * 查找当前仓库下的快递接口记录。 * * @param {number} id 接口 ID * @return {Promise} 接口记录 */ async findInterfaceById(id) { const { ctx } = this; const currentStoreId = this.getCurrentStoreId(); const setting = await ctx.model.ExpressInterface.findOne({ where: { id, warehouse_id: currentStoreId, }, include: this.getInterfaceInclude(), }); if (!setting) { throw this.createError('快递接口不存在或无权限操作', 404); } return setting; } /** * 查找同仓下的快递编码冲突记录。 * * @param {string} expressCode 快递编码 * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 冲突记录 */ async findCodeConflict(expressCode, excludeId = null) { const { ctx, app } = this; const { Op } = app.Sequelize; const where = { warehouse_id: this.getCurrentStoreId(), express_code: expressCode, }; const normalizedExcludeId = Number(excludeId || 0); if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { where.id = { [Op.ne]: normalizedExcludeId, }; } return await ctx.model.ExpressInterface.findOne({ where, attributes: [ 'id', 'express_code' ], include: this.getInterfaceInclude(), }); } /** * 查找同仓下的平台接口冲突记录。 * * @param {string} platformCode 平台代码 * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 冲突记录 */ async findInterfaceConflict(platformCode, excludeId = null) { const { ctx, app } = this; const { Op } = app.Sequelize; const where = { warehouse_id: this.getCurrentStoreId(), platform_code: platformCode, }; const normalizedExcludeId = Number(excludeId || 0); if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { where.id = { [Op.ne]: normalizedExcludeId, }; } return await ctx.model.ExpressInterface.findOne({ where, attributes: [ 'id', 'platform_code' ], include: this.getInterfaceInclude(), }); } /** * 校验快递编码是否可用。 * * @param {string} expressCode 快递编码 * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 是否可用 */ async ensureCodeAvailable(expressCode, excludeId = null) { const conflict = await this.findCodeConflict(expressCode, excludeId); if (conflict) { throw this.createError('快递编码已被当前仓库使用', 409); } return true; } /** * 校验平台接口组合是否可用。 * * @param {string} platformCode 平台代码 * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 是否可用 */ async ensureInterfaceAvailable(platformCode, excludeId = null) { const conflict = await this.findInterfaceConflict(platformCode, excludeId); if (conflict) { throw this.createError('当前平台和快递接口组合已被使用', 409); } return true; } /** * 获取快递接口列表。 * * @param {Object} data 请求参数 * @param {Object} [data.pagination] 分页参数 * @return {Promise} 分页结果 */ async list(data = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; const currentStoreId = this.getCurrentStoreId(); const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; const pageSource = pagination.page !== undefined ? pagination.page : data.page; const pageSizeSource = pagination.pageSize !== undefined ? pagination.pageSize : (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize)); const page = this.normalizePage(pageSource, 'page', 1, 1000000); const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200); const offset = (page - 1) * pageSize; const { normalizedWhere, parsedResult } = this.resolveListWhere(data); const andConditions = [ { warehouse_id: currentStoreId, }, ]; const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []; if (dynamicConditions.length > 0) { andConditions.push({ [Op.and]: dynamicConditions }); } const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) || normalizedWhere.quickWhere || null; const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' ? quickWhereInput.value : quickWhereInput; if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { const keyword = String(quickWhereValue).trim(); andConditions.push({ [Op.or]: [ { name: { [Op.like]: `%${keyword}%` } }, { express_code: { [Op.like]: `%${keyword}%` } }, { platform_code: { [Op.like]: `%${keyword}%` } }, { sender_name: { [Op.like]: `%${keyword}%` } }, { sender_tel: { [Op.like]: `%${keyword}%` } }, { viewer: { [Op.like]: `%${keyword}%` } }, { client_id: { [Op.like]: `%${keyword}%` } }, { province_name: { [Op.like]: `%${keyword}%` } }, { city_name: { [Op.like]: `%${keyword}%` } }, { district_name: { [Op.like]: `%${keyword}%` } }, { site_code: { [Op.like]: `%${keyword}%` } }, { product_type: { [Op.like]: `%${keyword}%` } }, { brandno: { [Op.like]: `%${keyword}%` } }, { shop_name: { [Op.like]: `%${keyword}%` } }, ], }); } const result = await ctx.model.ExpressInterface.findAndCountAll({ where: { [Op.and]: andConditions, }, include: this.getInterfaceInclude(), attributes: [ 'id', 'name', 'express_code', 'warehouse_id', 'shop_id', 'platform_shop_id', 'template_id', 'paymode', 'brandno', 'providertype', 'providerid', 'platform_code', 'sys_express_code', 'sender_name', 'sender_tel', 'weight', 'viewer', 'client_id', 'is_share', 'province_name', 'city_name', 'district_name', 'site_code', 'product_type', 'weight_type', 'shop_name', 'address', 'town_name', 'ispickup', 'shipperno', 'template_url', 'ext_data', ], order: [[ 'weight', 'ASC' ], [ 'id', 'DESC' ]], offset, limit: pageSize, distinct: true, }); const list = Array.isArray(result && result.rows) ? result.rows.map(row => this.normalizeInterfaceRow( row && typeof row.get === 'function' ? row.get({ plain: true }) : row, { includeSystemExpressFlag: true } )).filter(Boolean) : []; return { code: 200, data: { list, total: Number(result && result.count ? result.count : 0), page, page_size: pageSize, }, }; } /** * 按仓库和平台代码查询快递接口全量记录。 * * 该方法会先尝试读取缓存;缓存未命中时查库并回写缓存。 * * @param {Object} data 请求参数 * @return {Promise} 查询结果,data 为快递接口数组 */ async listByWarehousePlatformCode(data = {}) { const { ctx, app } = this; const { warehouseId, platformCode } = this.resolveWarehousePlatformTarget(data); const cacheKey = this.getWarehousePlatformCacheKey(warehouseId, platformCode); if (app && typeof app.getCacheAsync === 'function') { try { const cachedValue = await app.getCacheAsync(cacheKey); if (cachedValue !== null && cachedValue !== undefined) { const normalizedCached = this.normalizeFullInterfaceRows(cachedValue); if (this.hasWarehousePlatformShopData(normalizedCached)) { return { code: 200, data: normalizedCached, }; } } } catch (error) { if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') { this.ctx.logger.warn('[SettingExpressInterfaceService.listByWarehousePlatformCode] 读取缓存失败', { error: error.message, cacheKey, }); } } } console.log('查询入参', warehouseId, platformCode); const settings = await ctx.model.ExpressInterface.findAll({ where: { warehouse_id: warehouseId, platform_code: platformCode, }, include: this.getInterfaceInclude({ full: true }), attributes: this.getInterfaceFullAttributes(), order: [[ 'weight', 'ASC' ], [ 'id', 'ASC' ]], }); const plainSettings = Array.isArray(settings) ? settings.map(setting => (setting && typeof setting.get === 'function' ? setting.get({ plain: true }) : setting)) : []; const normalized = this.normalizeFullInterfaceRows(plainSettings); if (normalized && app && typeof app.setCacheAsync === 'function') { try { await app.setCacheAsync(cacheKey, normalized, DEFAULT_CACHE_TTL_SECONDS); } catch (error) { if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') { this.ctx.logger.warn('[SettingExpressInterfaceService.listByWarehousePlatformCode] 写入缓存失败', { error: error.message, cacheKey, }); } } } return { code: 200, data: normalized, }; } /** * 创建快递接口。 * * @param {Object} data 请求参数 * @return {Promise} 创建结果 */ async create(data = {}) { const { ctx } = this; const currentStoreId = this.getCurrentStoreId(); const name = this.normalizeText(data.name, 'name', 255); const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase(); const platformCode = await this.ensurePrintPlatformExists( data.platform_code !== undefined ? data.platform_code : data.platformCode ); if (!name) { throw this.createError('name 参数不能为空', 400); } if (!expressCode) { throw this.createError('express_code 参数不能为空', 400); } if (!platformCode) { throw this.createError('platform_code 参数不能为空', 400); } const sysExpressCode = await this.resolveSysExpressCode({ expressCode, platformCode, sysExpressCode: data.sys_express_code !== undefined ? data.sys_express_code : data.sysExpressCode, }); const payload = { warehouse_id: currentStoreId, name, express_code: expressCode, platform_code: platformCode, sys_express_code: sysExpressCode, shop_id: this.normalizeInteger(data.shop_id !== undefined ? data.shop_id : data.shopId, 'shop_id', { allowEmpty: true, min: 1, }), template_id: (() => { const normalizedTemplateId = this.normalizeOptionalText( data.template_id !== undefined ? data.template_id : data.templateId, 'template_id', 50 ); return normalizedTemplateId === '' ? null : normalizedTemplateId; })(), paymode: this.normalizeInteger(data.paymode !== undefined ? data.paymode : data.payMode, 'paymode', { allowEmpty: true, }), brandno: (() => { const normalizedBrandNo = this.normalizeOptionalText( data.brandno !== undefined ? data.brandno : data.brandNo, 'brandno', 255 ); return normalizedBrandNo === '' ? null : normalizedBrandNo; })(), providertype: (() => { const normalizedProviderType = this.normalizeOptionalText( data.providertype !== undefined ? data.providertype : data.providerType, 'providertype', 50 ); return normalizedProviderType === '' ? null : normalizedProviderType; })(), providerid: this.normalizeInteger(data.providerid !== undefined ? data.providerid : data.providerId, 'providerid', { allowEmpty: true, }), sender_name: this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50), sender_tel: this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11), weight: this.normalizeInteger(data.weight, 'weight', { allowEmpty: true, }), weight_type: this.normalizeInteger(data.weight_type !== undefined ? data.weight_type : data.weightType, 'weight_type', { allowEmpty: true, }), viewer: this.normalizeOptionalText(data.viewer, 'viewer', 50), client_id: this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50), ispickup: this.normalizeFlag(data.ispickup !== undefined ? data.ispickup : data.isPickup, 'ispickup', 0), shipperno: this.normalizeOptionalText(data.shipperno !== undefined ? data.shipperno : data.shipperNo, 'shipperno', 255), template_url: this.normalizeOptionalText(data.template_url !== undefined ? data.template_url : data.templateUrl, 'template_url', 500), ext_data: this.normalizeOptionalJson(data.ext_data !== undefined ? data.ext_data : data.extData, 'ext_data'), province_name: this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255), city_name: this.normalizeOptionalText(data.city_name || data.cityName, 'city_name', 255), district_name: this.normalizeOptionalText(data.district_name || data.districtName, 'district_name', 255), address: this.normalizeOptionalText(data.address, 'address', 255), town_name: this.normalizeOptionalText(data.town_name || data.townName, 'town_name', 255), site_code: this.normalizeOptionalText(data.site_code || data.siteCode, 'site_code', 255), product_type: this.normalizeOptionalText(data.product_type || data.productType, 'product_type', 50), shop_name: this.normalizeOptionalText(data.shop_name || data.shopName, 'shop_name', 255), }; const created = await ctx.model.ExpressInterface.create(payload); const plainCreatedRow = created && typeof created.get === 'function' ? created.get({ plain: true }) : created; const createdSetting = await this.findInterfaceById(Number(plainCreatedRow && plainCreatedRow.id)); const plainCreated = createdSetting && typeof createdSetting.get === 'function' ? createdSetting.get({ plain: true }) : createdSetting; await this.clearWarehousePlatformCache(currentStoreId, payload.platform_code); return { code: 200, data: this.normalizeInterfaceRow(plainCreated), }; } /** * 修改快递接口。 * * @param {Object} data 请求参数 * @return {Promise} 修改结果 */ async update(data = {}) { const id = Number(data.id || data.interface_id || data.interfaceId || 0); if (!Number.isInteger(id) || id <= 0) { throw this.createError('id 参数不能为空', 400); } const setting = await this.findInterfaceById(id); const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); const hasExpressCode = Object.prototype.hasOwnProperty.call(data, 'express_code') || Object.prototype.hasOwnProperty.call(data, 'expressCode'); const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code') || Object.prototype.hasOwnProperty.call(data, 'platformCode'); const hasSysExpressCode = Object.prototype.hasOwnProperty.call(data, 'sys_express_code') || Object.prototype.hasOwnProperty.call(data, 'sysExpressCode'); const hasSenderName = Object.prototype.hasOwnProperty.call(data, 'sender_name') || Object.prototype.hasOwnProperty.call(data, 'senderName'); const hasSenderTel = Object.prototype.hasOwnProperty.call(data, 'sender_tel') || Object.prototype.hasOwnProperty.call(data, 'senderTel'); const hasWeight = Object.prototype.hasOwnProperty.call(data, 'weight'); const hasWeightType = Object.prototype.hasOwnProperty.call(data, 'weight_type') || Object.prototype.hasOwnProperty.call(data, 'weightType'); const hasShopId = Object.prototype.hasOwnProperty.call(data, 'shop_id') || Object.prototype.hasOwnProperty.call(data, 'shopId'); const hasPlatformShopId = Object.prototype.hasOwnProperty.call(data, 'platform_shop_id') || Object.prototype.hasOwnProperty.call(data, 'platformShopId'); const hasTemplateId = Object.prototype.hasOwnProperty.call(data, 'template_id') || Object.prototype.hasOwnProperty.call(data, 'templateId'); const hasPaymode = Object.prototype.hasOwnProperty.call(data, 'paymode') || Object.prototype.hasOwnProperty.call(data, 'payMode'); const hasBrandNo = Object.prototype.hasOwnProperty.call(data, 'brandno') || Object.prototype.hasOwnProperty.call(data, 'brandNo'); const hasProviderType = Object.prototype.hasOwnProperty.call(data, 'providertype') || Object.prototype.hasOwnProperty.call(data, 'providerType'); const hasProviderId = Object.prototype.hasOwnProperty.call(data, 'providerid') || Object.prototype.hasOwnProperty.call(data, 'providerId'); const hasViewer = Object.prototype.hasOwnProperty.call(data, 'viewer'); const hasClientId = Object.prototype.hasOwnProperty.call(data, 'client_id') || Object.prototype.hasOwnProperty.call(data, 'clientId'); const hasIsPickup = Object.prototype.hasOwnProperty.call(data, 'ispickup') || Object.prototype.hasOwnProperty.call(data, 'isPickup'); const hasShipperNo = Object.prototype.hasOwnProperty.call(data, 'shipperno') || Object.prototype.hasOwnProperty.call(data, 'shipperNo'); const hasTemplateUrl = Object.prototype.hasOwnProperty.call(data, 'template_url') || Object.prototype.hasOwnProperty.call(data, 'templateUrl'); const hasProvinceName = Object.prototype.hasOwnProperty.call(data, 'province_name') || Object.prototype.hasOwnProperty.call(data, 'provinceName'); const hasCityName = Object.prototype.hasOwnProperty.call(data, 'city_name') || Object.prototype.hasOwnProperty.call(data, 'cityName'); const hasDistrictName = Object.prototype.hasOwnProperty.call(data, 'district_name') || Object.prototype.hasOwnProperty.call(data, 'districtName'); const hasAddress = Object.prototype.hasOwnProperty.call(data, 'address'); const hasTownName = Object.prototype.hasOwnProperty.call(data, 'town_name') || Object.prototype.hasOwnProperty.call(data, 'townName'); const hasSiteCode = Object.prototype.hasOwnProperty.call(data, 'site_code') || Object.prototype.hasOwnProperty.call(data, 'siteCode'); const hasProductType = Object.prototype.hasOwnProperty.call(data, 'product_type') || Object.prototype.hasOwnProperty.call(data, 'productType'); const hasShopName = Object.prototype.hasOwnProperty.call(data, 'shop_name') || Object.prototype.hasOwnProperty.call(data, 'shopName'); const hasExtData = Object.prototype.hasOwnProperty.call(data, 'ext_data') || Object.prototype.hasOwnProperty.call(data, 'extData'); if (!hasName && !hasExpressCode && !hasPlatformCode && !hasSysExpressCode && !hasSenderName && !hasSenderTel && !hasWeight && !hasWeightType && !hasShopId && !hasPlatformShopId && !hasTemplateId && !hasPaymode && !hasBrandNo && !hasProviderType && !hasProviderId && !hasViewer && !hasClientId && !hasIsPickup && !hasShipperNo && !hasTemplateUrl && !hasProvinceName && !hasCityName && !hasDistrictName && !hasAddress && !hasTownName && !hasSiteCode && !hasProductType && !hasShopName && !hasExtData) { throw this.createError('至少需要提供一个可更新字段', 400); } const updates = {}; let nextExpressCode = setting.express_code || ''; let nextPlatformCode = setting.platform_code || ''; if (hasName) { const name = this.normalizeText(data.name, 'name', 255); if (!name) { throw this.createError('name 参数不能为空', 400); } updates.name = name; } if (hasExpressCode) { const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase(); if (!expressCode) { throw this.createError('express_code 参数不能为空', 400); } nextExpressCode = expressCode; updates.express_code = expressCode; } if (hasPlatformCode) { const platformCode = this.normalizePlatformCode( data.platform_code !== undefined ? data.platform_code : data.platformCode, 'platform_code', 20 ); if (!platformCode) { throw this.createError('platform_code 参数不能为空', 400); } nextPlatformCode = platformCode; updates.platform_code = platformCode; } nextPlatformCode = await this.ensurePrintPlatformExists(nextPlatformCode); if (Object.prototype.hasOwnProperty.call(updates, 'platform_code')) { updates.platform_code = nextPlatformCode; } if (hasSenderName) { updates.sender_name = this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50); } if (hasSenderTel) { updates.sender_tel = this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11); } if (hasWeight) { updates.weight = this.normalizeInteger(data.weight, 'weight', { allowEmpty: true, }); } if (hasWeightType) { updates.weight_type = this.normalizeInteger(data.weight_type !== undefined ? data.weight_type : data.weightType, 'weight_type', { allowEmpty: true, }); } if (hasShopId) { const normalizedShopId = this.normalizeInteger(data.shop_id !== undefined ? data.shop_id : data.shopId, 'shop_id', { allowEmpty: true, min: 1, }); const shopBinding = await this.resolveShopBinding(normalizedShopId); updates.shop_id = shopBinding.shopId; updates.token = shopBinding.token; } if (hasPlatformShopId) { updates.platform_shop_id = this.normalizeInteger( data.platform_shop_id !== undefined ? data.platform_shop_id : data.platformShopId, 'platform_shop_id', { allowEmpty: true, min: 1, } ); } if (hasTemplateId) { const normalizedTemplateId = this.normalizeOptionalText( data.template_id !== undefined ? data.template_id : data.templateId, 'template_id', 50 ); updates.template_id = normalizedTemplateId === '' ? null : normalizedTemplateId; } if (hasPaymode) { updates.paymode = this.normalizeInteger( data.paymode !== undefined ? data.paymode : data.payMode, 'paymode', { allowEmpty: true, } ); } if (hasBrandNo) { const normalizedBrandNo = this.normalizeOptionalText( data.brandno !== undefined ? data.brandno : data.brandNo, 'brandno', 255 ); updates.brandno = normalizedBrandNo === '' ? null : normalizedBrandNo; } if (hasProviderType) { const normalizedProviderType = this.normalizeOptionalText( data.providertype !== undefined ? data.providertype : data.providerType, 'providertype', 50 ); updates.providertype = normalizedProviderType === '' ? null : normalizedProviderType; } if (hasProviderId) { updates.providerid = this.normalizeInteger( data.providerid !== undefined ? data.providerid : data.providerId, 'providerid', { allowEmpty: true, } ); } if (hasViewer) { updates.viewer = this.normalizeOptionalText(data.viewer, 'viewer', 50); } if (hasClientId) { updates.client_id = this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50); } if (hasIsPickup) { updates.ispickup = this.normalizeFlag(data.ispickup !== undefined ? data.ispickup : data.isPickup, 'ispickup', 0); } if (hasShipperNo) { updates.shipperno = this.normalizeOptionalText(data.shipperno !== undefined ? data.shipperno : data.shipperNo, 'shipperno', 255); } if (hasTemplateUrl) { updates.template_url = this.normalizeOptionalText( data.template_url !== undefined ? data.template_url : data.templateUrl, 'template_url', 500 ); } if (hasProvinceName) { updates.province_name = this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255); } if (hasCityName) { updates.city_name = this.normalizeOptionalText(data.city_name || data.cityName, 'city_name', 255); } if (hasDistrictName) { updates.district_name = this.normalizeOptionalText(data.district_name || data.districtName, 'district_name', 255); } if (hasAddress) { updates.address = this.normalizeOptionalText(data.address, 'address', 255); } if (hasTownName) { updates.town_name = this.normalizeOptionalText(data.town_name || data.townName, 'town_name', 255); } if (hasSiteCode) { updates.site_code = this.normalizeOptionalText(data.site_code || data.siteCode, 'site_code', 255); } if (hasProductType) { updates.product_type = this.normalizeOptionalText(data.product_type || data.productType, 'product_type', 50); } if (hasShopName) { updates.shop_name = this.normalizeOptionalText(data.shop_name || data.shopName, 'shop_name', 255); } if (hasExtData) { updates.ext_data = this.normalizeOptionalJson( data.ext_data !== undefined ? data.ext_data : data.extData, 'ext_data' ); } if (hasExpressCode || hasPlatformCode || hasSysExpressCode) { updates.sys_express_code = await this.resolveSysExpressCode({ expressCode: nextExpressCode, platformCode: nextPlatformCode, sysExpressCode: hasSysExpressCode ? (data.sys_express_code !== undefined ? data.sys_express_code : data.sysExpressCode) : undefined, }); } const previousWarehouseId = Number(setting.warehouse_id || this.getCurrentStoreId()); const previousPlatformCode = this.normalizePlatformCode(setting.platform_code, 'platform_code', 20); const nextWarehouseId = previousWarehouseId; const nextCachePlatformCode = Object.prototype.hasOwnProperty.call(updates, 'platform_code') ? this.normalizePlatformCode(updates.platform_code, 'platform_code', 20) : previousPlatformCode; await setting.update(updates); await Promise.all(Array.from(new Set([ this.getWarehousePlatformCacheKey(previousWarehouseId, previousPlatformCode), this.getWarehousePlatformCacheKey(nextWarehouseId, nextCachePlatformCode), ])).map(cacheKey => this.deleteCacheByKey(cacheKey))); const refreshedSetting = await this.findInterfaceById(id); const plainSetting = refreshedSetting && typeof refreshedSetting.get === 'function' ? refreshedSetting.get({ plain: true }) : refreshedSetting; return { code: 200, data: this.normalizeInterfaceRow(plainSetting), }; } /** * 删除快递接口。 * * @param {Object} data 请求参数 * @return {Promise} 删除结果 */ async delete(data = {}) { const id = Number(data.id || data.interface_id || data.interfaceId || 0); if (!Number.isInteger(id) || id <= 0) { throw this.createError('id 参数不能为空', 400); } const setting = await this.findInterfaceById(id); const plainSetting = setting && typeof setting.get === 'function' ? setting.get({ plain: true }) : setting; await setting.destroy(); await this.clearWarehousePlatformCache(plainSetting.warehouse_id, plainSetting.platform_code); return { code: 200, data: { id: Number(plainSetting.id), warehouse_id: Number(plainSetting.warehouse_id), deleted: true, }, }; } } module.exports = SettingExpressInterfaceService;