'use strict'; const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); class SettingPlatformService 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; } /** * 归一化删除 ID 列表。 * * 优先读取 `ids`,其次兼容单个 `id`、`setting_id`、`settingId`。 * * @param {Object} data 请求参数 * @return {Array} 删除 ID 列表 */ normalizeDeleteIds(data = {}) { const { ids, id, setting_id: settingId, settingId: camelSettingId, } = data || {}; const rawIds = ids !== undefined ? ids : (id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId)); const values = Array.isArray(rawIds) ? rawIds : String(rawIds || '') .split(',') .map(item => item.trim()) .filter(Boolean); const normalizedIds = []; const seenIds = new Set(); for (const value of values) { const normalized = Number(value); if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { continue; } seenIds.add(normalized); normalizedIds.push(normalized); } return normalizedIds; } /** * 生成平台列表缓存键。 * * @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} platformCode 平台设置代码 * @param {number|string} warehouseId 仓库 ID * @return {string} 缓存键 */ getPlatformDetailCacheKey(platformCode, warehouseId) { return `platform_setting_detail:${platformCode}:${warehouseId}`; } /** * 生成平台存在性缓存键。 * * @param {string} platformCode 平台设置代码 * @param {number|string} warehouseId 仓库 ID * @return {string} 缓存键 */ getPlatformExistsCacheKey(platformCode, warehouseId) { return `platform:${platformCode}:${warehouseId}`; } /** * 删除指定缓存键。 * * @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 {Array} platformCodes 平台设置代码列表 * @return {Promise} */ async clearPlatformCaches(warehouseId, platformCodes = []) { const normalizedWarehouseId = Number(warehouseId || 0); const uniquePlatformCodes = Array.from(new Set( Array.isArray(platformCodes) ? platformCodes.map(code => String(code || '').trim()).filter(Boolean) : [] )); const cacheKeys = [ this.getPlatformListCacheKey(normalizedWarehouseId), ...uniquePlatformCodes.flatMap(platformCode => [ this.getPlatformDetailCacheKey(platformCode, normalizedWarehouseId), this.getPlatformExistsCacheKey(platformCode, normalizedWarehouseId), ]), ]; await Promise.all(cacheKeys.map(cacheKey => this.deleteCacheByKey(cacheKey))); } /** * 规范化必填文本。 * * @param {string|number} value 原始值 * @param {string} fieldName 字段名称 * @param {number} maxLength 最大长度 * @return {string} 规范化后的文本 */ normalizeRequiredText(value, fieldName, maxLength) { if (value === undefined || value === null) { throw this.createError(`${fieldName} 参数不能为空`, 400); } if (typeof value !== 'string' && typeof value !== 'number') { throw this.createError(`${fieldName} 参数类型不合法`, 400); } const normalized = String(value).trim(); if (!normalized) { throw this.createError(`${fieldName} 参数不能为空`, 400); } if (normalized.length > maxLength) { throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); } return normalized; } /** * 规范化可选文本。 * * @param {string|number} value 原始值 * @param {string} fieldName 字段名称 * @param {number} maxLength 最大长度 * @return {string|null} 规范化后的文本 */ normalizeOptionalText(value, fieldName, maxLength) { if (value === undefined || value === null) { return null; } if (typeof value !== 'string' && typeof value !== 'number') { throw this.createError(`${fieldName} 参数类型不合法`, 400); } const normalized = String(value).trim(); if (!normalized) { return null; } if (normalized.length > maxLength) { throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); } return normalized; } /** * 规范化整数。 * * @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} 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', }, code: { field: 'code', }, name: { field: 'name', }, platform_code: { field: 'platform_code', }, 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 {string} code 设置代码 * @param {string} platformName 平台名称 * @return {string} 展示标签 */ buildPlatformLabel(code, platformName) { const normalizedCode = String(code || '').trim(); const normalizedPlatformName = String(platformName || '').trim(); if (!normalizedCode) { return normalizedPlatformName; } if (!normalizedPlatformName) { return normalizedCode; } return `${normalizedCode} (${normalizedPlatformName})`; } /** * 规范化平台设置记录。 * * @param {Object} row 数据库记录 * @return {Object|null} 规范化后的记录 */ normalizePlatformRow(row) { if (!row || typeof row !== 'object') { return null; } const platform = row.platform && typeof row.platform === 'object' ? row.platform : null; const code = this.normalizeOptionalText(row.code, 'code', 50); if (!code) { return null; } const platformCode = this.normalizeOptionalText(row.platform_code, 'platform_code', 50) || this.normalizeOptionalText(platform && platform.code, 'platform_code', 50) || ''; const platformName = this.normalizeOptionalText( row.platform_name !== undefined ? row.platform_name : (platform && platform.name), 'platform_name', 255 ) || ''; const platformLabel = this.buildPlatformLabel(code, platformName); return { id: row.id === undefined || row.id === null ? null : Number(row.id), code, name: this.normalizeOptionalText(row.name, 'name', 100), platform_code: platformCode, warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), label: platformLabel, platform_name: platformName, platform_label: platformLabel, platform: platform ? { code: this.normalizeOptionalText(platform.code, 'platform.code', 50), name: this.normalizeOptionalText(platform.name, 'platform.name', 255), // 兼容历史返回结构:platform.platform_code 回退为平台 code。 platform_code: this.normalizeOptionalText(platform.code, 'platform.code', 50), } : null, }; } /** * 查找当前仓库下的平台设置记录。 * * @param {number} id 设置 ID * @return {Promise} 平台设置记录 */ async findSettingById(id) { const { ctx } = this; const currentStoreId = this.getCurrentStoreId(); const setting = await ctx.model.PlatformSetting.findOne({ where: { id, warehouse_id: currentStoreId, }, include: [ { model: ctx.model.Platform, as: 'platform', attributes: [ 'code', 'name' ], required: false, }, ], }); if (!setting) { throw this.createError('平台设置不存在或无权限操作', 404); } return setting; } /** * 查找同仓下的 code 冲突记录。 * * @param {string} code 设置代码 * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 冲突记录 */ async findCodeConflict(code, excludeId = null) { const { ctx, app } = this; const { Op } = app.Sequelize; const where = { warehouse_id: this.getCurrentStoreId(), code, }; const normalizedExcludeId = Number(excludeId || 0); if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { where.id = { [Op.ne]: normalizedExcludeId, }; } return await ctx.model.PlatformSetting.findOne({ where, attributes: [ 'id', 'code' ], }); } /** * 查找同仓下的平台代码冲突记录。 * * @param {string} platformCode 平台代码 * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 冲突记录 */ async findPlatformCodeConflict(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.PlatformSetting.findOne({ where, attributes: [ 'id', 'platform_code' ], }); } /** * 校验平台是否存在。 * * @param {string} platformCode 平台代码 * @return {Promise} 平台记录 */ async ensurePlatformExists(platformCode) { const { ctx } = this; const platform = await ctx.model.Platform.findOne({ where: { code: platformCode, }, attributes: [ 'code', 'name' ], }); if (!platform) { throw this.createError('platform_code 不存在或不支持', 400); } return platform; } /** * 校验 code 是否可用。 * * @param {string} code 设置代码 * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 是否可用 */ async ensureCodeAvailable(code, excludeId = null) { const conflict = await this.findCodeConflict(code, excludeId); if (conflict) { throw this.createError('code 已被当前仓库使用', 409); } return true; } /** * 校验平台代码是否可用。 * * @param {string} platformCode 平台代码 * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 是否可用 */ async ensurePlatformCodeAvailable(platformCode, excludeId = null) { const conflict = await this.findPlatformCodeConflict(platformCode, excludeId); if (conflict) { throw this.createError('platform_code 已被当前仓库使用', 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]: [ { code: { [Op.like]: `%${keyword}%` } }, { name: { [Op.like]: `%${keyword}%` } }, { platform_code: { [Op.like]: `%${keyword}%` } }, ], }); } const result = await ctx.model.PlatformSetting.findAndCountAll({ where: { [Op.and]: andConditions, }, include: [ { model: ctx.model.Platform, as: 'platform', attributes: [ 'code', 'name' ], required: false, }, ], attributes: [ 'id', 'code', 'name', 'platform_code', 'warehouse_id' ], order: [[ 'id', 'DESC' ]], offset, limit: pageSize, }); const list = Array.isArray(result && result.rows) ? result.rows.map(row => this.normalizePlatformRow(row && typeof row.get === 'function' ? row.get({ plain: true }) : row)).filter(Boolean) : []; const total = Array.isArray(result && result.count) ? result.count.length : Number(result && result.count ? result.count : 0); return { code: 200, data: { list, total, page, page_size: pageSize, }, }; } /** * 创建平台设置。 * * @param {Object} data 请求参数 * @return {Promise} 创建结果 */ async create(data = {}) { const { ctx } = this; const currentStoreId = this.getCurrentStoreId(); const code = this.normalizeRequiredText(data.code, 'code', 50); const name = this.normalizeRequiredText(data.name, 'name', 100); const platformCode = this.normalizeRequiredText(data.platform_code !== undefined ? data.platform_code : data.platformCode, 'platform_code', 50); const platform = await this.ensurePlatformExists(platformCode); await this.ensureCodeAvailable(code); await this.ensurePlatformCodeAvailable(platformCode); const created = await ctx.model.PlatformSetting.create({ warehouse_id: currentStoreId, code, name, platform_code: platformCode, }); const plainCreated = created && typeof created.get === 'function' ? created.get({ plain: true }) : created; return { code: 200, data: this.normalizePlatformRow({ ...plainCreated, platform, }), }; } /** * 修改平台设置。 * * @param {Object} data 请求参数 * @return {Promise} 修改结果 */ async update(data = {}) { const id = Number(data.id || data.setting_id || data.settingId || 0); if (!Number.isInteger(id) || id <= 0) { throw this.createError('id 参数不能为空', 400); } const setting = await this.findSettingById(id); const hasCode = Object.prototype.hasOwnProperty.call(data, 'code'); const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code') || Object.prototype.hasOwnProperty.call(data, 'platformCode'); if (!hasCode && !hasName && !hasPlatformCode) { throw this.createError('至少需要提供一个可更新字段', 400); } const updates = {}; let nextCode = setting.code || ''; let nextPlatformCode = setting.platform_code || ''; let platform = setting.platform || null; if (hasCode) { const code = this.normalizeRequiredText(data.code, 'code', 50); updates.code = code; nextCode = code; } if (hasName) { updates.name = this.normalizeRequiredText(data.name, 'name', 100); } if (hasPlatformCode) { const platformCode = this.normalizeRequiredText(data.platform_code !== undefined ? data.platform_code : data.platformCode, 'platform_code', 50); platform = await this.ensurePlatformExists(platformCode); updates.platform_code = platformCode; nextPlatformCode = platformCode; } if (Object.prototype.hasOwnProperty.call(updates, 'code')) { await this.ensureCodeAvailable(nextCode, id); } if (Object.prototype.hasOwnProperty.call(updates, 'platform_code')) { await this.ensurePlatformCodeAvailable(nextPlatformCode, id); } await setting.update(updates); const plainSetting = setting && typeof setting.get === 'function' ? setting.get({ plain: true }) : setting; return { code: 200, data: this.normalizePlatformRow({ ...plainSetting, platform, }), }; } /** * 删除平台设置。 * * @param {Object} data 请求参数 * @return {Promise} 删除结果 */ async delete(data = {}) { const ids = this.normalizeDeleteIds(data); if (!Array.isArray(ids) || ids.length === 0) { throw this.createError('ids 参数不能为空', 400); } const { ctx, app } = this; const currentStoreId = this.getCurrentStoreId(); const { Op } = app.Sequelize; const settings = await ctx.model.PlatformSetting.findAll({ where: { warehouse_id: currentStoreId, id: { [Op.in]: ids, }, }, attributes: [ 'id', 'code', 'warehouse_id' ], }); if (!Array.isArray(settings) || settings.length !== ids.length) { throw this.createError('平台设置不存在或无权限操作', 404); } await ctx.model.PlatformSetting.destroy({ where: { warehouse_id: currentStoreId, id: { [Op.in]: ids, }, }, }); await this.clearPlatformCaches( currentStoreId, settings.map(setting => setting && setting.code).filter(Boolean) ); const deletedIds = settings.map(setting => Number(setting.id)).filter(id => Number.isInteger(id) && id > 0); const responseData = { ids: deletedIds, warehouse_id: currentStoreId, deleted: true, }; if (deletedIds.length === 1) { responseData.id = deletedIds[0]; } return { code: 200, data: responseData, }; } } module.exports = SettingPlatformService;