feat(billing): cap active users on an owner subscription
Super admin can set a seat limit of 3, 10, 20, or a negotiated number so an owner cannot add users past that cap. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
ALTER TABLE "BillingAccount" ADD COLUMN "maxUsers" INTEGER;
|
||||
@@ -465,6 +465,8 @@ model BillingAccount {
|
||||
maxOrganizations Int @default(1)
|
||||
/// سقف حجم فایل همهٔ محیطهای این مالک، به بایت. null = بدون سقف
|
||||
storageQuotaBytes BigInt?
|
||||
/// سقف کاربر فعال همهٔ محیطهای این مالک. null = هنوز تعیین نشده
|
||||
maxUsers Int?
|
||||
/// رزرو برای درگاه/لندینگ بعدی
|
||||
externalPaymentRef String?
|
||||
notes String?
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
BillingAccountStatus,
|
||||
BillingPlanCode,
|
||||
OrgModuleKey,
|
||||
OwnerSeatUsageDto,
|
||||
SubscriptionSummaryDto,
|
||||
} from '@mento/shared';
|
||||
import {
|
||||
@@ -64,6 +65,7 @@ export class BillingService {
|
||||
startsAt: Date;
|
||||
expiresAt: Date;
|
||||
maxOrganizations: number;
|
||||
maxUsers?: number | null;
|
||||
externalPaymentRef: string | null;
|
||||
notes: string | null;
|
||||
}): BillingAccountDto {
|
||||
@@ -72,11 +74,71 @@ export class BillingService {
|
||||
id: row.id,
|
||||
ownerUserId: row.ownerUserId,
|
||||
...summary,
|
||||
maxUsers: row.maxUsers ?? null,
|
||||
externalPaymentRef: row.externalPaymentRef,
|
||||
notes: row.notes,
|
||||
};
|
||||
}
|
||||
|
||||
async seatUsage(ownerUserId: string): Promise<OwnerSeatUsageDto> {
|
||||
const account = await this.getByOwnerUserId(ownerUserId);
|
||||
const orgIds = await this.ownedOrganizationIds(ownerUserId);
|
||||
const usedUsers = await this.countActiveUsers(orgIds);
|
||||
return { usedUsers, maxUsers: account?.maxUsers ?? null };
|
||||
}
|
||||
|
||||
async setMaxUsers(ownerUserId: string, maxUsers: number): Promise<OwnerSeatUsageDto> {
|
||||
await this.prisma.billingAccount.update({
|
||||
where: { ownerUserId },
|
||||
data: { maxUsers },
|
||||
});
|
||||
return this.seatUsage(ownerUserId);
|
||||
}
|
||||
|
||||
/** کاربر جدید فقط وقتی سقف اشتراک جا دارد. کسی که از قبل در محیطهای همین مالک فعال است صندلی تازه نمیگیرد. */
|
||||
async assertSeatAvailable(organizationId: string, userId: string | null): Promise<void> {
|
||||
const owner = await this.prisma.membership.findFirst({
|
||||
where: { organizationId, role: 'owner', isActive: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (!owner) return;
|
||||
const account = await this.getByOwnerUserId(owner.userId);
|
||||
if (!account || account.maxUsers == null) return;
|
||||
const orgIds = await this.ownedOrganizationIds(owner.userId);
|
||||
if (userId) {
|
||||
const already = await this.prisma.membership.findFirst({
|
||||
where: { userId, organizationId: { in: orgIds }, isActive: true },
|
||||
select: { id: true },
|
||||
});
|
||||
if (already) return;
|
||||
}
|
||||
const used = await this.countActiveUsers(orgIds);
|
||||
if (used >= account.maxUsers) {
|
||||
throw new ForbiddenException(
|
||||
`سقف کاربر این اشتراک ${account.maxUsers} نفر است. برای افزودن کاربر باید سقف اشتراک بیشتر شود.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async ownedOrganizationIds(ownerUserId: string): Promise<string[]> {
|
||||
const rows = await this.prisma.membership.findMany({
|
||||
where: { userId: ownerUserId, role: 'owner', isActive: true },
|
||||
select: { organizationId: true },
|
||||
});
|
||||
return rows.map((row) => row.organizationId);
|
||||
}
|
||||
|
||||
private async countActiveUsers(organizationIds: string[]): Promise<number> {
|
||||
if (!organizationIds.length) return 0;
|
||||
const rows = await this.prisma.membership.findMany({
|
||||
where: { organizationId: { in: organizationIds }, isActive: true },
|
||||
select: { userId: true },
|
||||
distinct: ['userId'],
|
||||
});
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
async getByOwnerUserId(ownerUserId: string) {
|
||||
return this.prisma.billingAccount.findUnique({ where: { ownerUserId } });
|
||||
}
|
||||
|
||||
@@ -148,6 +148,13 @@ export class ApplyBillingPlanDto {
|
||||
status?: 'active' | 'expired' | 'suspended';
|
||||
}
|
||||
|
||||
export class SetUserCapDto {
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(100_000)
|
||||
maxUsers!: number;
|
||||
}
|
||||
|
||||
export class SetStorageQuotaDto {
|
||||
/** گیگابایت؛ null = بدون سقف */
|
||||
@IsNumber()
|
||||
|
||||
@@ -12,6 +12,7 @@ import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import {
|
||||
ApplyBillingPlanDto,
|
||||
SetStorageQuotaDto,
|
||||
SetUserCapDto,
|
||||
CreatePlatformAdminDto,
|
||||
CreatePlatformOrganizationDto,
|
||||
ResetPlatformAdminPasswordDto,
|
||||
@@ -133,6 +134,16 @@ export class PlatformController {
|
||||
return this.platform.setStorageQuota(id, dto.quotaGb);
|
||||
}
|
||||
|
||||
@Get('users/:id/seats')
|
||||
seatUsage(@Param('id') id: string) {
|
||||
return this.platform.seatUsage(id);
|
||||
}
|
||||
|
||||
@Patch('users/:id/billing/users')
|
||||
setUserCap(@Param('id') id: string, @Body() dto: SetUserCapDto) {
|
||||
return this.platform.setUserCap(id, dto.maxUsers);
|
||||
}
|
||||
|
||||
@Patch('organizations/:id/modules')
|
||||
updateOrganizationModules(
|
||||
@Param('id') id: string,
|
||||
|
||||
@@ -425,6 +425,30 @@ export class PlatformService {
|
||||
return this.storage.usageForOwner(userId, refresh);
|
||||
}
|
||||
|
||||
async seatUsage(userId: string) {
|
||||
await this.requireBillingOwner(userId);
|
||||
return this.billing.seatUsage(userId);
|
||||
}
|
||||
|
||||
async setUserCap(userId: string, maxUsers: number) {
|
||||
await this.requireBillingOwner(userId);
|
||||
return this.billing.setMaxUsers(userId, maxUsers);
|
||||
}
|
||||
|
||||
private async requireBillingOwner(userId: string) {
|
||||
const owner = await this.prisma.membership.findFirst({
|
||||
where: { userId, role: 'owner', isActive: true },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!owner) {
|
||||
throw new BadRequestException('سقف کاربر فقط برای مالک محیط معنی دارد');
|
||||
}
|
||||
const account = await this.billing.getByOwnerUserId(userId);
|
||||
if (!account) {
|
||||
throw new BadRequestException('اول برای این مالک یک پلن اعمال کنید');
|
||||
}
|
||||
}
|
||||
|
||||
async setStorageQuota(userId: string, quotaGb: number | null) {
|
||||
await this.storageUsage(userId, false);
|
||||
return this.storage.setQuotaGb(userId, quotaGb);
|
||||
@@ -495,9 +519,13 @@ export class PlatformService {
|
||||
userId: true,
|
||||
organizationId: true,
|
||||
role: true,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
if (!row) throw new NotFoundException('عضویت پیدا نشد');
|
||||
if (isActive && !row.isActive) {
|
||||
await this.billing.assertSeatAvailable(row.organizationId, row.userId);
|
||||
}
|
||||
if (!isActive && row.role === 'owner') {
|
||||
const activeOwners = await this.memberships.countActiveOwners(
|
||||
row.organizationId,
|
||||
|
||||
@@ -23,6 +23,7 @@ import { normalizeMobile } from '../auth/auth.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { OrgRolesService } from '../org-roles/org-roles.service';
|
||||
import { MembershipsService } from '../memberships/memberships.service';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { LocalFileStorage } from '../storage/local-file.storage';
|
||||
import * as path from 'path';
|
||||
|
||||
@@ -70,6 +71,7 @@ export class UsersService {
|
||||
private readonly orgRoles: OrgRolesService,
|
||||
private readonly memberships: MembershipsService,
|
||||
private readonly files: LocalFileStorage,
|
||||
private readonly billing: BillingService,
|
||||
) {}
|
||||
|
||||
async list(organizationId: string): Promise<OrgUserDto[]> {
|
||||
@@ -105,6 +107,7 @@ export class UsersService {
|
||||
return this.addExistingUser(organizationId, existingUser.id, resolved);
|
||||
}
|
||||
|
||||
await this.billing.assertSeatAvailable(organizationId, null);
|
||||
const password = dto.password?.trim() ?? '';
|
||||
if (password.length < 8) {
|
||||
throw new BadRequestException(
|
||||
@@ -506,6 +509,9 @@ export class UsersService {
|
||||
throw new BadRequestException('حداقل یک مالک فعال لازم است');
|
||||
}
|
||||
}
|
||||
if (isActive && !target.isActive) {
|
||||
await this.billing.assertSeatAvailable(organizationId, targetId);
|
||||
}
|
||||
await this.prisma.membership.update({
|
||||
where: { id: target.id },
|
||||
data: { isActive },
|
||||
@@ -533,6 +539,7 @@ export class UsersService {
|
||||
userId: string,
|
||||
resolved: { role: UserRole; orgRoleId: string },
|
||||
): Promise<OrgUserDto> {
|
||||
await this.billing.assertSeatAvailable(organizationId, userId);
|
||||
const existing = await this.prisma.membership.findFirst({
|
||||
where: { userId, organizationId },
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user