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 },
|
||||
});
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import axios from 'axios';
|
||||
import type { BillingAccountDto, BillingPlanCode, StorageUsageDto } from '@mento/shared';
|
||||
import type { BillingAccountDto, BillingPlanCode, OwnerSeatUsageDto, StorageUsageDto } from '@mento/shared';
|
||||
import {
|
||||
BILLING_PLAN_CODES,
|
||||
BILLING_PLAN_LABELS,
|
||||
BILLING_USER_CAPS,
|
||||
isPermanentBillingPlan,
|
||||
} from '@mento/shared';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
@@ -21,6 +22,10 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const usage = ref<StorageUsageDto | null>(null);
|
||||
const seats = ref<OwnerSeatUsageDto | null>(null);
|
||||
const customUsers = ref('');
|
||||
const seatBusy = ref(false);
|
||||
const seatError = ref('');
|
||||
const quotaGb = ref('');
|
||||
const storageBusy = ref(false);
|
||||
const storageError = ref('');
|
||||
@@ -100,8 +105,54 @@ function saveTypedQuota() {
|
||||
void saveQuota(value);
|
||||
}
|
||||
|
||||
async function loadSeats() {
|
||||
seatError.value = '';
|
||||
try {
|
||||
const { data } = await platformApi.get<OwnerSeatUsageDto>(`/platform/users/${props.userId}/seats`);
|
||||
seats.value = data;
|
||||
customUsers.value =
|
||||
data.maxUsers != null && !(BILLING_USER_CAPS as readonly number[]).includes(data.maxUsers)
|
||||
? String(data.maxUsers)
|
||||
: '';
|
||||
} catch (err) {
|
||||
seatError.value = errorText(err, 'تعداد کاربر خوانده نشد');
|
||||
}
|
||||
}
|
||||
|
||||
async function saveUserCap(maxUsers: number) {
|
||||
seatBusy.value = true;
|
||||
seatError.value = '';
|
||||
try {
|
||||
const { data } = await platformApi.patch<OwnerSeatUsageDto>(
|
||||
`/platform/users/${props.userId}/billing/users`,
|
||||
{ maxUsers },
|
||||
);
|
||||
seats.value = data;
|
||||
customUsers.value =
|
||||
data.maxUsers != null && !(BILLING_USER_CAPS as readonly number[]).includes(data.maxUsers)
|
||||
? String(data.maxUsers)
|
||||
: '';
|
||||
} catch (err) {
|
||||
seatError.value = errorText(err, 'سقف کاربر ذخیره نشد');
|
||||
} finally {
|
||||
seatBusy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function saveCustomUsers() {
|
||||
const value = Number(customUsers.value.trim());
|
||||
if (!Number.isInteger(value) || value < 21) {
|
||||
seatError.value = 'برای بالای ۲۰ کاربر، عدد توافقی را از ۲۱ به بالا وارد کنید';
|
||||
return;
|
||||
}
|
||||
void saveUserCap(value);
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (props.billing) void loadStorage();
|
||||
if (props.billing) {
|
||||
void loadStorage();
|
||||
void loadSeats();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -127,6 +178,41 @@ onMounted(() => {
|
||||
{{ BILLING_PLAN_LABELS[code] }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="billing" class="storage">
|
||||
<strong>تعداد کاربر</strong>
|
||||
<p v-if="seats" class="muted">
|
||||
فعال {{ toFaDigits(seats.usedUsers) }}
|
||||
<template v-if="seats.maxUsers == null"> · سقف تعیین نشده</template>
|
||||
<template v-else> از {{ toFaDigits(seats.maxUsers) }}</template>
|
||||
</p>
|
||||
<p v-else-if="!seatError" class="muted">در حال خواندن کاربران…</p>
|
||||
<p v-if="seats?.maxUsers != null && seats.usedUsers > seats.maxUsers" class="error">
|
||||
تعداد فعلی از سقف بیشتر است. تا کم شدن کاربران، افزودن کاربر جدید بسته است.
|
||||
</p>
|
||||
<div class="plan-row">
|
||||
<button
|
||||
v-for="cap in BILLING_USER_CAPS"
|
||||
:key="cap"
|
||||
class="btn"
|
||||
:class="{ 'btn-ghost': seats?.maxUsers !== cap }"
|
||||
type="button"
|
||||
:disabled="seatBusy"
|
||||
@click="saveUserCap(cap)"
|
||||
>
|
||||
تا {{ toFaDigits(cap) }} کاربر
|
||||
</button>
|
||||
</div>
|
||||
<label class="quota">
|
||||
بالای ۲۰، توافقی
|
||||
<input v-model="customUsers" type="number" min="21" step="1" inputmode="numeric" />
|
||||
</label>
|
||||
<div class="plan-row">
|
||||
<button class="btn" type="button" :disabled="seatBusy" @click="saveCustomUsers">
|
||||
ذخیره سقف توافقی
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="seatError" class="error">{{ seatError }}</p>
|
||||
</div>
|
||||
<div v-if="billing" class="storage">
|
||||
<strong>حجم فایل</strong>
|
||||
<p v-if="usage" class="muted">
|
||||
|
||||
@@ -351,6 +351,18 @@ export interface SetStorageQuotaRequest {
|
||||
quotaGb: number | null;
|
||||
}
|
||||
|
||||
/** سقفهای آمادهٔ تعداد کاربر. بالاتر از ۲۰ توافقی و با عدد جدا ذخیره میشود. */
|
||||
export const BILLING_USER_CAPS = [3, 10, 20] as const;
|
||||
|
||||
export interface OwnerSeatUsageDto {
|
||||
usedUsers: number;
|
||||
maxUsers: number | null;
|
||||
}
|
||||
|
||||
export interface SetUserCapRequest {
|
||||
maxUsers: number;
|
||||
}
|
||||
|
||||
export interface SubscriptionSummaryDto {
|
||||
planCode: BillingPlanCode;
|
||||
status: BillingAccountStatus;
|
||||
@@ -369,6 +381,8 @@ export interface BillingAccountDto {
|
||||
startsAt: string;
|
||||
expiresAt: string;
|
||||
maxOrganizations: number;
|
||||
/** null یعنی سقف کاربر هنوز تعیین نشده */
|
||||
maxUsers?: number | null;
|
||||
externalPaymentRef?: string | null;
|
||||
notes?: string | null;
|
||||
daysRemaining: number;
|
||||
|
||||
Reference in New Issue
Block a user