WMS_MAIN/app/service/systems/account_platform.js

384 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
class AccountPlatformService extends Service {
/**
* 切换平台激活角色
* @param {number} accountId - 账号ID
* @param {number} accountStoreRoleId - 账号仓库角色关联ID
* @param {string} platformCode - 平台编码
* @return {Promise<Object>}
*/
async switchActiveRole(accountId, accountStoreRoleId, platformCode) {
const { ctx, app } = this;
// 使用事务确保数据一致性
const transaction = await ctx.model.transaction();
try {
// 1. 验证角色关联的有效性
const accountStoreRole = await ctx.model.AccountStoreRole.findOne({
where: {
id: accountStoreRoleId,
account_id: accountId,
status: 1,
},
transaction,
});
if (!accountStoreRole) {
throw new Error('角色关联不存在或已失效');
}
// 2. 使用 upsert 切换激活角色
const [ platformActive, created ] = await ctx.model.AccountPlatformActive.upsert({
account_id: accountId,
account_store_role_id: accountStoreRoleId,
platform_code: platformCode,
}, {
transaction,
returning: true,
});
await transaction.commit();
// 3. 清理缓存
await this.clearPlatformCache(accountId, platformCode);
return {
success: true,
created,
data: platformActive,
};
} catch (error) {
await transaction.rollback();
// 处理唯一约束冲突
if (error.name === 'SequelizeUniqueConstraintError') {
// 如果是 account_store_role_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<Object|null>}
*/
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: [
{
model: ctx.model.AccountStoreRole,
as: 'accountStoreRole',
where: { status: 1 },
required: true,
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [ 'id', 'name', 'code', 'permissions' ],
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'name', 'code' ],
},
],
},
],
});
if (!platformActive) {
return null;
}
// 整理返回数据
const result = {
account_id: accountId,
platform_code: platformCode,
role_id: platformActive.accountStoreRole.role_id,
role_name: platformActive.accountStoreRole.role.name,
role_code: platformActive.accountStoreRole.role.code,
role_permissions: platformActive.accountStoreRole.role.permissions,
store_id: platformActive.accountStoreRole.store_id,
store_name: platformActive.accountStoreRole.store.name,
store_code: platformActive.accountStoreRole.store.code,
created_at: platformActive.created_at,
updated_at: platformActive.updated_at,
};
// 缓存结果
if (useCache) {
try {
await app.setCacheAsync(cacheKey, result, 1800); // 缓存30分钟
} catch (error) {
console.warn('缓存平台激活状态失败:', error.message);
}
}
return result;
}
/**
* 批量获取账号在多个平台的激活状态
* @param {number} accountId - 账号ID
* @param {Array<string>} platformCodes - 平台编码数组
* @return {Promise<Object>}
*/
async getMultiplePlatformActiveRoles(accountId, platformCodes) {
const { ctx } = this;
const platformActives = await ctx.model.AccountPlatformActive.findAll({
where: {
account_id: accountId,
platform_code: platformCodes,
},
include: [
{
model: ctx.model.AccountStoreRole,
as: 'accountStoreRole',
where: { status: 1 },
required: true,
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [ 'id', 'name', 'code' ],
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'name', 'code' ],
},
],
},
],
});
// 转换为平台编码为key的对象
const result = {};
platformActives.forEach(active => {
result[active.platform_code] = {
role_id: active.accountStoreRole.role_id,
role_name: active.accountStoreRole.role.name,
role_code: active.accountStoreRole.role.code,
store_id: active.accountStoreRole.store_id,
store_name: active.accountStoreRole.store.name,
store_code: active.accountStoreRole.store.code,
created_at: active.created_at,
updated_at: active.updated_at,
};
});
// 填充未设置的平台
platformCodes.forEach(code => {
if (!result[code]) {
result[code] = null;
}
});
return result;
}
/**
* 获取账号所有平台的激活状态
* @param {number} accountId - 账号ID
* @return {Promise<Array>}
*/
async getAllPlatformActives(accountId) {
const { ctx } = this;
const platformActives = await ctx.model.AccountPlatformActive.findAll({
where: { account_id: accountId },
include: [
{
model: ctx.model.AccountStoreRole,
as: 'accountStoreRole',
where: { status: 1 },
required: true,
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [ 'id', 'name', 'code' ],
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'name', 'code' ],
},
],
},
],
order: [[ 'platform_code', 'ASC' ]],
});
return platformActives.map(active => ({
platform_code: active.platform_code,
role_id: active.accountStoreRole.role_id,
role_name: active.accountStoreRole.role.name,
role_code: active.accountStoreRole.role.code,
store_id: active.accountStoreRole.store_id,
store_name: active.accountStoreRole.store.name,
store_code: active.accountStoreRole.store.code,
created_at: active.created_at,
updated_at: active.updated_at,
}));
}
/**
* 清除平台激活状态
* @param {number} accountId - 账号ID
* @param {string} platformCode - 平台编码
* @return {Promise<boolean>}
*/
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<Array>}
*/
async getAvailableRoles(accountId, storeId = null) {
const { ctx } = this;
const where = {
account_id: accountId,
status: 1,
};
if (storeId) {
where.store_id = storeId;
}
const accountStoreRoles = await ctx.model.AccountStoreRole.findAll({
where,
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' ],
[ 'role_id', 'ASC' ],
],
});
return accountStoreRoles.map(item => ({
id: item.id,
account_id: item.account_id,
store_id: item.store_id,
store_name: item.store.name,
store_code: item.store.code,
role_id: item.role_id,
role_name: item.role.name,
role_code: item.role.code,
role_description: item.role.description,
real_name: item.real_name,
created_at: item.created_at,
}));
}
/**
* 根据平台获取账号的当前仓库和角色
* @param {number} accountId - 账号ID
* @param {string} platformCode - 平台编码
* @return {Promise<Object|null>}
*/
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;