// app/service/system/platform.js const Service = require('egg').Service; const DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS = 600; class PlatformService extends Service { /** * 获取当前上下文中的仓库ID。 * * @return {number} 仓库ID,未获取到时返回 0。 */ getCurrentWarehouseId() { const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); if (Number.isFinite(warehouseId) && warehouseId > 0) { return warehouseId; } return 0; } /** * 生成平台列表缓存键。 * * @param {number|string} warehouseId 仓库ID。 * @return {string} 缓存键。 */ getPlatformListCacheKey(warehouseId = 0) { const normalizedWarehouseId = Number(warehouseId || 0); if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { return `platform:list:${normalizedWarehouseId}`; } return 'platform:list'; } /** * 生成平台设置项展示名称。 * * @param {string} settingCode 平台设置编码。 * @param {Object} platformItem 系统平台项。 * @return {string} 展示名称。 */ buildMergedPlatformLabel(settingCode, platformItem) { const normalizedSettingCode = String(settingCode || '').trim(); const platformName = String(platformItem && (platformItem.name || platformItem.label || platformItem.code || platformItem.value) || '').trim(); if (!normalizedSettingCode) { return platformName; } if (!platformName) { return normalizedSettingCode; } return `${normalizedSettingCode} (${platformName})`; } /** * 规范化系统平台记录。 * * @param {Object} row 数据库记录。 * @return {Object|null} 规范化后的记录。 */ normalizePlatformRow(row) { if (!row || typeof row !== 'object') { return null; } const code = String(row.code || '').trim(); if (!code) { return null; } const name = String(row.name || '').trim(); const defaultExpressInterface = String(row.default_express_interface || '').trim(); return { code, name, default_express_interface: defaultExpressInterface, value: code, label: name || code, platform_code: code, platform_name: name, is_system_setting: false, }; } /** * 从数据库加载当前仓库的平台设置列表。 * * @param {number|string} warehouseId 仓库ID。 * @return {Promise} 平台设置列表。 */ async loadPlatformSettingListFromDatabase(warehouseId = 0) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { return []; } const platformSettingModel = this.ctx.model && this.ctx.model.PlatformSetting; if (!platformSettingModel || typeof platformSettingModel.findAll !== 'function') { return []; } const rows = await platformSettingModel.findAll({ attributes: [ 'id', 'code', 'platform_code', 'warehouse_id' ], where: { warehouse_id: normalizedWarehouseId, }, order: [[ 'code', 'ASC' ]], raw: true, }); if (!Array.isArray(rows)) { return []; } return rows; } /** * 规范化平台设置记录。 * * @param {Object} row 数据库记录。 * @param {Map} platformMap 系统平台映射。 * @return {Object|null} 规范化后的记录。 */ normalizePlatformSettingRow(row, platformMap) { if (!row || typeof row !== 'object') { return null; } const code = String(row.code || '').trim(); if (!code) { return null; } const platformCode = String(row.platform_code || '').trim(); const platformItem = platformMap instanceof Map ? platformMap.get(platformCode) : null; const label = this.buildMergedPlatformLabel(code, platformItem); return { code, name: label, value: code, label, is_system_setting: true, id: row.id === undefined || row.id === null ? null : row.id, alias: '', platform_code: String((platformItem && (platformItem.code || platformItem.value)) || platformCode || '').trim(), platform_name: String((platformItem && (platformItem.name || platformItem.label || platformItem.value)) || '').trim(), default_express_interface: String((platformItem && platformItem.default_express_interface) || '').trim(), }; } /** * 合并基础平台列表和平台设置列表。 * * @param {Array} platformList 系统平台列表。 * @param {Array} platformSettingList 平台设置列表。 * @return {Array} 合并后的平台列表。 */ buildMergedPlatformList(platformList, platformSettingList) { const mergedList = []; const seenCodeMap = new Set(); const normalizedPlatformList = Array.isArray(platformList) ? platformList : []; const platformMap = new Map(); for (const platformItem of normalizedPlatformList) { if (!platformItem || typeof platformItem !== 'object') { continue; } const code = String(platformItem.code || platformItem.value || '').trim(); if (!code) { continue; } if (!platformMap.has(code)) { platformMap.set(code, platformItem); } } for (const platformItem of normalizedPlatformList) { if (!platformItem || typeof platformItem !== 'object') { continue; } const code = String(platformItem.code || platformItem.value || '').trim(); if (!code || seenCodeMap.has(code)) { continue; } mergedList.push(platformItem); seenCodeMap.add(code); } for (const row of Array.isArray(platformSettingList) ? platformSettingList : []) { const mergedItem = this.normalizePlatformSettingRow(row, platformMap); if (!mergedItem || seenCodeMap.has(mergedItem.code)) { continue; } mergedList.push(mergedItem); seenCodeMap.add(mergedItem.code); } return mergedList; } async loadPlatformListFromDatabase() { const rows = await this.ctx.model.Platform.findAll({ attributes: [ 'code', 'name', 'default_express_interface' ], order: [[ 'code', 'ASC' ]], raw: true, }); if (!Array.isArray(rows)) { return []; } return rows .map(row => this.normalizePlatformRow(row)) .filter(Boolean); } /** * 获取平台列表。 * * 先读取系统平台,再按当前仓库合并平台设置;同一编码只保留一条记录。 * * @return {Promise} 平台列表。 */ async getPlatformList() { const warehouseId = this.getCurrentWarehouseId(); const cacheKey = this.getPlatformListCacheKey(warehouseId); try { const cachedList = await this.app.getCacheAsync(cacheKey); if (cachedList !== null && cachedList !== undefined) { return Array.isArray(cachedList) ? cachedList : []; } const [ platformList, platformSettingList ] = await Promise.all([ this.loadPlatformListFromDatabase(), this.loadPlatformSettingListFromDatabase(warehouseId), ]); const mergedList = this.buildMergedPlatformList(platformList, platformSettingList); await this.app.setCacheAsync(cacheKey, mergedList, DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS); return mergedList; } catch (error) { this.ctx.logger.error('[PlatformService.getPlatformList] 获取平台列表失败', { error: error.message, stack: error.stack, }); throw error; } } /** * 检查平台是否存在 * 逻辑: * 1. 先查询设置表,有对应的平台代码+仓库ID组合,返回关联的基础表的代码和名称 * 2. 如果没有,尝试基础表中的code是否匹配,存在匹配则直接返回基础表的代码和名称 * 3. 使用缓存优化性能 * @param {string} platformCode 平台代码 * @param {number} warehouseId 仓库ID * @return {Promise} 平台信息或null */ async checkPlatformExists(platformCode, warehouseId) { const { ctx, app } = this; // 生成缓存key const cacheKey = `platform:${platformCode}:${warehouseId}`; try { // 1. 先从缓存获取 const cachedData = await app.getCacheAsync(cacheKey); if (cachedData) { ctx.logger.info(`从缓存获取平台信息: ${cacheKey}`); // 如果缓存中存的是"不存在"的特殊标记,返回null if (cachedData === '__NOT_EXISTS__') { return null; } return cachedData; } ctx.logger.info(`${cacheKey}无缓存`); let platformInfo = null; // 2. 先查询平台设置表(关联基础平台表) const platformSetting = await app.model.PlatformSetting.findOne({ where: { code: platformCode, warehouse_id: warehouseId, }, include: [ { model: this.app.model.Platform, as: 'platform', attributes: [ 'code', 'name', 'default_express_interface' ], }, ], }); if (platformSetting && platformSetting.platform) { // 从设置表中找到,并且有关联的平台信息 platformInfo = { code: platformSetting.platform.code, name: platformSetting.platform.name, default_express_interface: platformSetting.platform.default_express_interface, source: 'setting', // 标记来源 setting_id: platformSetting.id, warehouse_id: warehouseId, }; } else { // 3. 设置表中没有,直接查询基础平台表 const basePlatform = await app.model.Platform.findOne({ where: { code: platformCode, }, attributes: [ 'code', 'name', 'default_express_interface' ], }); if (basePlatform) { platformInfo = { code: basePlatform.code, name: basePlatform.name, default_express_interface: basePlatform.default_express_interface, source: 'base', // 标记来源 warehouse_id: warehouseId, }; } } // 4. 设置缓存 if (platformInfo) { // 平台存在,缓存5分钟 await app.setCacheAsync(cacheKey, platformInfo, 300); ctx.logger.info(`平台信息已缓存: ${cacheKey}`); } else { // 平台不存在,缓存特殊标记,时间可以短一些(2分钟) await app.setCacheAsync(cacheKey, '__NOT_EXISTS__', 120); ctx.logger.info(`平台不存在标记已缓存: ${cacheKey}`); } return platformInfo; } catch (error) { ctx.logger.error(`检查平台存在性失败: ${error.message}`, { platformCode, warehouseId, error: error.stack, }); throw error; } } /** * 获取平台信息(带异常处理) * @param {string} platformCode 平台代码 * @param {number} warehouseId 仓库ID * @return {Promise} 平台信息 * @throws {Error} 平台不存在时抛出异常 */ async getPlatformInfo(platformCode, warehouseId) { const platformInfo = await this.checkPlatformExists(platformCode, warehouseId); if (!platformInfo) { throw new Error(`平台 ${platformCode} 在仓库 ${warehouseId} 中不存在`); } return platformInfo; } /** * 清除平台缓存 * @param {string} platformCode 平台代码 * @param {number} warehouseId 仓库ID */ async clearPlatformCache(platformCode, warehouseId) { const { app } = this; const cacheKey = `platform:${platformCode}:${warehouseId}`; await app.setCacheAsync(cacheKey, null, 0); // 立即过期 } /** * 获取平台设置详情(包括完整的设置信息) * @param {string} platformCode 平台代码 * @param {number} warehouseId 仓库ID * @return {Promise} 平台设置详情 */ async getPlatformSettingDetail(platformCode, warehouseId) { const cacheKey = `platform_setting_detail:${platformCode}:${warehouseId}`; try { // 从缓存获取 const cachedData = await this.app.getCacheAsync(cacheKey); if (cachedData) { return cachedData === '__NOT_EXISTS__' ? null : cachedData; } const setting = await this.app.model.PlatformSetting.findOne({ where: { code: platformCode, warehouse_id: warehouseId, }, include: [ { model: this.app.model.Platform, as: 'platform', attributes: [ 'code', 'name', 'default_express_interface' ], }, ], }); if (setting) { const result = { id: setting.id, platform_code: setting.platform_code, code: setting.code, warehouse_id: setting.warehouse_id, platform: setting.platform, warehouse: setting.warehouse, }; // 缓存10分钟 await this.app.setCacheAsync(cacheKey, result, 600); return result; } // 缓存2分钟的不存在标记 await this.app.setCacheAsync(cacheKey, '__NOT_EXISTS__', 120); return null; } catch (error) { this.ctx.logger.error(`获取平台设置详情失败: ${error.message}`); throw error; } } /** * 批量检查多个平台 * @param {Array} platformWarehouseList 平台和仓库列表 [{platformCode, warehouseId}, ...] * @return {Promise} 存在的平台列表 */ async batchCheckPlatforms(platformWarehouseList) { const results = []; for (const item of platformWarehouseList) { const { platformCode, warehouseId } = item; const exists = await this.checkPlatformExists(platformCode, warehouseId); if (exists) { results.push({ platformCode, warehouseId, exists: true, info: exists, }); } else { results.push({ platformCode, warehouseId, exists: false, info: null, }); } } return results; } /** * 创建平台设置 * @param {Object} data 平台设置数据 * @param {string} data.platform_code 平台代码 * @param {string} data.code 设置代码 * @param {number} data.warehouse_id 仓库ID * @return {Promise} 创建的设置 */ async createPlatformSetting(data) { const { ctx } = this; try { // 1. 验证平台是否存在 const platform = await this.app.model.Platform.findOne({ where: { code: data.platform_code }, }); if (!platform) { throw new Error(`平台 ${data.platform_code} 不存在`); } // 2. 验证仓库是否存在 const warehouse = await this.app.model.Store.findOne({ where: { id: data.warehouse_id }, }); if (!warehouse) { throw new Error(`仓库 ${data.warehouse_id} 不存在`); } // 3. 检查是否已存在相同的设置 const exists = await this.app.model.PlatformSetting.findOne({ where: { platform_code: data.platform_code, warehouse_id: data.warehouse_id, }, }); if (exists) { throw new Error(`平台 ${data.platform_code} 在仓库 ${data.warehouse_id} 中已存在设置`); } // 4. 创建设置 const setting = await this.app.model.PlatformSetting.create(data); // 5. 清除相关缓存 await this.clearPlatformCache(data.platform_code, data.warehouse_id); return setting; } catch (error) { ctx.logger.error(`创建平台设置失败: ${error.message}`); throw error; } } } module.exports = PlatformService;