flnxi-Wu/lib/license/check-limits.ts
2026-06-02 19:25:48 +08:00

135 lines
3.5 KiB
TypeScript

/**
* 许可证限制检查工具
* 用于在各个 API 中检查是否达到许可证限制
*/
import { isFeatureEnabled, getLicenseType } from './license-service';
import { prisma } from '@/lib/prisma';
import { getAuthorizedUsageLimits, hasPremiumModule, PREMIUM_MODULE_IDS } from './premium-module-service';
export interface LimitCheckResult {
allowed: boolean;
current: number;
max: number;
message?: string;
}
const LIMIT_MODULE_UNAVAILABLE_MESSAGE = '授权限额模块不可用,请重新验证许可证或联系管理员。';
async function checkAuthorizedLimit(type: 'users' | 'materials'): Promise<LimitCheckResult> {
const limits = await getAuthorizedUsageLimits();
if (!limits) {
return {
allowed: false,
current: 0,
max: 0,
message: LIMIT_MODULE_UNAVAILABLE_MESSAGE,
};
}
const max = type === 'users' ? limits.maxUsers : limits.maxMaterials;
if (max === -1) {
return { allowed: true, current: 0, max };
}
if (!Number.isInteger(max) || max < 0) {
return {
allowed: false,
current: 0,
max: 0,
message: LIMIT_MODULE_UNAVAILABLE_MESSAGE,
};
}
const current = type === 'users'
? await prisma.user.count()
: await prisma.material.count();
return {
allowed: current < max,
current,
max,
};
}
/**
* 检查是否可以创建新用户
*/
export async function canCreateUser(): Promise<LimitCheckResult> {
const result = await checkAuthorizedLimit('users');
if (!result.allowed) {
if (result.message) return result;
const licenseType = await getLicenseType();
return {
...result,
message:
licenseType === 'FREE'
? `当前许可证最多支持 ${result.max} 个用户,当前已有 ${result.current} 个用户。请联系管理员处理授权。`
: `已达到用户数量上限(${result.max}),请联系管理员。`,
};
}
return result;
}
/**
* 检查是否可以上传新素材
*/
export async function canUploadMaterial(): Promise<LimitCheckResult> {
const result = await checkAuthorizedLimit('materials');
if (!result.allowed) {
if (result.message) return result;
const licenseType = await getLicenseType();
return {
...result,
message:
licenseType === 'FREE'
? `当前许可证最多支持 ${result.max} 个素材,当前已有 ${result.current} 个素材。请联系管理员处理授权。`
: `已达到素材数量上限(${result.max}),请联系管理员。`,
};
}
return result;
}
/**
* 检查自定义模板功能是否可用
*/
export async function canUseCustomTemplates(): Promise<boolean> {
if (!(await isFeatureEnabled('customTemplates'))) return false;
return await hasPremiumModule(PREMIUM_MODULE_IDS.CUSTOM_TEMPLATES_CORE);
}
/**
* 检查部门隔离功能是否可用
*/
export async function canUseDepartmentIsolation(): Promise<boolean> {
return await isFeatureEnabled('departmentIsolation');
}
/**
* 检查内网穿透功能是否可用
*/
export async function canUseIntranetPenetration(): Promise<boolean> {
if (!(await isFeatureEnabled('intranetPenetration'))) return false;
return await hasPremiumModule(PREMIUM_MODULE_IDS.INTRANET_PENETRATION_CORE);
}
/**
* 检查系统设置功能是否可用
*/
export async function canUseSystemSettings(): Promise<boolean> {
return await isFeatureEnabled('systemSettings');
}
/**
* 检查 API 访问功能是否可用
*/
export async function canUseApiAccess(): Promise<boolean> {
return await isFeatureEnabled('apiAccess');
}