'use strict'; const Service = require('egg').Service; class AccountPlatformService extends Service { getActiveInclude(ctx) { return [ { model: ctx.model.AccountStoreEmployee, as: 'accountStoreEmployee', where: { status: 1 }, required: true, include: [ { model: ctx.model.EmployeeRole, as: 'employeeRoles', required: false, attributes: [ 'id', 'employee_id', 'role_id' ], include: [ { model: ctx.model.Role, as: 'role', attributes: [ 'id', 'name', 'code', 'permissions', 'description' ], }, ], }, { model: ctx.model.Store, as: 'store', attributes: [ 'id', 'name', 'code' ], }, ], }, ]; } getPrimaryRoleBinding(accountStoreEmployee) { const bindings = Array.isArray(accountStoreEmployee?.employeeRoles) ? accountStoreEmployee.employeeRoles : []; return bindings.length > 0 ? bindings[0] : null; } formatActiveContext(platformActive) { if (!platformActive || !platformActive.accountStoreEmployee) { return null; } const employee = platformActive.accountStoreEmployee; const roleBinding = this.getPrimaryRoleBinding(employee); const role = roleBinding?.role || null; const store = employee.store || null; return { account_id: platformActive.account_id, platform_code: platformActive.platform_code, role_id: roleBinding ? roleBinding.role_id : null, role_name: role ? role.name : '', role_code: role ? role.code : '', role_permissions: role ? this.ctx.service.systems.auth.rolePermission.toApiPermissionIds(role.permissions) : [], store_id: employee.store_id, store_name: store ? store.name : '', store_code: store ? store.code : '', created_at: platformActive.created_at, updated_at: platformActive.updated_at, }; } /** * 切换平台激活角色 * @param {number} accountId - 账号ID * @param {number} accountStoreRoleId - 账号仓库员工关联ID(保持历史参数名兼容) * @param {string} platformCode - 平台编码 * @return {Promise} */ async switchActiveRole(accountId, accountStoreRoleId, platformCode) { const { ctx } = this; // 使用事务确保数据一致性 const transaction = await ctx.model.transaction(); try { // 1. 验证员工关联的有效性 const accountStoreEmployee = await ctx.model.AccountStoreEmployee.findOne({ where: { id: accountStoreRoleId, account_id: accountId, status: 1, }, transaction, }); if (!accountStoreEmployee) { throw new Error('角色关联不存在或已失效'); } const existingActive = await ctx.model.AccountPlatformActive.findOne({ where: { account_id: accountId, platform_code: platformCode, }, transaction, }); // 2. 使用 upsert 切换激活角色 await ctx.model.AccountPlatformActive.upsert({ account_id: accountId, employee_id: accountStoreRoleId, platform_code: platformCode, }, { transaction, }); const platformActive = await ctx.model.AccountPlatformActive.findOne({ where: { account_id: accountId, platform_code: platformCode, }, transaction, }); await transaction.commit(); // 3. 清理缓存 await this.clearPlatformCache(accountId, platformCode); return { success: true, created: !existingActive, data: platformActive, }; } catch (error) { await transaction.rollback(); // 处理唯一约束冲突 if (error.name === 'SequelizeUniqueConstraintError') { // 如果是 employee_id 和 platform_code 冲突,说明同一个平台不能关联到不同账号 if (error.errors && error.errors.some(e => e.path === 'uk_account_store_role_platform')) { throw new Error('该角色已被其他账号在同一平台激活'); } throw new Error('平台激活状态更新失败,可能存在数据冲突'); } throw error; } } /** * 获取平台当前激活角色 * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 * @param {boolean} useCache - 是否使用缓存 * @return {Promise} */ async getActiveRoleByPlatform(accountId, platformCode, useCache = true) { const { ctx, app } = this; const cacheKey = `platform_active:${accountId}:${platformCode}`; // 尝试从缓存获取 if (useCache) { try { const cached = await app.getCacheAsync(cacheKey); if (cached) { return cached; } } catch (error) { console.warn('获取平台激活缓存失败:', error.message); } } // 查询数据库 const platformActive = await ctx.model.AccountPlatformActive.findOne({ where: { account_id: accountId, platform_code: platformCode, }, include: this.getActiveInclude(ctx), }); if (!platformActive) { return null; } // 整理返回数据 const result = this.formatActiveContext(platformActive); // 缓存结果 if (useCache) { try { await app.setCacheAsync(cacheKey, result, 1800); // 缓存30分钟 } catch (error) { console.warn('缓存平台激活状态失败:', error.message); } } return result; } /** * 批量获取账号在多个平台的激活状态 * @param {number} accountId - 账号ID * @param {Array} platformCodes - 平台编码数组 * @return {Promise} */ async getMultiplePlatformActiveRoles(accountId, platformCodes) { const { ctx } = this; const platformActives = await ctx.model.AccountPlatformActive.findAll({ where: { account_id: accountId, platform_code: platformCodes, }, include: this.getActiveInclude(ctx), }); // 转换为平台编码为key的对象 const result = {}; platformActives.forEach(active => { const context = this.formatActiveContext(active); result[active.platform_code] = { role_id: context ? context.role_id : null, role_name: context ? context.role_name : '', role_code: context ? context.role_code : '', store_id: context ? context.store_id : null, store_name: context ? context.store_name : '', store_code: context ? context.store_code : '', created_at: context ? context.created_at : active.created_at, updated_at: context ? context.updated_at : active.updated_at, }; }); // 填充未设置的平台 platformCodes.forEach(code => { if (!result[code]) { result[code] = null; } }); return result; } /** * 获取账号所有平台的激活状态 * @param {number} accountId - 账号ID * @return {Promise} */ async getAllPlatformActives(accountId) { const { ctx } = this; const platformActives = await ctx.model.AccountPlatformActive.findAll({ where: { account_id: accountId }, include: this.getActiveInclude(ctx), order: [[ 'platform_code', 'ASC' ]], }); return platformActives.map(active => { const context = this.formatActiveContext(active); return { platform_code: active.platform_code, role_id: context ? context.role_id : null, role_name: context ? context.role_name : '', role_code: context ? context.role_code : '', store_id: context ? context.store_id : null, store_name: context ? context.store_name : '', store_code: context ? context.store_code : '', created_at: active.created_at, updated_at: active.updated_at, }; }); } /** * 清除平台激活状态 * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 * @return {Promise} */ async clearPlatformActive(accountId, platformCode) { const { ctx, app } = this; try { const result = await ctx.model.AccountPlatformActive.destroy({ where: { account_id: accountId, platform_code: platformCode, }, }); // 清理缓存 await this.clearPlatformCache(accountId, platformCode); return result > 0; } catch (error) { throw error; } } /** * 清理平台缓存 * @param accountId * @param platformCode * @private */ async clearPlatformCache(accountId, platformCode) { const { app } = this; const cacheKey = `platform_active:${accountId}:${platformCode}`; try { await app.setCacheAsync(cacheKey, null, 0); } catch (error) { console.warn('清理平台缓存失败:', error.message); } } /** * 获取账号可用的角色列表 * @param {number} accountId - 账号ID * @param {number} storeId - 仓库ID(可选) * @return {Promise} */ async getAvailableRoles(accountId, storeId = null) { const { ctx } = this; const where = { account_id: accountId, status: 1, }; if (storeId) { where.store_id = storeId; } const accountStoreEmployees = await ctx.model.AccountStoreEmployee.findAll({ where, include: [ { model: ctx.model.EmployeeRole, as: 'employeeRoles', required: false, attributes: [ 'id', 'employee_id', 'role_id' ], include: [ { model: ctx.model.Role, as: 'role', attributes: [ 'id', 'name', 'code', 'description' ], }, ], }, { model: ctx.model.Store, as: 'store', attributes: [ 'id', 'name', 'code' ], }, ], order: [ [ 'store_id', 'ASC' ], [ 'id', 'ASC' ], ], }); const rows = []; for (const employee of accountStoreEmployees) { const roleBindings = Array.isArray(employee.employeeRoles) ? employee.employeeRoles : []; for (const binding of roleBindings) { const role = binding.role; if (!role) continue; rows.push({ id: employee.id, account_id: employee.account_id, store_id: employee.store_id, store_name: employee.store ? employee.store.name : '', store_code: employee.store ? employee.store.code : '', role_id: binding.role_id, role_name: role.name, role_code: role.code, role_description: role.description, real_name: employee.real_name, created_at: employee.created_at, }); } } return rows; } /** * 根据平台获取账号的当前仓库和角色 * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 * @return {Promise} */ async getCurrentContext(accountId, platformCode) { const activeRole = await this.getActiveRoleByPlatform(accountId, platformCode); if (!activeRole) { return null; } return { account_id: accountId, store_id: activeRole.store_id, store_name: activeRole.store_name, store_code: activeRole.store_code, role_id: activeRole.role_id, role_name: activeRole.role_name, role_code: activeRole.role_code, permissions: activeRole.role_permissions, platform_code: platformCode, }; } } module.exports = AccountPlatformService;