Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebf13cfde5 | ||
|
|
0e580b19c3 | ||
|
|
4a9fe0b07c | ||
|
|
04d37a9d12 |
@@ -0,0 +1,64 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Organization" ADD COLUMN IF NOT EXISTS "enabledModules" TEXT[] DEFAULT ARRAY[]::TEXT[];
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE IF NOT EXISTS "BillingAccount" (
|
||||
"id" TEXT NOT NULL,
|
||||
"ownerUserId" TEXT NOT NULL,
|
||||
"planCode" TEXT NOT NULL DEFAULT 'trial',
|
||||
"status" TEXT NOT NULL DEFAULT 'active',
|
||||
"startsAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"maxOrganizations" INTEGER NOT NULL DEFAULT 1,
|
||||
"externalPaymentRef" TEXT,
|
||||
"notes" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "BillingAccount_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "BillingAccount_ownerUserId_key" ON "BillingAccount"("ownerUserId");
|
||||
CREATE INDEX IF NOT EXISTS "BillingAccount_status_idx" ON "BillingAccount"("status");
|
||||
CREATE INDEX IF NOT EXISTS "BillingAccount_expiresAt_idx" ON "BillingAccount"("expiresAt");
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'BillingAccount_ownerUserId_fkey'
|
||||
) THEN
|
||||
ALTER TABLE "BillingAccount"
|
||||
ADD CONSTRAINT "BillingAccount_ownerUserId_fkey"
|
||||
FOREIGN KEY ("ownerUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Backfill: full module catalog for existing orgs (empty → all)
|
||||
UPDATE "Organization"
|
||||
SET "enabledModules" = ARRAY[
|
||||
'customers','pipeline','products','invoices','quotes','commissions','sales_forecast',
|
||||
'activities','tickets','workflow_automations','message_automations','lead_forms',
|
||||
'project_boards','inventory','cheques','attachments','loyalty','reports','notes',
|
||||
'tahesab','custom_fields','currencies','team_settings','faq'
|
||||
]::TEXT[]
|
||||
WHERE cardinality("enabledModules") = 0;
|
||||
|
||||
-- Backfill BillingAccount for every active owner membership (15-day trial)
|
||||
INSERT INTO "BillingAccount" (
|
||||
"id", "ownerUserId", "planCode", "status", "startsAt", "expiresAt",
|
||||
"maxOrganizations", "createdAt", "updatedAt"
|
||||
)
|
||||
SELECT
|
||||
md5(random()::text || clock_timestamp()::text || m."userId"),
|
||||
m."userId",
|
||||
'trial',
|
||||
'active',
|
||||
NOW(),
|
||||
NOW() + INTERVAL '15 days',
|
||||
GREATEST(1, COUNT(*)::int),
|
||||
NOW(),
|
||||
NOW()
|
||||
FROM "Membership" m
|
||||
WHERE m."role" = 'owner' AND m."isActive" = true
|
||||
GROUP BY m."userId"
|
||||
ON CONFLICT ("ownerUserId") DO NOTHING;
|
||||
@@ -147,6 +147,8 @@ model Organization {
|
||||
businessField String?
|
||||
baseCurrency String @default("IRR")
|
||||
enabledCurrencies String[] @default(["IRR", "USD", "EUR"])
|
||||
/// ماژولهای فعال منو برای این محیط
|
||||
enabledModules String[] @default([])
|
||||
isActive Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -230,6 +232,7 @@ model User {
|
||||
ticketMessages TicketMessage[] @relation("TicketMessageAuthor")
|
||||
confirmedMemories MemoryItem[] @relation("MemoryConfirmedBy")
|
||||
memberships Membership[]
|
||||
billingAccount BillingAccount?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -293,6 +296,28 @@ model PlatformAdmin {
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
/// اشتراک SaaS روی مالک حساب (نه روی هر عضویت)
|
||||
model BillingAccount {
|
||||
id String @id @default(cuid())
|
||||
ownerUserId String @unique
|
||||
owner User @relation(fields: [ownerUserId], references: [id], onDelete: Cascade)
|
||||
/// trial | monthly | quarterly | semiannual | yearly | custom
|
||||
planCode String @default("trial")
|
||||
/// active | expired | suspended
|
||||
status String @default("active")
|
||||
startsAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
maxOrganizations Int @default(1)
|
||||
/// رزرو برای درگاه/لندینگ بعدی
|
||||
externalPaymentRef String?
|
||||
notes String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([status])
|
||||
@@index([expiresAt])
|
||||
}
|
||||
|
||||
model Company {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
|
||||
+38
-4
@@ -44,9 +44,19 @@ async function seedPlatformAdmin() {
|
||||
return;
|
||||
}
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
const existingByMobile = await prisma.platformAdmin.findUnique({ where: { mobile } });
|
||||
if (existingByMobile) {
|
||||
console.log('Platform admin exists:', mobile);
|
||||
await prisma.platformAdmin.update({
|
||||
where: { id: existingByMobile.id },
|
||||
data: {
|
||||
passwordHash,
|
||||
fullName: envName,
|
||||
isActive: true,
|
||||
...(email ? { email } : {}),
|
||||
},
|
||||
});
|
||||
console.log('Platform admin password refreshed:', mobile);
|
||||
return;
|
||||
}
|
||||
if (email) {
|
||||
@@ -54,14 +64,38 @@ async function seedPlatformAdmin() {
|
||||
if (existingByEmail) {
|
||||
await prisma.platformAdmin.update({
|
||||
where: { id: existingByEmail.id },
|
||||
data: { mobile, ...(envName ? { fullName: envName } : {}) },
|
||||
data: {
|
||||
mobile,
|
||||
passwordHash,
|
||||
fullName: envName,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
console.log('Platform admin linked mobile:', mobile, '→', email);
|
||||
console.log('Platform admin linked mobile + password refreshed:', mobile, '→', email);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
const orphans = await prisma.platformAdmin.findMany({
|
||||
where: { mobile: null },
|
||||
take: 2,
|
||||
});
|
||||
if (orphans.length === 1) {
|
||||
const orphan = orphans[0]!;
|
||||
await prisma.platformAdmin.update({
|
||||
where: { id: orphan.id },
|
||||
data: {
|
||||
mobile,
|
||||
passwordHash,
|
||||
fullName: envName,
|
||||
isActive: true,
|
||||
...(email ? { email } : {}),
|
||||
},
|
||||
});
|
||||
console.log('Platform admin orphan linked mobile:', mobile);
|
||||
return;
|
||||
}
|
||||
|
||||
await prisma.platformAdmin.create({
|
||||
data: {
|
||||
mobile,
|
||||
|
||||
@@ -33,6 +33,7 @@ import { TahesabModule } from './integrations/tahesab/tahesab.module';
|
||||
import { InventoryModule } from './inventory/inventory.module';
|
||||
import { FinanceModule } from './finance/finance.module';
|
||||
import { PlatformModule } from './platform/platform.module';
|
||||
import { BillingModule } from './billing/billing.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -45,6 +46,7 @@ import { PlatformModule } from './platform/platform.module';
|
||||
PrismaModule,
|
||||
StorageModule,
|
||||
HealthModule,
|
||||
BillingModule,
|
||||
AuthModule,
|
||||
PlatformModule,
|
||||
UsersModule,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { MembershipsModule } from '../memberships/memberships.module';
|
||||
import { BillingModule } from '../billing/billing.module';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
@@ -13,6 +14,7 @@ import { SmsService } from '../common/sms.service';
|
||||
imports: [
|
||||
ConfigModule,
|
||||
MembershipsModule,
|
||||
BillingModule,
|
||||
PassportModule.register({ defaultStrategy: 'jwt' }),
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
|
||||
@@ -10,12 +10,19 @@ import { ConfigService } from '@nestjs/config';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import * as path from 'path';
|
||||
import type { AuthUserDto, LoginResponse, LoginResult } from '@mento/shared';
|
||||
import type {
|
||||
AuthUserDto,
|
||||
LoginResponse,
|
||||
LoginResult,
|
||||
OrgModuleKey,
|
||||
SubscriptionSummaryDto,
|
||||
} from '@mento/shared';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsService } from '../common/sms.service';
|
||||
import { LocalFileStorage } from '../storage/local-file.storage';
|
||||
import { MembershipsService } from '../memberships/memberships.service';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import {
|
||||
LoginDto,
|
||||
LoginOtpRequestDto,
|
||||
@@ -97,6 +104,7 @@ export class AuthService {
|
||||
private readonly sms: SmsService,
|
||||
private readonly files: LocalFileStorage,
|
||||
private readonly memberships: MembershipsService,
|
||||
private readonly billing: BillingService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -260,6 +268,11 @@ export class AuthService {
|
||||
organizationId: organization.id,
|
||||
role: 'owner',
|
||||
});
|
||||
await this.billing.ensureTrialForOwner(owner.id, { maxOrganizations: 1 });
|
||||
await this.prisma.organization.update({
|
||||
where: { id: organization.id },
|
||||
data: { enabledModules: this.billing.defaultModulesForNewOrg() },
|
||||
});
|
||||
|
||||
await this.prisma.authChallenge.update({
|
||||
where: { id: challenge.id },
|
||||
@@ -578,6 +591,9 @@ export class AuthService {
|
||||
if (!user || user.isActive === false) {
|
||||
throw new UnauthorizedException('حساب کاربری غیرفعال است');
|
||||
}
|
||||
const subscription = await this.billing.requireActiveForOrganization(
|
||||
organizationId,
|
||||
);
|
||||
await this.memberships.syncUserLastOrg(
|
||||
userId,
|
||||
organizationId,
|
||||
@@ -597,6 +613,7 @@ export class AuthService {
|
||||
user: await this.toAuthUserDto(
|
||||
{ ...user, role: membership.role, organizationId },
|
||||
organizationId,
|
||||
subscription,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -611,19 +628,30 @@ export class AuthService {
|
||||
organizationId: string;
|
||||
},
|
||||
organizationId: string,
|
||||
subscription?: SubscriptionSummaryDto | null,
|
||||
): Promise<AuthUserDto> {
|
||||
const membership = await this.prisma.membership.findFirst({
|
||||
where: { userId: user.id, organizationId, isActive: true },
|
||||
include: { organization: { select: { name: true } } },
|
||||
include: {
|
||||
organization: { select: { name: true, enabledModules: true } },
|
||||
},
|
||||
});
|
||||
const role = membership?.role ?? user.role;
|
||||
const orgName = membership?.organization.name;
|
||||
const sub =
|
||||
subscription ??
|
||||
(await this.billing.requireActiveForOrganization(organizationId));
|
||||
return this.toAuthUser({
|
||||
...user,
|
||||
role,
|
||||
organizationId,
|
||||
organizationName: orgName,
|
||||
avatarStorageKey: await this.readAvatarKey(user.id),
|
||||
enabledModules: this.billing.normalizeModules(
|
||||
membership?.organization.enabledModules,
|
||||
),
|
||||
subscription: sub,
|
||||
isOrgOwner: role === 'owner',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -708,6 +736,9 @@ export class AuthService {
|
||||
organizationId: string;
|
||||
organizationName?: string;
|
||||
avatarStorageKey?: string | null;
|
||||
enabledModules?: OrgModuleKey[];
|
||||
subscription?: SubscriptionSummaryDto | null;
|
||||
isOrgOwner?: boolean;
|
||||
}): AuthUserDto {
|
||||
return {
|
||||
id: user.id,
|
||||
@@ -718,6 +749,9 @@ export class AuthService {
|
||||
organizationName: user.organizationName,
|
||||
hasAvatar: Boolean(user.avatarStorageKey),
|
||||
...(user.mobile ? { mobile: user.mobile } : {}),
|
||||
...(user.enabledModules ? { enabledModules: user.enabledModules } : {}),
|
||||
...(user.subscription ? { subscription: user.subscription } : {}),
|
||||
...(user.isOrgOwner !== undefined ? { isOrgOwner: user.isOrgOwner } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
export type JwtPayload = {
|
||||
@@ -15,6 +16,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(
|
||||
config: ConfigService,
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
@@ -53,6 +55,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
if (!membership) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
await this.billing.requireActiveForOrganization(membership.organizationId);
|
||||
return {
|
||||
userId: user.id,
|
||||
organizationId: membership.organizationId,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { BillingService } from './billing.service';
|
||||
import { OrgModuleGuard } from './org-module.guard';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [BillingService, OrgModuleGuard],
|
||||
exports: [BillingService, OrgModuleGuard],
|
||||
})
|
||||
export class BillingModule {}
|
||||
@@ -0,0 +1,302 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import type {
|
||||
ApplyBillingPlanRequest,
|
||||
BillingAccountDto,
|
||||
BillingAccountStatus,
|
||||
BillingPlanCode,
|
||||
OrgModuleKey,
|
||||
SubscriptionSummaryDto,
|
||||
} from '@mento/shared';
|
||||
import {
|
||||
BILLING_PLAN_DAYS,
|
||||
BILLING_PLAN_DEFAULT_MAX_ORGS,
|
||||
defaultEnabledModules,
|
||||
isOrgModuleKey,
|
||||
} from '@mento/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
function daysRemaining(expiresAt: Date, now = new Date()): number {
|
||||
const ms = expiresAt.getTime() - now.getTime();
|
||||
return Math.max(0, Math.ceil(ms / (24 * 60 * 60 * 1000)));
|
||||
}
|
||||
|
||||
function toSummary(row: {
|
||||
planCode: string;
|
||||
status: string;
|
||||
startsAt: Date;
|
||||
expiresAt: Date;
|
||||
maxOrganizations: number;
|
||||
}): SubscriptionSummaryDto {
|
||||
const remaining = daysRemaining(row.expiresAt);
|
||||
const status = (row.status as BillingAccountStatus) ?? 'active';
|
||||
return {
|
||||
planCode: row.planCode as BillingPlanCode,
|
||||
status,
|
||||
startsAt: row.startsAt.toISOString(),
|
||||
expiresAt: row.expiresAt.toISOString(),
|
||||
maxOrganizations: row.maxOrganizations,
|
||||
daysRemaining: remaining,
|
||||
warn: remaining > 0 && remaining <= 3,
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class BillingService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
toDto(row: {
|
||||
id: string;
|
||||
ownerUserId: string;
|
||||
planCode: string;
|
||||
status: string;
|
||||
startsAt: Date;
|
||||
expiresAt: Date;
|
||||
maxOrganizations: number;
|
||||
externalPaymentRef: string | null;
|
||||
notes: string | null;
|
||||
}): BillingAccountDto {
|
||||
const summary = toSummary(row);
|
||||
return {
|
||||
id: row.id,
|
||||
ownerUserId: row.ownerUserId,
|
||||
...summary,
|
||||
externalPaymentRef: row.externalPaymentRef,
|
||||
notes: row.notes,
|
||||
};
|
||||
}
|
||||
|
||||
async getByOwnerUserId(ownerUserId: string) {
|
||||
return this.prisma.billingAccount.findUnique({ where: { ownerUserId } });
|
||||
}
|
||||
|
||||
async ensureTrialForOwner(
|
||||
ownerUserId: string,
|
||||
opts?: { maxOrganizations?: number },
|
||||
) {
|
||||
const existing = await this.getByOwnerUserId(ownerUserId);
|
||||
if (existing) return existing;
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(now.getTime() + 15 * 24 * 60 * 60 * 1000);
|
||||
return this.prisma.billingAccount.create({
|
||||
data: {
|
||||
ownerUserId,
|
||||
planCode: 'trial',
|
||||
status: 'active',
|
||||
startsAt: now,
|
||||
expiresAt,
|
||||
maxOrganizations: Math.max(1, opts?.maxOrganizations ?? 1),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** اشتراک محیط = BillingAccount اولین مالک فعال — برای عضو زیرمجموعه حساب جدید ساخته نمیشود */
|
||||
async resolveForOrganization(organizationId: string) {
|
||||
const owner = await this.prisma.membership.findFirst({
|
||||
where: {
|
||||
organizationId,
|
||||
role: 'owner',
|
||||
isActive: true,
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (!owner) return null;
|
||||
return this.getByOwnerUserId(owner.userId);
|
||||
}
|
||||
|
||||
async requireActiveForOrganization(organizationId: string): Promise<SubscriptionSummaryDto> {
|
||||
const account = await this.resolveForOrganization(organizationId);
|
||||
if (!account) {
|
||||
throw new UnauthorizedException(
|
||||
'اشتراک این محیط یافت نشد؛ مالک باید از پنل سوپرادمین پلن داشته باشد',
|
||||
);
|
||||
}
|
||||
return this.assertActive(account);
|
||||
}
|
||||
|
||||
async requireActiveForOwner(ownerUserId: string): Promise<SubscriptionSummaryDto> {
|
||||
const account = await this.getByOwnerUserId(ownerUserId);
|
||||
if (!account) {
|
||||
throw new UnauthorizedException(
|
||||
'اشتراک یافت نشد؛ ابتدا پلن را از سوپرادمین اعمال کنید',
|
||||
);
|
||||
}
|
||||
return this.assertActive(account);
|
||||
}
|
||||
|
||||
private async assertActive(account: {
|
||||
id: string;
|
||||
planCode: string;
|
||||
status: string;
|
||||
startsAt: Date;
|
||||
expiresAt: Date;
|
||||
maxOrganizations: number;
|
||||
}): Promise<SubscriptionSummaryDto> {
|
||||
const now = new Date();
|
||||
if (account.status === 'suspended') {
|
||||
throw new UnauthorizedException('اشتراک این حساب معلق شده است');
|
||||
}
|
||||
if (account.status === 'expired' || account.expiresAt.getTime() < now.getTime()) {
|
||||
if (account.status !== 'expired') {
|
||||
await this.prisma.billingAccount.update({
|
||||
where: { id: account.id },
|
||||
data: { status: 'expired' },
|
||||
});
|
||||
}
|
||||
throw new UnauthorizedException('اشتراک منقضی شده است');
|
||||
}
|
||||
return toSummary(account);
|
||||
}
|
||||
|
||||
async assertCanCreateOrganization(ownerUserId: string) {
|
||||
let account = await this.getByOwnerUserId(ownerUserId);
|
||||
if (!account) {
|
||||
// اولین محیط مالک: trial خودکار
|
||||
account = await this.ensureTrialForOwner(ownerUserId, { maxOrganizations: 1 });
|
||||
}
|
||||
const summary = await this.assertActive(account);
|
||||
const ownedCount = await this.prisma.membership.count({
|
||||
where: { userId: ownerUserId, role: 'owner', isActive: true },
|
||||
});
|
||||
if (ownedCount >= summary.maxOrganizations) {
|
||||
throw new ForbiddenException(
|
||||
`سقف تعداد محیط برای این اشتراک ${summary.maxOrganizations} است`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async applyPlan(
|
||||
ownerUserId: string,
|
||||
dto: ApplyBillingPlanRequest,
|
||||
): Promise<BillingAccountDto> {
|
||||
const ownerMembership = await this.prisma.membership.findFirst({
|
||||
where: { userId: ownerUserId, role: 'owner', isActive: true },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!ownerMembership) {
|
||||
throw new BadRequestException(
|
||||
'اشتراک فقط برای مالک محیط تعریف میشود؛ این کاربر مالک هیچ محیطی نیست',
|
||||
);
|
||||
}
|
||||
|
||||
const planCode = dto.planCode;
|
||||
const now = new Date();
|
||||
let expiresAt: Date;
|
||||
let maxOrganizations: number;
|
||||
|
||||
if (planCode === 'custom') {
|
||||
if (!dto.expiresAt) {
|
||||
throw new BadRequestException('برای پلن سفارشی تاریخ انقضا لازم است');
|
||||
}
|
||||
expiresAt = new Date(dto.expiresAt);
|
||||
if (Number.isNaN(expiresAt.getTime())) {
|
||||
throw new BadRequestException('تاریخ انقضا معتبر نیست');
|
||||
}
|
||||
maxOrganizations = Math.max(1, dto.maxOrganizations ?? 1);
|
||||
} else {
|
||||
const days = BILLING_PLAN_DAYS[planCode];
|
||||
expiresAt = dto.expiresAt
|
||||
? new Date(dto.expiresAt)
|
||||
: new Date(now.getTime() + days * 24 * 60 * 60 * 1000);
|
||||
if (Number.isNaN(expiresAt.getTime())) {
|
||||
throw new BadRequestException('تاریخ انقضا معتبر نیست');
|
||||
}
|
||||
maxOrganizations = Math.max(
|
||||
1,
|
||||
dto.maxOrganizations ?? BILLING_PLAN_DEFAULT_MAX_ORGS[planCode],
|
||||
);
|
||||
}
|
||||
|
||||
const status: BillingAccountStatus =
|
||||
dto.status ??
|
||||
(expiresAt.getTime() < now.getTime() ? 'expired' : 'active');
|
||||
|
||||
const existing = await this.getByOwnerUserId(ownerUserId);
|
||||
const row = existing
|
||||
? await this.prisma.billingAccount.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
planCode,
|
||||
status,
|
||||
startsAt: existing.startsAt ?? now,
|
||||
expiresAt,
|
||||
maxOrganizations,
|
||||
...(dto.notes !== undefined ? { notes: dto.notes } : {}),
|
||||
},
|
||||
})
|
||||
: await this.prisma.billingAccount.create({
|
||||
data: {
|
||||
ownerUserId,
|
||||
planCode,
|
||||
status,
|
||||
startsAt: now,
|
||||
expiresAt,
|
||||
maxOrganizations,
|
||||
notes: dto.notes ?? null,
|
||||
},
|
||||
});
|
||||
return this.toDto(row);
|
||||
}
|
||||
|
||||
async setOrgModules(organizationId: string, modules: string[]) {
|
||||
const cleaned = [
|
||||
...new Set(
|
||||
modules.filter(isOrgModuleKey),
|
||||
),
|
||||
] as OrgModuleKey[];
|
||||
await this.prisma.organization.update({
|
||||
where: { id: organizationId },
|
||||
data: { enabledModules: cleaned },
|
||||
});
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
normalizeModules(raw: string[] | null | undefined): OrgModuleKey[] {
|
||||
if (!raw?.length) return defaultEnabledModules();
|
||||
const cleaned = raw.filter(isOrgModuleKey) as OrgModuleKey[];
|
||||
return cleaned.length ? cleaned : defaultEnabledModules();
|
||||
}
|
||||
|
||||
async requireModule(organizationId: string, module: OrgModuleKey) {
|
||||
const org = await this.prisma.organization.findUnique({
|
||||
where: { id: organizationId },
|
||||
select: { enabledModules: true },
|
||||
});
|
||||
if (!org) throw new ForbiddenException('محیط پیدا نشد');
|
||||
const enabled = this.normalizeModules(org.enabledModules);
|
||||
if (!enabled.includes(module)) {
|
||||
throw new ForbiddenException('این ماژول برای این محیط فعال نیست');
|
||||
}
|
||||
}
|
||||
|
||||
defaultModulesForNewOrg(): OrgModuleKey[] {
|
||||
return defaultEnabledModules();
|
||||
}
|
||||
|
||||
async countExpiringSoon() {
|
||||
const now = new Date();
|
||||
const in3 = new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000);
|
||||
return this.prisma.billingAccount.count({
|
||||
where: {
|
||||
status: 'active',
|
||||
expiresAt: { gt: now, lte: in3 },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async countExpired() {
|
||||
return this.prisma.billingAccount.count({
|
||||
where: {
|
||||
OR: [
|
||||
{ status: 'expired' },
|
||||
{ status: 'active', expiresAt: { lt: new Date() } },
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import type { OrgModuleKey } from '@mento/shared';
|
||||
|
||||
export const ORG_MODULE_KEY = 'org_module';
|
||||
|
||||
export const RequireOrgModule = (module: OrgModuleKey) =>
|
||||
SetMetadata(ORG_MODULE_KEY, module);
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import type { OrgModuleKey } from '@mento/shared';
|
||||
import { BillingService } from './billing.service';
|
||||
import { ORG_MODULE_KEY } from './org-module.decorator';
|
||||
|
||||
@Injectable()
|
||||
export class OrgModuleGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly billing: BillingService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const module = this.reflector.getAllAndOverride<OrgModuleKey | undefined>(
|
||||
ORG_MODULE_KEY,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
if (!module) return true;
|
||||
const req = context.switchToHttp().getRequest<{
|
||||
user?: { organizationId?: string };
|
||||
}>();
|
||||
const organizationId = req.user?.organizationId;
|
||||
if (!organizationId) return false;
|
||||
await this.billing.requireModule(organizationId, module);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -18,13 +18,16 @@ import type { Response } from 'express';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import type { Actor } from '../common/record-scope';
|
||||
import { OrgModuleGuard } from '../billing/org-module.guard';
|
||||
import { RequireOrgModule } from '../billing/org-module.decorator';
|
||||
import { CreatePersonDto, ListQueryDto, UpdatePersonDto } from './dto';
|
||||
import { PeopleService } from './people.service';
|
||||
import { ContactsExcelService } from './contacts-excel.service';
|
||||
import { brand } from '@mento/shared';
|
||||
|
||||
@Controller('people')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, OrgModuleGuard)
|
||||
@RequireOrgModule('customers')
|
||||
export class PeopleController {
|
||||
constructor(
|
||||
private readonly peopleService: PeopleService,
|
||||
|
||||
@@ -12,6 +12,8 @@ import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { Roles } from '../auth/roles.decorator';
|
||||
import { RolesGuard } from '../auth/roles.guard';
|
||||
import { OrgModuleGuard } from '../billing/org-module.guard';
|
||||
import { RequireOrgModule } from '../billing/org-module.decorator';
|
||||
import {
|
||||
CreateMessageAutomationRuleDto,
|
||||
UpdateMessageAutomationRuleDto,
|
||||
@@ -19,7 +21,8 @@ import {
|
||||
import { MessageAutomationsService } from './message-automations.service';
|
||||
|
||||
@Controller('message-automations')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@UseGuards(JwtAuthGuard, RolesGuard, OrgModuleGuard)
|
||||
@RequireOrgModule('message_automations')
|
||||
@Roles('owner', 'admin')
|
||||
export class MessageAutomationsController {
|
||||
constructor(private readonly messages: MessageAutomationsService) {}
|
||||
|
||||
@@ -3,11 +3,18 @@ import { AuthModule } from '../auth/auth.module';
|
||||
import { MembershipsModule } from '../memberships/memberships.module';
|
||||
import { OrgRolesModule } from '../org-roles/org-roles.module';
|
||||
import { PipelinesModule } from '../pipelines/pipelines.module';
|
||||
import { BillingModule } from '../billing/billing.module';
|
||||
import { OrganizationsController } from './organizations.controller';
|
||||
import { OrganizationsService } from './organizations.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, MembershipsModule, OrgRolesModule, PipelinesModule],
|
||||
imports: [
|
||||
AuthModule,
|
||||
MembershipsModule,
|
||||
OrgRolesModule,
|
||||
PipelinesModule,
|
||||
BillingModule,
|
||||
],
|
||||
controllers: [OrganizationsController],
|
||||
providers: [OrganizationsService],
|
||||
})
|
||||
|
||||
@@ -15,6 +15,7 @@ import { isKnownCurrency } from '../common/currency';
|
||||
import { MembershipsService } from '../memberships/memberships.service';
|
||||
import { OrgRolesService } from '../org-roles/org-roles.service';
|
||||
import { PipelinesService } from '../pipelines/pipelines.service';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
|
||||
function slugify(input: string): string {
|
||||
return (
|
||||
@@ -34,6 +35,7 @@ export class OrganizationsService {
|
||||
private readonly memberships: MembershipsService,
|
||||
private readonly orgRoles: OrgRolesService,
|
||||
private readonly pipelines: PipelinesService,
|
||||
private readonly billing: BillingService,
|
||||
) {}
|
||||
|
||||
async createForUser(
|
||||
@@ -57,6 +59,8 @@ export class OrganizationsService {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
await this.billing.assertCanCreateOrganization(userId);
|
||||
|
||||
const baseSlug = slugify(name);
|
||||
let slug = baseSlug;
|
||||
let i = 1;
|
||||
@@ -69,6 +73,7 @@ export class OrganizationsService {
|
||||
name,
|
||||
slug,
|
||||
businessField,
|
||||
enabledModules: this.billing.defaultModulesForNewOrg(),
|
||||
},
|
||||
});
|
||||
await this.memberships.createMembership({
|
||||
@@ -76,6 +81,7 @@ export class OrganizationsService {
|
||||
organizationId: organization.id,
|
||||
role: 'owner',
|
||||
});
|
||||
await this.billing.ensureTrialForOwner(userId);
|
||||
await this.orgRoles.ensureDefaultRoles(organization.id);
|
||||
await this.pipelines.ensureDefaultPipeline(organization.id);
|
||||
return { id: organization.id };
|
||||
@@ -219,6 +225,7 @@ export class OrganizationsService {
|
||||
businessField: string | null;
|
||||
baseCurrency: string;
|
||||
enabledCurrencies: string[];
|
||||
enabledModules?: string[];
|
||||
exchangeRates: Array<{
|
||||
currency: string;
|
||||
rateToBase: Prisma.Decimal;
|
||||
@@ -235,6 +242,7 @@ export class OrganizationsService {
|
||||
: null,
|
||||
baseCurrency: org.baseCurrency,
|
||||
enabledCurrencies: org.enabledCurrencies,
|
||||
enabledModules: this.billing.normalizeModules(org.enabledModules),
|
||||
exchangeRates: org.exchangeRates.map((r) => ({
|
||||
currency: r.currency,
|
||||
rateToBase: Number(r.rateToBase),
|
||||
|
||||
@@ -18,13 +18,16 @@ import type { Response } from 'express';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import type { Actor } from '../common/record-scope';
|
||||
import { OrgModuleGuard } from '../billing/org-module.guard';
|
||||
import { RequireOrgModule } from '../billing/org-module.decorator';
|
||||
import { CreateDealDto, MoveDealDto, UpdateDealDto } from './dto';
|
||||
import { DealsService } from './deals.service';
|
||||
import { DealsExcelService } from './deals-excel.service';
|
||||
import { brand } from '@mento/shared';
|
||||
|
||||
@Controller('deals')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, OrgModuleGuard)
|
||||
@RequireOrgModule('pipeline')
|
||||
export class DealsController {
|
||||
constructor(
|
||||
private readonly dealsService: DealsService,
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import {
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsEmail,
|
||||
IsIn,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
Min,
|
||||
MinLength,
|
||||
ValidateIf,
|
||||
} from 'class-validator';
|
||||
@@ -119,3 +122,32 @@ export class ResetPlatformUserPasswordDto {
|
||||
@MaxLength(120)
|
||||
password!: string;
|
||||
}
|
||||
|
||||
export class ApplyBillingPlanDto {
|
||||
@IsIn(['trial', 'monthly', 'quarterly', 'semiannual', 'yearly', 'custom'])
|
||||
planCode!: 'trial' | 'monthly' | 'quarterly' | 'semiannual' | 'yearly' | 'custom';
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
maxOrganizations?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
expiresAt?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(500)
|
||||
notes?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['active', 'expired', 'suspended'])
|
||||
status?: 'active' | 'expired' | 'suspended';
|
||||
}
|
||||
|
||||
export class UpdateOrgModulesDto {
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
enabledModules!: string[];
|
||||
}
|
||||
|
||||
@@ -10,10 +10,12 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import {
|
||||
ApplyBillingPlanDto,
|
||||
CreatePlatformAdminDto,
|
||||
CreatePlatformOrganizationDto,
|
||||
ResetPlatformAdminPasswordDto,
|
||||
ResetPlatformUserPasswordDto,
|
||||
UpdateOrgModulesDto,
|
||||
UpdatePlatformMembershipRoleDto,
|
||||
UpdatePlatformOrganizationDto,
|
||||
UpdatePlatformStatusDto,
|
||||
@@ -105,6 +107,19 @@ export class PlatformController {
|
||||
return this.platform.resetUserPassword(id, dto);
|
||||
}
|
||||
|
||||
@Post('users/:id/billing/apply-plan')
|
||||
applyBillingPlan(@Param('id') id: string, @Body() dto: ApplyBillingPlanDto) {
|
||||
return this.platform.applyBillingPlan(id, dto);
|
||||
}
|
||||
|
||||
@Patch('organizations/:id/modules')
|
||||
updateOrganizationModules(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateOrgModulesDto,
|
||||
) {
|
||||
return this.platform.updateOrganizationModules(id, dto);
|
||||
}
|
||||
|
||||
@Patch('memberships/:id')
|
||||
setMembershipActive(
|
||||
@Param('id') id: string,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { AuthModule } from '../auth/auth.module';
|
||||
import { MembershipsModule } from '../memberships/memberships.module';
|
||||
import { OrgRolesModule } from '../org-roles/org-roles.module';
|
||||
import { PipelinesModule } from '../pipelines/pipelines.module';
|
||||
import { BillingModule } from '../billing/billing.module';
|
||||
import { PlatformAuthController } from './platform-auth.controller';
|
||||
import { PlatformAuthGuard } from './platform-auth.guard';
|
||||
import { PlatformAuthService } from './platform-auth.service';
|
||||
@@ -17,6 +18,7 @@ import { PlatformService } from './platform.service';
|
||||
MembershipsModule,
|
||||
OrgRolesModule,
|
||||
PipelinesModule,
|
||||
BillingModule,
|
||||
PassportModule,
|
||||
],
|
||||
controllers: [PlatformAuthController, PlatformController],
|
||||
|
||||
@@ -18,12 +18,15 @@ import { normalizeMobile } from '../auth/auth.service';
|
||||
import { MembershipsService } from '../memberships/memberships.service';
|
||||
import { OrgRolesService } from '../org-roles/org-roles.service';
|
||||
import { PipelinesService } from '../pipelines/pipelines.service';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type {
|
||||
ApplyBillingPlanDto,
|
||||
CreatePlatformAdminDto,
|
||||
CreatePlatformOrganizationDto,
|
||||
ResetPlatformAdminPasswordDto,
|
||||
ResetPlatformUserPasswordDto,
|
||||
UpdateOrgModulesDto,
|
||||
UpdatePlatformOrganizationDto,
|
||||
} from './dto';
|
||||
|
||||
@@ -45,6 +48,7 @@ export class PlatformService {
|
||||
private readonly memberships: MembershipsService,
|
||||
private readonly orgRoles: OrgRolesService,
|
||||
private readonly pipelines: PipelinesService,
|
||||
private readonly billing: BillingService,
|
||||
) {}
|
||||
|
||||
async stats(): Promise<PlatformStatsDto> {
|
||||
@@ -61,12 +65,18 @@ export class PlatformService {
|
||||
this.prisma.user.count({ where: { isActive: true } }),
|
||||
this.prisma.membership.count(),
|
||||
]);
|
||||
const [expiringSoonCount, expiredBillingCount] = await Promise.all([
|
||||
this.billing.countExpiringSoon(),
|
||||
this.billing.countExpired(),
|
||||
]);
|
||||
return {
|
||||
organizationCount,
|
||||
activeOrganizationCount,
|
||||
userCount,
|
||||
activeUserCount,
|
||||
membershipCount,
|
||||
expiringSoonCount,
|
||||
expiredBillingCount,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -89,6 +99,7 @@ export class PlatformService {
|
||||
businessField: true,
|
||||
isActive: true,
|
||||
createdAt: true,
|
||||
enabledModules: true,
|
||||
_count: {
|
||||
select: {
|
||||
memberships: true,
|
||||
@@ -111,6 +122,7 @@ export class PlatformService {
|
||||
businessField: true,
|
||||
isActive: true,
|
||||
createdAt: true,
|
||||
enabledModules: true,
|
||||
_count: {
|
||||
select: {
|
||||
memberships: true,
|
||||
@@ -213,6 +225,7 @@ export class PlatformService {
|
||||
name,
|
||||
slug,
|
||||
businessField,
|
||||
enabledModules: this.billing.defaultModulesForNewOrg(),
|
||||
users: {
|
||||
create: {
|
||||
email: ownerEmail,
|
||||
@@ -238,6 +251,7 @@ export class PlatformService {
|
||||
organizationId: organization.id,
|
||||
role: 'owner',
|
||||
});
|
||||
await this.billing.ensureTrialForOwner(owner.id, { maxOrganizations: 1 });
|
||||
await this.orgRoles.ensureDefaultRoles(organization.id);
|
||||
await this.pipelines.ensureDefaultPipeline(organization.id);
|
||||
|
||||
@@ -331,6 +345,7 @@ export class PlatformService {
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 300,
|
||||
include: {
|
||||
billingAccount: true,
|
||||
memberships: {
|
||||
include: {
|
||||
organization: {
|
||||
@@ -356,12 +371,33 @@ export class PlatformService {
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
},
|
||||
billingAccount: true,
|
||||
},
|
||||
});
|
||||
if (!row) throw new NotFoundException('کاربر پیدا نشد');
|
||||
return this.userToDto(row);
|
||||
}
|
||||
|
||||
async applyBillingPlan(userId: string, dto: ApplyBillingPlanDto) {
|
||||
const existing = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) throw new NotFoundException('کاربر پیدا نشد');
|
||||
await this.billing.applyPlan(userId, dto);
|
||||
return this.getUser(userId);
|
||||
}
|
||||
|
||||
async updateOrganizationModules(id: string, dto: UpdateOrgModulesDto) {
|
||||
const existing = await this.prisma.organization.findUnique({
|
||||
where: { id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) throw new NotFoundException('محیط پیدا نشد');
|
||||
await this.billing.setOrgModules(id, dto.enabledModules ?? []);
|
||||
return this.getOrganization(id);
|
||||
}
|
||||
|
||||
async setUserActive(id: string, isActive: boolean): Promise<PlatformUserDto> {
|
||||
const existing = await this.prisma.user.findUnique({
|
||||
where: { id },
|
||||
@@ -609,6 +645,7 @@ export class PlatformService {
|
||||
businessField: string | null;
|
||||
isActive: boolean;
|
||||
createdAt: Date;
|
||||
enabledModules?: string[];
|
||||
_count: { memberships: number; people: number; deals: number };
|
||||
}): PlatformOrganizationDto {
|
||||
return {
|
||||
@@ -621,6 +658,7 @@ export class PlatformService {
|
||||
memberCount: row._count.memberships,
|
||||
personCount: row._count.people,
|
||||
dealCount: row._count.deals,
|
||||
enabledModules: this.billing.normalizeModules(row.enabledModules),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -632,6 +670,17 @@ export class PlatformService {
|
||||
isActive: boolean;
|
||||
lastLoginAt: Date | null;
|
||||
createdAt: Date;
|
||||
billingAccount?: {
|
||||
id: string;
|
||||
ownerUserId: string;
|
||||
planCode: string;
|
||||
status: string;
|
||||
startsAt: Date;
|
||||
expiresAt: Date;
|
||||
maxOrganizations: number;
|
||||
externalPaymentRef: string | null;
|
||||
notes: string | null;
|
||||
} | null;
|
||||
memberships: Array<{
|
||||
id: string;
|
||||
role: PlatformUserDto['memberships'][number]['role'];
|
||||
@@ -639,6 +688,9 @@ export class PlatformService {
|
||||
organization: { id: string; name: string; isActive: boolean };
|
||||
}>;
|
||||
}): PlatformUserDto {
|
||||
const isBillingOwner = row.memberships.some(
|
||||
(m) => m.role === 'owner' && m.isActive,
|
||||
);
|
||||
return {
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
@@ -647,6 +699,11 @@ export class PlatformService {
|
||||
isActive: row.isActive,
|
||||
lastLoginAt: row.lastLoginAt?.toISOString() ?? null,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
isBillingOwner,
|
||||
billing:
|
||||
isBillingOwner && row.billingAccount
|
||||
? this.billing.toDto(row.billingAccount)
|
||||
: null,
|
||||
memberships: row.memberships.map((m) => ({
|
||||
membershipId: m.id,
|
||||
organizationId: m.organization.id,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { RouterLink, RouterView, useRouter } from 'vue-router';
|
||||
import { RouterLink, RouterView, useRoute, useRouter } from 'vue-router';
|
||||
import { usePlatformAuthStore } from '@/stores/platform-auth';
|
||||
import UiIcon from '@/components/UiIcon.vue';
|
||||
import MentoLogo from '@/components/brand/MentoLogo.vue';
|
||||
@@ -8,9 +8,32 @@ import BrandName from '@/components/brand/BrandName.vue';
|
||||
|
||||
const platform = usePlatformAuthStore();
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
|
||||
const displayName = computed(() => platform.admin?.fullName || 'سوپرادمین');
|
||||
|
||||
const pageTitle = computed(() => {
|
||||
switch (route.name) {
|
||||
case 'adm-dashboard':
|
||||
return 'داشبورد';
|
||||
case 'adm-organizations':
|
||||
return 'محیطها';
|
||||
case 'adm-users':
|
||||
return 'کاربران';
|
||||
case 'adm-admins':
|
||||
return 'ادمینها';
|
||||
default:
|
||||
return 'سوپرادمین';
|
||||
}
|
||||
});
|
||||
|
||||
const tabs = [
|
||||
{ name: 'adm-dashboard', label: 'خانه', icon: 'home' as const },
|
||||
{ name: 'adm-organizations', label: 'محیطها', icon: 'building' as const },
|
||||
{ name: 'adm-users', label: 'کاربران', icon: 'users' as const },
|
||||
{ name: 'adm-admins', label: 'ادمینها', icon: 'lock' as const },
|
||||
];
|
||||
|
||||
function onLogout() {
|
||||
platform.logout();
|
||||
void router.push({ name: 'adm-login' });
|
||||
@@ -19,36 +42,41 @@ function onLogout() {
|
||||
|
||||
<template>
|
||||
<div class="adm-shell">
|
||||
<aside class="sidebar">
|
||||
<aside class="sidebar desktop-only">
|
||||
<div class="brand">
|
||||
<MentoLogo :size="32" :show-text="false" />
|
||||
<div class="brand-mark">
|
||||
<MentoLogo :size="36" :show-text="false" />
|
||||
</div>
|
||||
<div class="brand-copy">
|
||||
<BrandName />
|
||||
<span>پنل سوپرادمین</span>
|
||||
<span>کنترل پلتفرم</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="nav">
|
||||
<RouterLink :to="{ name: 'adm-dashboard' }" class="nav-item">
|
||||
<UiIcon name="home" :size="18" />
|
||||
<span>داشبورد</span>
|
||||
</RouterLink>
|
||||
<RouterLink :to="{ name: 'adm-organizations' }" class="nav-item">
|
||||
<UiIcon name="building" :size="18" />
|
||||
<span>محیطها</span>
|
||||
</RouterLink>
|
||||
<RouterLink :to="{ name: 'adm-users' }" class="nav-item">
|
||||
<UiIcon name="users" :size="18" />
|
||||
<span>کاربران</span>
|
||||
</RouterLink>
|
||||
<RouterLink :to="{ name: 'adm-admins' }" class="nav-item">
|
||||
<UiIcon name="lock" :size="18" />
|
||||
<span>ادمینها</span>
|
||||
<nav class="nav" aria-label="منوی سوپرادمین">
|
||||
<RouterLink
|
||||
v-for="tab in tabs"
|
||||
:key="tab.name"
|
||||
:to="{ name: tab.name }"
|
||||
class="nav-item"
|
||||
>
|
||||
<span class="nav-ico" aria-hidden="true">
|
||||
<UiIcon :name="tab.icon" :size="18" />
|
||||
</span>
|
||||
<span>{{ tab.label }}</span>
|
||||
</RouterLink>
|
||||
</nav>
|
||||
|
||||
<div class="side-foot">
|
||||
<p class="who">{{ displayName }}</p>
|
||||
<div class="who-card">
|
||||
<span class="who-avatar" aria-hidden="true">
|
||||
{{ displayName.slice(0, 1) }}
|
||||
</span>
|
||||
<div class="who-meta">
|
||||
<strong>{{ displayName }}</strong>
|
||||
<small>سوپرادمین</small>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="logout" @click="onLogout">
|
||||
<UiIcon name="logout" :size="16" />
|
||||
<span>خروج</span>
|
||||
@@ -56,9 +84,40 @@ function onLogout() {
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main class="main">
|
||||
<RouterView />
|
||||
</main>
|
||||
<div class="stage">
|
||||
<header class="topbar">
|
||||
<div class="top-brand mobile-only">
|
||||
<MentoLogo :size="28" :show-text="false" />
|
||||
<div>
|
||||
<strong>{{ pageTitle }}</strong>
|
||||
<small>سوپرادمین</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="top-desktop desktop-only">
|
||||
<h1>{{ pageTitle }}</h1>
|
||||
<p>مدیریت حسابها، اشتراک و ماژولها</p>
|
||||
</div>
|
||||
<button type="button" class="logout-top mobile-only" @click="onLogout">
|
||||
<UiIcon name="logout" :size="18" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<main class="main">
|
||||
<RouterView />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<nav class="tabbar" aria-label="ناوبری پایین">
|
||||
<RouterLink
|
||||
v-for="tab in tabs"
|
||||
:key="tab.name"
|
||||
:to="{ name: tab.name }"
|
||||
class="tab"
|
||||
>
|
||||
<UiIcon :name="tab.icon" :size="20" />
|
||||
<span>{{ tab.label }}</span>
|
||||
</RouterLink>
|
||||
</nav>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -67,119 +126,299 @@ function onLogout() {
|
||||
min-height: 100vh;
|
||||
min-height: 100dvh;
|
||||
display: grid;
|
||||
grid-template-columns: 240px minmax(0, 1fr);
|
||||
background: var(--bg);
|
||||
grid-template-columns: 260px minmax(0, 1fr);
|
||||
background:
|
||||
radial-gradient(ellipse 70% 45% at 100% -10%, rgba(20, 184, 166, 0.14), transparent 55%),
|
||||
radial-gradient(ellipse 50% 35% at 0% 100%, rgba(14, 165, 233, 0.08), transparent 50%),
|
||||
linear-gradient(180deg, #f4fbfa 0%, var(--bg) 40%);
|
||||
}
|
||||
|
||||
.desktop-only {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.mobile-only {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.2rem;
|
||||
padding: 1.15rem 0.9rem;
|
||||
background: #fff;
|
||||
border-inline-end: 1px solid var(--line);
|
||||
gap: 1.35rem;
|
||||
padding: 1.25rem 1rem;
|
||||
background: rgba(255, 255, 255, 0.86);
|
||||
backdrop-filter: blur(12px);
|
||||
border-inline-end: 1px solid color-mix(in srgb, var(--line) 80%, transparent);
|
||||
box-shadow: 10px 0 40px rgba(15, 23, 42, 0.04);
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.7rem;
|
||||
padding: 0.2rem 0.35rem;
|
||||
gap: 0.75rem;
|
||||
padding: 0.35rem 0.4rem;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 16px;
|
||||
background: linear-gradient(145deg, var(--accent-subtle), #fff);
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 18%, white);
|
||||
box-shadow: 0 8px 20px rgba(13, 148, 136, 0.08);
|
||||
}
|
||||
|
||||
.brand-copy {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
gap: 0.1rem;
|
||||
}
|
||||
|
||||
.brand-copy span {
|
||||
color: var(--muted);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.nav {
|
||||
display: grid;
|
||||
gap: 0.25rem;
|
||||
gap: 0.35rem;
|
||||
flex: 1;
|
||||
align-content: start;
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
padding: 0.7rem 0.8rem;
|
||||
border-radius: 12px;
|
||||
gap: 0.7rem;
|
||||
padding: 0.72rem 0.8rem;
|
||||
border-radius: 14px;
|
||||
color: var(--ink-secondary);
|
||||
text-decoration: none;
|
||||
font-weight: 700;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 750;
|
||||
font-size: 0.92rem;
|
||||
transition: background 0.15s ease, color 0.15s ease, transform 0.15s ease;
|
||||
}
|
||||
|
||||
.nav-item:hover {
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.nav-ico {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 11px;
|
||||
background: var(--surface-subtle);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.nav-item.router-link-active {
|
||||
background: var(--accent-subtle);
|
||||
background: linear-gradient(135deg, var(--accent-subtle), #fff);
|
||||
color: var(--accent-deep);
|
||||
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 22%, white);
|
||||
}
|
||||
|
||||
.nav-item.router-link-active .nav-ico {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.side-foot {
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
padding: 0.35rem;
|
||||
gap: 0.65rem;
|
||||
padding-top: 0.35rem;
|
||||
border-top: 1px solid var(--line-light);
|
||||
}
|
||||
|
||||
.who {
|
||||
margin: 0;
|
||||
.who-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.65rem;
|
||||
padding: 0.55rem;
|
||||
border-radius: 14px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--line-light);
|
||||
}
|
||||
|
||||
.who-avatar {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 12px;
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent-deep);
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.who-meta {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.who-meta strong {
|
||||
font-size: 0.86rem;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.who-meta small {
|
||||
color: var(--muted);
|
||||
font-size: 0.8rem;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.logout {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.4rem;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #94a3b8;
|
||||
border: 1px solid var(--line);
|
||||
background: #fff;
|
||||
color: var(--muted);
|
||||
font: inherit;
|
||||
font-size: 0.8rem;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 750;
|
||||
cursor: pointer;
|
||||
padding: 0.55rem 0.75rem;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.logout:hover {
|
||||
color: var(--danger);
|
||||
border-color: color-mix(in srgb, var(--danger) 30%, white);
|
||||
}
|
||||
|
||||
.stage {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100dvh;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem 1.5rem 0.85rem;
|
||||
background: color-mix(in srgb, #f4fbfa 78%, transparent);
|
||||
backdrop-filter: blur(14px);
|
||||
border-bottom: 1px solid transparent;
|
||||
}
|
||||
|
||||
.top-desktop h1 {
|
||||
margin: 0;
|
||||
font-size: 1.35rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.top-desktop p {
|
||||
margin: 0.2rem 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
.top-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.65rem;
|
||||
}
|
||||
|
||||
.top-brand strong {
|
||||
display: block;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.top-brand small {
|
||||
color: var(--muted);
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.logout-top {
|
||||
border: 0;
|
||||
background: #fff;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 12px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--muted);
|
||||
box-shadow: 0 4px 14px rgba(15, 23, 42, 0.06);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 1.4rem 1.5rem 2rem;
|
||||
padding: 0.4rem 1.5rem 2rem;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.tabbar {
|
||||
display: none;
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: 30;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 0.15rem;
|
||||
padding: 0.45rem 0.55rem calc(0.45rem + env(safe-area-inset-bottom));
|
||||
background: rgba(255, 255, 255, 0.92);
|
||||
backdrop-filter: blur(16px);
|
||||
border-top: 1px solid var(--line-light);
|
||||
box-shadow: 0 -10px 30px rgba(15, 23, 42, 0.06);
|
||||
}
|
||||
|
||||
.tab {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: 0.15rem;
|
||||
padding: 0.45rem 0.2rem;
|
||||
border-radius: 12px;
|
||||
text-decoration: none;
|
||||
color: var(--muted);
|
||||
font-size: 0.68rem;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.tab.router-link-active {
|
||||
color: var(--accent-deep);
|
||||
background: var(--accent-subtle);
|
||||
}
|
||||
|
||||
@media (max-width: 860px) {
|
||||
.adm-shell {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
border-inline-end: 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding-bottom: 0.75rem;
|
||||
.desktop-only {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.nav {
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
flex: none;
|
||||
.mobile-only {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
justify-content: center;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.side-foot {
|
||||
grid-template-columns: 1fr auto;
|
||||
align-items: center;
|
||||
.topbar {
|
||||
padding: 0.75rem 0.9rem;
|
||||
border-bottom: 1px solid var(--line-light);
|
||||
}
|
||||
|
||||
.main {
|
||||
padding: 1rem 0.9rem 1.6rem;
|
||||
padding: 0.75rem 0.9rem calc(1.2rem + env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
.tabbar {
|
||||
display: grid;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -79,17 +79,43 @@ const moreSectionActive = computed(
|
||||
settingsActive.value,
|
||||
);
|
||||
|
||||
const enabledModules = computed(() => auth.user?.enabledModules ?? null);
|
||||
const subscription = computed(() => auth.user?.subscription ?? null);
|
||||
|
||||
function moduleAllowed(module?: string) {
|
||||
if (!module) return true;
|
||||
if (!enabledModules.value) return true;
|
||||
return enabledModules.value.includes(module as never);
|
||||
}
|
||||
|
||||
const openHub = computed<NavHubDef | null>(() => {
|
||||
if (!openHubKey.value) return null;
|
||||
const hub = NAV_HUBS.find((item) => item.key === openHubKey.value);
|
||||
if (!hub) return null;
|
||||
return {
|
||||
...hub,
|
||||
cards: hub.cards.filter((card) => !card.admin || canSettings.value),
|
||||
shortcuts: hub.shortcuts.filter((item) => !item.admin || canSettings.value),
|
||||
cards: hub.cards.filter(
|
||||
(card) =>
|
||||
(!card.admin || canSettings.value) && moduleAllowed(card.module),
|
||||
),
|
||||
shortcuts: hub.shortcuts.filter(
|
||||
(item) =>
|
||||
(!item.admin || canSettings.value) && moduleAllowed(item.module),
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
const hubVisible = computed(() => {
|
||||
const map: Record<string, boolean> = {};
|
||||
for (const hub of NAV_HUBS) {
|
||||
map[hub.key] = hub.cards.some(
|
||||
(card) =>
|
||||
(!card.admin || canSettings.value) && moduleAllowed(card.module),
|
||||
);
|
||||
}
|
||||
return map;
|
||||
});
|
||||
|
||||
function givenName(fullName: string): string {
|
||||
const parts = fullName.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length <= 1) return fullName.trim();
|
||||
@@ -368,7 +394,7 @@ onUnmounted(() => {
|
||||
<span>داشبورد</span>
|
||||
</RouterLink>
|
||||
|
||||
<div class="nav-fold" :class="{ active: customersActive || openHubKey === 'customers' }">
|
||||
<div class="nav-fold" v-if="hubVisible.customers" :class="{ active: customersActive || openHubKey === 'customers' }">
|
||||
<button
|
||||
class="nav-item nav-fold-btn"
|
||||
type="button"
|
||||
@@ -383,7 +409,7 @@ onUnmounted(() => {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="nav-fold" :class="{ active: salesActive || openHubKey === 'sales' }">
|
||||
<div class="nav-fold" v-if="hubVisible.sales" :class="{ active: salesActive || openHubKey === 'sales' }">
|
||||
<button
|
||||
class="nav-item nav-fold-btn"
|
||||
type="button"
|
||||
@@ -398,7 +424,7 @@ onUnmounted(() => {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="nav-fold" :class="{ active: activitiesActive || openHubKey === 'activities' }">
|
||||
<div class="nav-fold" v-if="hubVisible.activities" :class="{ active: activitiesActive || openHubKey === 'activities' }">
|
||||
<button
|
||||
class="nav-item nav-fold-btn"
|
||||
type="button"
|
||||
@@ -600,6 +626,17 @@ onUnmounted(() => {
|
||||
<RouterLink class="round-btn" :to="{ name: 'tickets' }" title="پیامها">
|
||||
<UiIcon name="mail" :size="18" />
|
||||
</RouterLink>
|
||||
<div
|
||||
v-if="subscription"
|
||||
class="sub-chip"
|
||||
:class="{ warn: subscription.warn }"
|
||||
:title="`انقضا: ${subscription.expiresAt}`"
|
||||
>
|
||||
<UiIcon name="clock" :size="15" />
|
||||
<span>
|
||||
{{ toFaDigits(subscription.daysRemaining) }} روز باقیمانده
|
||||
</span>
|
||||
</div>
|
||||
<div class="date-chip">
|
||||
<UiIcon name="calendar" :size="16" />
|
||||
<span>{{ todayLabel }}</span>
|
||||
@@ -1601,6 +1638,24 @@ onUnmounted(() => {
|
||||
height: 34px;
|
||||
}
|
||||
|
||||
.sub-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.35rem 0.7rem;
|
||||
border-radius: 999px;
|
||||
background: var(--accent-subtle);
|
||||
color: var(--accent-deep);
|
||||
font-size: 0.78rem;
|
||||
font-weight: 800;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sub-chip.warn {
|
||||
background: color-mix(in srgb, var(--danger) 12%, white);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.date-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { OrgModuleKey } from '@mento/shared';
|
||||
|
||||
export type NavHubKey =
|
||||
| 'customers'
|
||||
| 'sales'
|
||||
@@ -43,6 +45,7 @@ export type NavHubCard = {
|
||||
icon: NavIconName;
|
||||
tint: NavHubTint;
|
||||
admin?: boolean;
|
||||
module?: OrgModuleKey;
|
||||
};
|
||||
|
||||
export type NavHubShortcut = {
|
||||
@@ -50,6 +53,7 @@ export type NavHubShortcut = {
|
||||
title: string;
|
||||
icon: NavIconName;
|
||||
admin?: boolean;
|
||||
module?: OrgModuleKey;
|
||||
};
|
||||
|
||||
export type NavHubDef = {
|
||||
@@ -70,8 +74,8 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
icon: 'users',
|
||||
tint: 'mint',
|
||||
shortcuts: [
|
||||
{ to: '/contacts/people/new', title: 'شخص جدید', icon: 'user-plus' },
|
||||
{ to: '/contacts/companies/new', title: 'شرکت جدید', icon: 'building' },
|
||||
{ to: '/contacts/people/new', title: 'شخص جدید', icon: 'user-plus', module: 'customers' },
|
||||
{ to: '/contacts/companies/new', title: 'شرکت جدید', icon: 'building', module: 'customers' },
|
||||
],
|
||||
cards: [
|
||||
{
|
||||
@@ -80,6 +84,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'مخاطبان حقیقی و پروندههای مشتری',
|
||||
icon: 'user',
|
||||
tint: 'mint',
|
||||
module: 'customers',
|
||||
},
|
||||
{
|
||||
to: '/contacts?tab=companies',
|
||||
@@ -87,6 +92,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'سازمانها و مشتریان حقوقی',
|
||||
icon: 'building',
|
||||
tint: 'violet',
|
||||
module: 'customers',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -97,8 +103,8 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
icon: 'briefcase',
|
||||
tint: 'mint',
|
||||
shortcuts: [
|
||||
{ to: '/deals/new', title: 'معامله جدید', icon: 'plus' },
|
||||
{ to: '/quotes/new', title: 'پیشفاکتور جدید', icon: 'document' },
|
||||
{ to: '/deals/new', title: 'معامله جدید', icon: 'plus', module: 'pipeline' },
|
||||
{ to: '/quotes/new', title: 'پیشفاکتور جدید', icon: 'document', module: 'quotes' },
|
||||
],
|
||||
cards: [
|
||||
{
|
||||
@@ -107,6 +113,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'سرنخها، معاملات و مراحل فروش',
|
||||
icon: 'filter',
|
||||
tint: 'mint',
|
||||
module: 'pipeline',
|
||||
},
|
||||
{
|
||||
to: '/settings/products',
|
||||
@@ -115,6 +122,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
icon: 'box',
|
||||
tint: 'peach',
|
||||
admin: true,
|
||||
module: 'products',
|
||||
},
|
||||
{
|
||||
to: '/invoices',
|
||||
@@ -122,6 +130,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'صدور فاکتور و پیگیری پرداختها',
|
||||
icon: 'mail',
|
||||
tint: 'sky',
|
||||
module: 'invoices',
|
||||
},
|
||||
{
|
||||
to: '/quotes',
|
||||
@@ -129,6 +138,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'پیشنهاد قیمت و پیگیری تایید',
|
||||
icon: 'document',
|
||||
tint: 'amber',
|
||||
module: 'quotes',
|
||||
},
|
||||
{
|
||||
to: '/commissions',
|
||||
@@ -136,6 +146,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'سهم فروشندگان از فاکتورهای صادرشده',
|
||||
icon: 'dollar',
|
||||
tint: 'rose',
|
||||
module: 'commissions',
|
||||
},
|
||||
{
|
||||
to: '/sales/forecast',
|
||||
@@ -143,6 +154,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'تعیین اهداف و تحلیل عملکرد فروش',
|
||||
icon: 'target',
|
||||
tint: 'mint',
|
||||
module: 'sales_forecast',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -153,8 +165,8 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
icon: 'check',
|
||||
tint: 'sky',
|
||||
shortcuts: [
|
||||
{ to: '/activities/new', title: 'فعالیت جدید', icon: 'plus' },
|
||||
{ to: '/activities/calendar', title: 'تقویم', icon: 'calendar' },
|
||||
{ to: '/activities/new', title: 'فعالیت جدید', icon: 'plus', module: 'activities' },
|
||||
{ to: '/activities/calendar', title: 'تقویم', icon: 'calendar', module: 'activities' },
|
||||
],
|
||||
cards: [
|
||||
{
|
||||
@@ -163,6 +175,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'کارها، تماسها و پیگیریهای جاری',
|
||||
icon: 'check',
|
||||
tint: 'mint',
|
||||
module: 'activities',
|
||||
},
|
||||
{
|
||||
to: '/activities/calendar',
|
||||
@@ -170,6 +183,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'نمای روز، هفته و زمانبندی کارها',
|
||||
icon: 'calendar',
|
||||
tint: 'violet',
|
||||
module: 'activities',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -180,8 +194,8 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
icon: 'chat',
|
||||
tint: 'peach',
|
||||
shortcuts: [
|
||||
{ to: '/tickets/new', title: 'تیکت جدید', icon: 'plus' },
|
||||
{ to: '/tickets', title: 'تیکتها', icon: 'chat' },
|
||||
{ to: '/tickets/new', title: 'تیکت جدید', icon: 'plus', module: 'tickets' },
|
||||
{ to: '/tickets', title: 'تیکتها', icon: 'chat', module: 'tickets' },
|
||||
],
|
||||
cards: [
|
||||
{
|
||||
@@ -190,6 +204,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'درخواستها و پیامهای پشتیبانی',
|
||||
icon: 'chat',
|
||||
tint: 'peach',
|
||||
module: 'tickets',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -200,8 +215,18 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
icon: 'sparkle',
|
||||
tint: 'violet',
|
||||
shortcuts: [
|
||||
{ to: '/settings/automations', title: 'قانون گردش کار', icon: 'layers' },
|
||||
{ to: '/settings/message-automations', title: 'قانون پیامک', icon: 'send' },
|
||||
{
|
||||
to: '/settings/automations',
|
||||
title: 'قانون گردش کار',
|
||||
icon: 'layers',
|
||||
module: 'workflow_automations',
|
||||
},
|
||||
{
|
||||
to: '/settings/message-automations',
|
||||
title: 'قانون پیامک',
|
||||
icon: 'send',
|
||||
module: 'message_automations',
|
||||
},
|
||||
],
|
||||
cards: [
|
||||
{
|
||||
@@ -211,6 +236,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
icon: 'layers',
|
||||
tint: 'violet',
|
||||
admin: true,
|
||||
module: 'workflow_automations',
|
||||
},
|
||||
{
|
||||
to: '/settings/message-automations',
|
||||
@@ -219,6 +245,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
icon: 'send',
|
||||
tint: 'sky',
|
||||
admin: true,
|
||||
module: 'message_automations',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -229,8 +256,8 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
icon: 'apps-plus',
|
||||
tint: 'violet',
|
||||
shortcuts: [
|
||||
{ to: '/project-cards/new', title: 'کارت پروژه جدید', icon: 'plus' },
|
||||
{ to: '/cheques', title: 'ثبت چک', icon: 'document' },
|
||||
{ to: '/project-cards/new', title: 'کارت پروژه جدید', icon: 'plus', module: 'project_boards' },
|
||||
{ to: '/cheques', title: 'ثبت چک', icon: 'document', module: 'cheques' },
|
||||
],
|
||||
cards: [
|
||||
{
|
||||
@@ -240,6 +267,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
icon: 'layers',
|
||||
tint: 'mint',
|
||||
admin: true,
|
||||
module: 'lead_forms',
|
||||
},
|
||||
{
|
||||
to: '/projects',
|
||||
@@ -247,6 +275,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'کارتها و مراحل اجرای کار',
|
||||
icon: 'flag',
|
||||
tint: 'violet',
|
||||
module: 'project_boards',
|
||||
},
|
||||
{
|
||||
to: '/inventory',
|
||||
@@ -254,6 +283,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'موجودی کالا و گردش داخلی',
|
||||
icon: 'box',
|
||||
tint: 'peach',
|
||||
module: 'inventory',
|
||||
},
|
||||
{
|
||||
to: '/cheques',
|
||||
@@ -261,6 +291,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'چکهای دریافتی و پرداختی',
|
||||
icon: 'document',
|
||||
tint: 'sky',
|
||||
module: 'cheques',
|
||||
},
|
||||
{
|
||||
to: '/attachments',
|
||||
@@ -268,6 +299,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'فایلهای متصل به یادداشتها',
|
||||
icon: 'document',
|
||||
tint: 'amber',
|
||||
module: 'attachments',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -278,8 +310,13 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
icon: 'settings',
|
||||
tint: 'sky',
|
||||
shortcuts: [
|
||||
{ to: '/settings/team#settings-team', title: 'تیم و نقشها', icon: 'users' },
|
||||
{ to: '/settings/tahesab', title: 'تهحساب', icon: 'chart' },
|
||||
{
|
||||
to: '/settings/team#settings-team',
|
||||
title: 'تیم و نقشها',
|
||||
icon: 'users',
|
||||
module: 'team_settings',
|
||||
},
|
||||
{ to: '/settings/tahesab', title: 'تهحساب', icon: 'chart', module: 'tahesab' },
|
||||
],
|
||||
cards: [
|
||||
{
|
||||
@@ -288,6 +325,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'نام سازمان و تنظیمات پایه',
|
||||
icon: 'building',
|
||||
tint: 'mint',
|
||||
module: 'team_settings',
|
||||
},
|
||||
{
|
||||
to: '/settings/team#settings-team',
|
||||
@@ -295,6 +333,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'اعضا، دسترسی و نقشها',
|
||||
icon: 'users',
|
||||
tint: 'violet',
|
||||
module: 'team_settings',
|
||||
},
|
||||
{
|
||||
to: '/settings/custom-fields',
|
||||
@@ -302,6 +341,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'فیلدهای اضافه روی پروندهها',
|
||||
icon: 'pencil',
|
||||
tint: 'peach',
|
||||
module: 'custom_fields',
|
||||
},
|
||||
{
|
||||
to: '/settings/currencies',
|
||||
@@ -309,6 +349,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'ارز پایه و نرخ تبدیل',
|
||||
icon: 'dollar',
|
||||
tint: 'sky',
|
||||
module: 'currencies',
|
||||
},
|
||||
{
|
||||
to: '/settings/tahesab',
|
||||
@@ -316,6 +357,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'اتصال مالی و تنظیمات حسابداری',
|
||||
icon: 'chart',
|
||||
tint: 'amber',
|
||||
module: 'tahesab',
|
||||
},
|
||||
{
|
||||
to: '/settings/faq',
|
||||
@@ -323,6 +365,7 @@ export const NAV_HUBS: NavHubDef[] = [
|
||||
desc: 'پرسشهای پرتکرار سازمان',
|
||||
icon: 'lightbulb',
|
||||
tint: 'rose',
|
||||
module: 'faq',
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -125,10 +125,7 @@ onMounted(() => {
|
||||
<template>
|
||||
<div class="page">
|
||||
<header class="head">
|
||||
<div>
|
||||
<h1>سوپرادمینها</h1>
|
||||
<p>افزودن ادمین با موبایل و رمز ثابت، فعال/غیرفعال و ریست رمز.</p>
|
||||
</div>
|
||||
<p class="lead">افزودن سوپرادمین با موبایل، فعال/غیرفعال و ریست رمز.</p>
|
||||
<button class="btn" type="button" @click="showCreate = !showCreate">
|
||||
{{ showCreate ? 'بستن فرم' : 'ادمین جدید' }}
|
||||
</button>
|
||||
@@ -234,26 +231,24 @@ onMounted(() => {
|
||||
<style scoped>
|
||||
.page {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
max-width: 1040px;
|
||||
gap: 0.95rem;
|
||||
max-width: 1080px;
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
gap: 0.85rem;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.head h1 {
|
||||
margin: 0 0 0.3rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.lead,
|
||||
.head p,
|
||||
.muted {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
@@ -270,10 +265,11 @@ onMounted(() => {
|
||||
.reset-panel {
|
||||
background: #fff;
|
||||
border: 1px solid #eef2f7;
|
||||
border-radius: 14px;
|
||||
border-radius: 18px;
|
||||
padding: 1rem;
|
||||
display: grid;
|
||||
gap: 0.85rem;
|
||||
box-shadow: 0 10px 28px rgba(15, 23, 42, 0.04);
|
||||
}
|
||||
|
||||
.panel h2 {
|
||||
@@ -319,11 +315,12 @@ input {
|
||||
.row {
|
||||
background: #fff;
|
||||
border: 1px solid #eef2f7;
|
||||
border-radius: 14px;
|
||||
padding: 0.85rem 1rem;
|
||||
border-radius: 18px;
|
||||
padding: 0.95rem 1rem;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 0.7rem 1rem;
|
||||
box-shadow: 0 8px 22px rgba(15, 23, 42, 0.035);
|
||||
}
|
||||
|
||||
.row-main {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import axios from 'axios';
|
||||
import type { PlatformStatsDto } from '@mento/shared';
|
||||
import { platformApi } from '@/lib/platform-api';
|
||||
import { toFaDigits } from '@/lib/jalali';
|
||||
@@ -19,10 +18,8 @@ async function load() {
|
||||
try {
|
||||
const { data } = await platformApi.get<PlatformStatsDto>('/platform/stats');
|
||||
stats.value = data;
|
||||
} catch (e) {
|
||||
error.value = axios.isAxiosError(e)
|
||||
? 'بارگذاری آمار ناموفق بود'
|
||||
: 'بارگذاری آمار ناموفق بود';
|
||||
} catch {
|
||||
error.value = 'بارگذاری آمار ناموفق بود';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
@@ -35,87 +32,146 @@ onMounted(() => {
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<header class="head">
|
||||
<div>
|
||||
<section class="hero">
|
||||
<div class="hero-copy">
|
||||
<p class="eyebrow">سوپرادمین</p>
|
||||
<h1>سلام {{ platform.admin?.fullName || '' }}</h1>
|
||||
<p class="lead">نمای کلی حسابها و محیطهای ثبتشده روی پلتفرم.</p>
|
||||
<h2>سلام {{ platform.admin?.fullName || '' }}</h2>
|
||||
<p class="lead">امروز وضعیت حسابها، اشتراکها و ماژولها را از اینجا کنترل کنید.</p>
|
||||
</div>
|
||||
</header>
|
||||
<div class="hero-orb" aria-hidden="true" />
|
||||
</section>
|
||||
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<p v-else-if="loading" class="muted">در حال بارگذاری…</p>
|
||||
|
||||
<div v-else-if="stats" class="kpis">
|
||||
<article class="kpi">
|
||||
<span class="ico"><UiIcon name="building" :size="20" /></span>
|
||||
<p>محیطها</p>
|
||||
<strong>{{ toFaDigits(stats.organizationCount) }}</strong>
|
||||
<small>{{ toFaDigits(stats.activeOrganizationCount) }} فعال</small>
|
||||
<span class="ico"><UiIcon name="building" :size="18" /></span>
|
||||
<div>
|
||||
<p>محیطها</p>
|
||||
<strong>{{ toFaDigits(stats.organizationCount) }}</strong>
|
||||
<small>{{ toFaDigits(stats.activeOrganizationCount) }} فعال</small>
|
||||
</div>
|
||||
</article>
|
||||
<article class="kpi">
|
||||
<span class="ico"><UiIcon name="users" :size="20" /></span>
|
||||
<p>کاربران</p>
|
||||
<strong>{{ toFaDigits(stats.userCount) }}</strong>
|
||||
<small>{{ toFaDigits(stats.activeUserCount) }} فعال</small>
|
||||
<span class="ico"><UiIcon name="users" :size="18" /></span>
|
||||
<div>
|
||||
<p>کاربران</p>
|
||||
<strong>{{ toFaDigits(stats.userCount) }}</strong>
|
||||
<small>{{ toFaDigits(stats.activeUserCount) }} فعال</small>
|
||||
</div>
|
||||
</article>
|
||||
<article class="kpi">
|
||||
<span class="ico"><UiIcon name="layers" :size="20" /></span>
|
||||
<p>عضویتها</p>
|
||||
<strong>{{ toFaDigits(stats.membershipCount) }}</strong>
|
||||
<small>نقش در محیطها</small>
|
||||
<span class="ico"><UiIcon name="layers" :size="18" /></span>
|
||||
<div>
|
||||
<p>عضویتها</p>
|
||||
<strong>{{ toFaDigits(stats.membershipCount) }}</strong>
|
||||
<small>نقش در محیطها</small>
|
||||
</div>
|
||||
</article>
|
||||
<article class="kpi warn">
|
||||
<span class="ico"><UiIcon name="clock" :size="18" /></span>
|
||||
<div>
|
||||
<p>نزدیک انقضا</p>
|
||||
<strong>{{ toFaDigits(stats.expiringSoonCount ?? 0) }}</strong>
|
||||
<small>کمتر از ۳ روز</small>
|
||||
</div>
|
||||
</article>
|
||||
<article class="kpi danger">
|
||||
<span class="ico"><UiIcon name="warning" :size="18" /></span>
|
||||
<div>
|
||||
<p>منقضی</p>
|
||||
<strong>{{ toFaDigits(stats.expiredBillingCount ?? 0) }}</strong>
|
||||
<small>نیاز به تمدید</small>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div class="shortcuts">
|
||||
<RouterLink :to="{ name: 'adm-organizations' }" class="card">
|
||||
<UiIcon name="building" :size="18" />
|
||||
<div>
|
||||
<strong>مدیریت محیطها</strong>
|
||||
<span>ساخت، ویرایش و فعال/غیرفعال کردن سازمانها</span>
|
||||
</div>
|
||||
</RouterLink>
|
||||
<RouterLink :to="{ name: 'adm-users' }" class="card">
|
||||
<UiIcon name="users" :size="18" />
|
||||
<div>
|
||||
<strong>مدیریت کاربران</strong>
|
||||
<span>نقش، دسترسی و ریست رمز عبور</span>
|
||||
</div>
|
||||
</RouterLink>
|
||||
<RouterLink :to="{ name: 'adm-admins' }" class="card">
|
||||
<UiIcon name="lock" :size="18" />
|
||||
<div>
|
||||
<strong>سوپرادمینها</strong>
|
||||
<span>افزودن ادمین با موبایل و رمز</span>
|
||||
</div>
|
||||
</RouterLink>
|
||||
</div>
|
||||
<section class="actions">
|
||||
<h3>میانبرها</h3>
|
||||
<div class="shortcuts">
|
||||
<RouterLink :to="{ name: 'adm-organizations' }" class="card">
|
||||
<span class="card-ico mint"><UiIcon name="building" :size="18" /></span>
|
||||
<div>
|
||||
<strong>محیطها</strong>
|
||||
<span>ساخت، ماژول و فعال/غیرفعال</span>
|
||||
</div>
|
||||
<UiIcon name="chevron" :size="16" class="go" />
|
||||
</RouterLink>
|
||||
<RouterLink :to="{ name: 'adm-users' }" class="card">
|
||||
<span class="card-ico violet"><UiIcon name="users" :size="18" /></span>
|
||||
<div>
|
||||
<strong>کاربران</strong>
|
||||
<span>اشتراک مالک، نقش و ریست رمز</span>
|
||||
</div>
|
||||
<UiIcon name="chevron" :size="16" class="go" />
|
||||
</RouterLink>
|
||||
<RouterLink :to="{ name: 'adm-admins' }" class="card">
|
||||
<span class="card-ico peach"><UiIcon name="lock" :size="18" /></span>
|
||||
<div>
|
||||
<strong>ادمینها</strong>
|
||||
<span>افزودن سوپرادمین با موبایل</span>
|
||||
</div>
|
||||
<UiIcon name="chevron" :size="16" class="go" />
|
||||
</RouterLink>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
display: grid;
|
||||
gap: 1.2rem;
|
||||
max-width: 980px;
|
||||
gap: 1.15rem;
|
||||
max-width: 1080px;
|
||||
}
|
||||
|
||||
.head h1 {
|
||||
margin: 0.15rem 0 0.35rem;
|
||||
font-size: 1.45rem;
|
||||
.hero {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 22px;
|
||||
padding: 1.25rem 1.3rem;
|
||||
background:
|
||||
linear-gradient(135deg, rgba(20, 184, 166, 0.16), rgba(255, 255, 255, 0.92) 55%),
|
||||
#fff;
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 16%, white);
|
||||
box-shadow: 0 14px 36px rgba(15, 23, 42, 0.05);
|
||||
}
|
||||
|
||||
.hero-copy {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
max-width: 34rem;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0;
|
||||
color: var(--accent-deep);
|
||||
font-size: 0.78rem;
|
||||
font-weight: 800;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.hero h2 {
|
||||
margin: 0.25rem 0 0.35rem;
|
||||
font-size: clamp(1.35rem, 2.4vw, 1.7rem);
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.lead,
|
||||
.muted {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.hero-orb {
|
||||
position: absolute;
|
||||
inset-inline-end: -40px;
|
||||
top: -50px;
|
||||
width: 180px;
|
||||
height: 180px;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(circle, rgba(45, 212, 191, 0.35), transparent 70%);
|
||||
}
|
||||
|
||||
.error {
|
||||
@@ -125,70 +181,135 @@ onMounted(() => {
|
||||
|
||||
.kpis {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 0.85rem;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.kpi {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
align-items: flex-start;
|
||||
background: #fff;
|
||||
border: 1px solid #eef2f7;
|
||||
border-radius: 14px;
|
||||
padding: 1rem 1.05rem;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
border-radius: 18px;
|
||||
padding: 0.95rem;
|
||||
box-shadow: 0 10px 28px rgba(15, 23, 42, 0.04);
|
||||
}
|
||||
|
||||
.kpi p,
|
||||
.kpi small {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 0.82rem;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.kpi strong {
|
||||
display: block;
|
||||
margin: 0.2rem 0 0.15rem;
|
||||
font-size: 1.55rem;
|
||||
margin: 0.15rem 0;
|
||||
font-size: 1.4rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.ico {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
margin-bottom: 0.55rem;
|
||||
border-radius: 10px;
|
||||
flex: 0 0 auto;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: 12px;
|
||||
background: var(--accent-subtle);
|
||||
color: var(--accent-deep);
|
||||
}
|
||||
|
||||
.kpi.warn .ico {
|
||||
background: var(--warning-soft);
|
||||
color: var(--warning-deep);
|
||||
}
|
||||
|
||||
.kpi.danger .ico {
|
||||
background: var(--danger-soft);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.actions h3 {
|
||||
margin: 0 0 0.65rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.shortcuts {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 0.85rem;
|
||||
gap: 0.65rem;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 0.8rem;
|
||||
padding: 1rem 1.05rem;
|
||||
gap: 0.85rem;
|
||||
padding: 0.95rem 1rem;
|
||||
background: #fff;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
border: 1px solid var(--line-light);
|
||||
border-radius: 18px;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
box-shadow: 0 8px 22px rgba(15, 23, 42, 0.04);
|
||||
transition: transform 0.15s ease, box-shadow 0.15s ease;
|
||||
}
|
||||
|
||||
.card:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 14px 28px rgba(15, 23, 42, 0.07);
|
||||
}
|
||||
|
||||
.card span {
|
||||
display: block;
|
||||
color: var(--muted);
|
||||
font-size: 0.82rem;
|
||||
font-size: 0.8rem;
|
||||
margin-top: 0.15rem;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.kpis,
|
||||
.shortcuts {
|
||||
.card-ico {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.card-ico.mint {
|
||||
background: var(--accent-subtle);
|
||||
color: var(--accent-deep);
|
||||
}
|
||||
|
||||
.card-ico.violet {
|
||||
background: #f3e8ff;
|
||||
color: #7c3aed;
|
||||
}
|
||||
|
||||
.card-ico.peach {
|
||||
background: #ffedd5;
|
||||
color: #c2410c;
|
||||
}
|
||||
|
||||
.go {
|
||||
color: var(--muted-light);
|
||||
}
|
||||
|
||||
@media (max-width: 980px) {
|
||||
.kpis {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
.kpis {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.hero {
|
||||
border-radius: 18px;
|
||||
padding: 1.1rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -3,11 +3,18 @@ import { onMounted, reactive, ref } from 'vue';
|
||||
import axios from 'axios';
|
||||
import type {
|
||||
CreatePlatformOrganizationRequest,
|
||||
OrgModuleKey,
|
||||
PlatformOrganizationDto,
|
||||
UpdatePlatformOrganizationRequest,
|
||||
UserRole,
|
||||
} from '@mento/shared';
|
||||
import { USER_ROLE_LABELS, USER_ROLES, isBusinessField } from '@mento/shared';
|
||||
import {
|
||||
ORG_MODULE_GROUPS,
|
||||
ORG_MODULE_LABELS,
|
||||
USER_ROLE_LABELS,
|
||||
USER_ROLES,
|
||||
isBusinessField,
|
||||
} from '@mento/shared';
|
||||
import { platformApi } from '@/lib/platform-api';
|
||||
import { BUSINESS_FIELDS, BUSINESS_FIELD_LABELS } from '@/lib/business-fields';
|
||||
import { formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
|
||||
@@ -40,6 +47,9 @@ const editForm = reactive({
|
||||
businessField: '' as string,
|
||||
});
|
||||
|
||||
const moduleDraft = ref<OrgModuleKey[]>([]);
|
||||
const savingModules = ref(false);
|
||||
|
||||
function fieldLabel(value?: string | null) {
|
||||
if (!value) return '—';
|
||||
return isBusinessField(value) ? BUSINESS_FIELD_LABELS[value] : value;
|
||||
@@ -92,6 +102,7 @@ async function toggleOpen(org: PlatformOrganizationDto) {
|
||||
`/platform/organizations/${org.id}`,
|
||||
);
|
||||
detail.value = data;
|
||||
moduleDraft.value = [...(data.enabledModules ?? [])];
|
||||
} catch (e) {
|
||||
error.value = apiError(e, 'بارگذاری اعضا ناموفق بود');
|
||||
}
|
||||
@@ -222,6 +233,7 @@ async function setMembershipRole(membershipId: string, role: UserRole) {
|
||||
`/platform/organizations/${openId.value}`,
|
||||
);
|
||||
detail.value = data;
|
||||
moduleDraft.value = [...(data.enabledModules ?? [])];
|
||||
}
|
||||
} catch (e) {
|
||||
error.value = apiError(e, 'تغییر نقش ناموفق بود');
|
||||
@@ -230,6 +242,41 @@ async function setMembershipRole(membershipId: string, role: UserRole) {
|
||||
}
|
||||
}
|
||||
|
||||
function toggleModule(key: OrgModuleKey) {
|
||||
if (moduleDraft.value.includes(key)) {
|
||||
moduleDraft.value = moduleDraft.value.filter((k) => k !== key);
|
||||
} else {
|
||||
moduleDraft.value = [...moduleDraft.value, key];
|
||||
}
|
||||
}
|
||||
|
||||
function selectGroup(keys: OrgModuleKey[], on: boolean) {
|
||||
if (on) {
|
||||
moduleDraft.value = [...new Set([...moduleDraft.value, ...keys])];
|
||||
} else {
|
||||
moduleDraft.value = moduleDraft.value.filter((k) => !keys.includes(k));
|
||||
}
|
||||
}
|
||||
|
||||
async function saveModules(orgId: string) {
|
||||
savingModules.value = true;
|
||||
error.value = '';
|
||||
success.value = '';
|
||||
try {
|
||||
const { data } = await platformApi.patch<PlatformOrganizationDto>(
|
||||
`/platform/organizations/${orgId}/modules`,
|
||||
{ enabledModules: moduleDraft.value },
|
||||
);
|
||||
detail.value = data;
|
||||
moduleDraft.value = [...(data.enabledModules ?? [])];
|
||||
success.value = 'ماژولهای محیط ذخیره شد';
|
||||
} catch (e) {
|
||||
error.value = apiError(e, 'ذخیره ماژولها ناموفق بود');
|
||||
} finally {
|
||||
savingModules.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
});
|
||||
@@ -238,10 +285,7 @@ onMounted(() => {
|
||||
<template>
|
||||
<div class="page">
|
||||
<header class="head">
|
||||
<div>
|
||||
<h1>محیطها</h1>
|
||||
<p>ساخت، ویرایش و فعال/غیرفعال کردن سازمانها و نقش اعضا.</p>
|
||||
</div>
|
||||
<p class="lead">ساخت، ویرایش، ماژولها و نقش اعضا.</p>
|
||||
<div class="head-actions">
|
||||
<form class="search" @submit.prevent="load">
|
||||
<input v-model="query" type="search" placeholder="جستجوی نام یا اسلاگ" />
|
||||
@@ -355,6 +399,47 @@ onMounted(() => {
|
||||
</form>
|
||||
|
||||
<div v-if="openId === org.id" class="detail">
|
||||
<div class="modules">
|
||||
<div class="modules-head">
|
||||
<strong>ماژولهای فعال</strong>
|
||||
<button
|
||||
class="btn"
|
||||
type="button"
|
||||
:disabled="savingModules"
|
||||
@click="saveModules(org.id)"
|
||||
>
|
||||
{{ savingModules ? 'ذخیره…' : 'ذخیره ماژولها' }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-for="group in ORG_MODULE_GROUPS" :key="group.title" class="mod-group">
|
||||
<div class="mod-group-head">
|
||||
<span>{{ group.title }}</span>
|
||||
<button
|
||||
class="btn btn-ghost"
|
||||
type="button"
|
||||
@click="selectGroup(group.keys, true)"
|
||||
>
|
||||
همه
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-ghost"
|
||||
type="button"
|
||||
@click="selectGroup(group.keys, false)"
|
||||
>
|
||||
هیچکدام
|
||||
</button>
|
||||
</div>
|
||||
<label v-for="key in group.keys" :key="key" class="mod-item">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="moduleDraft.includes(key)"
|
||||
@change="toggleModule(key)"
|
||||
/>
|
||||
{{ ORG_MODULE_LABELS[key] }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="!detail?.members?.length" class="muted">عضوی ثبت نشده.</p>
|
||||
<ul v-else>
|
||||
<li v-for="member in detail.members" :key="member.membershipId">
|
||||
@@ -400,37 +485,41 @@ onMounted(() => {
|
||||
<style scoped>
|
||||
.page {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
max-width: 1040px;
|
||||
gap: 0.95rem;
|
||||
max-width: 1080px;
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
gap: 0.85rem;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.head h1 {
|
||||
margin: 0 0 0.3rem;
|
||||
}
|
||||
|
||||
.lead,
|
||||
.head p,
|
||||
.muted {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
.head-actions {
|
||||
display: flex;
|
||||
gap: 0.6rem;
|
||||
gap: 0.55rem;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.search {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
gap: 0.45rem;
|
||||
padding: 0.25rem;
|
||||
border-radius: 14px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--line-light);
|
||||
box-shadow: 0 6px 18px rgba(15, 23, 42, 0.04);
|
||||
}
|
||||
|
||||
.search input,
|
||||
@@ -440,14 +529,16 @@ onMounted(() => {
|
||||
.edit-panel select,
|
||||
.member-actions select {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 0.65rem 0.8rem;
|
||||
border-radius: 12px;
|
||||
padding: 0.6rem 0.75rem;
|
||||
font: inherit;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.search input {
|
||||
min-width: 220px;
|
||||
min-width: 180px;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.error {
|
||||
@@ -464,10 +555,11 @@ onMounted(() => {
|
||||
.edit-panel {
|
||||
background: #fff;
|
||||
border: 1px solid #eef2f7;
|
||||
border-radius: 14px;
|
||||
border-radius: 18px;
|
||||
padding: 1rem;
|
||||
display: grid;
|
||||
gap: 0.85rem;
|
||||
box-shadow: 0 10px 28px rgba(15, 23, 42, 0.04);
|
||||
}
|
||||
|
||||
.panel h2 {
|
||||
@@ -505,11 +597,12 @@ label span {
|
||||
.row {
|
||||
background: #fff;
|
||||
border: 1px solid #eef2f7;
|
||||
border-radius: 14px;
|
||||
padding: 0.85rem 1rem;
|
||||
border-radius: 18px;
|
||||
padding: 0.95rem 1rem;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 0.7rem 1rem;
|
||||
box-shadow: 0 8px 22px rgba(15, 23, 42, 0.035);
|
||||
}
|
||||
|
||||
.row-main {
|
||||
@@ -572,6 +665,37 @@ label span {
|
||||
grid-column: 1 / -1;
|
||||
border-top: 1px solid var(--line);
|
||||
padding-top: 0.75rem;
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.modules {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
padding: 0.85rem;
|
||||
border-radius: 12px;
|
||||
background: #f8fafc;
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.modules-head,
|
||||
.mod-group-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.mod-group {
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.mod-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
.detail ul {
|
||||
@@ -607,5 +731,18 @@ label span {
|
||||
.edit-panel {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.search {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.search input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import axios from 'axios';
|
||||
import type { PlatformUserDto, UserRole } from '@mento/shared';
|
||||
import { USER_ROLE_LABELS, USER_ROLES } from '@mento/shared';
|
||||
import type {
|
||||
ApplyBillingPlanRequest,
|
||||
BillingPlanCode,
|
||||
PlatformUserDto,
|
||||
UserRole,
|
||||
} from '@mento/shared';
|
||||
import {
|
||||
BILLING_PLAN_CODES,
|
||||
BILLING_PLAN_LABELS,
|
||||
USER_ROLE_LABELS,
|
||||
USER_ROLES,
|
||||
} from '@mento/shared';
|
||||
import { platformApi } from '@/lib/platform-api';
|
||||
import { formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
|
||||
|
||||
@@ -121,6 +131,25 @@ async function setMembershipRole(userId: string, membershipId: string, role: Use
|
||||
}
|
||||
}
|
||||
|
||||
async function applyPlan(userId: string, planCode: BillingPlanCode) {
|
||||
busyId.value = `plan-${userId}-${planCode}`;
|
||||
error.value = '';
|
||||
success.value = '';
|
||||
try {
|
||||
const body: ApplyBillingPlanRequest = { planCode };
|
||||
const { data } = await platformApi.post<PlatformUserDto>(
|
||||
`/platform/users/${userId}/billing/apply-plan`,
|
||||
body,
|
||||
);
|
||||
items.value = items.value.map((row) => (row.id === userId ? data : row));
|
||||
success.value = `پلن «${BILLING_PLAN_LABELS[planCode]}» اعمال شد`;
|
||||
} catch (e) {
|
||||
error.value = apiError(e, 'اعمال پلن ناموفق بود');
|
||||
} finally {
|
||||
busyId.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
});
|
||||
@@ -129,10 +158,7 @@ onMounted(() => {
|
||||
<template>
|
||||
<div class="page">
|
||||
<header class="head">
|
||||
<div>
|
||||
<h1>کاربران</h1>
|
||||
<p>فعال/غیرفعال حساب، نقش عضویت و ریست رمز عبور.</p>
|
||||
</div>
|
||||
<p class="lead">اشتراک مالک، نقش عضویت و ریست رمز.</p>
|
||||
<form class="search" @submit.prevent="load">
|
||||
<input v-model="query" type="search" placeholder="نام، ایمیل یا موبایل" />
|
||||
<button class="btn" type="submit" :disabled="loading">جستجو</button>
|
||||
@@ -201,6 +227,32 @@ onMounted(() => {
|
||||
</form>
|
||||
|
||||
<div v-if="openId === user.id" class="detail">
|
||||
<div v-if="user.isBillingOwner" class="billing">
|
||||
<strong>اشتراک مالک</strong>
|
||||
<p v-if="user.billing" class="muted">
|
||||
{{ BILLING_PLAN_LABELS[user.billing.planCode] }}
|
||||
· {{ user.billing.status }}
|
||||
· {{ toFaDigits(user.billing.daysRemaining) }} روز
|
||||
· سقف محیط {{ toFaDigits(user.billing.maxOrganizations) }}
|
||||
</p>
|
||||
<p v-else class="muted">هنوز پلن ندارد — یکی از پلنها را اعمال کنید.</p>
|
||||
<div class="plan-row">
|
||||
<button
|
||||
v-for="code in BILLING_PLAN_CODES.filter((c) => c !== 'custom')"
|
||||
:key="code"
|
||||
class="btn btn-ghost"
|
||||
type="button"
|
||||
:disabled="busyId === `plan-${user.id}-${code}`"
|
||||
@click="applyPlan(user.id, code)"
|
||||
>
|
||||
{{ BILLING_PLAN_LABELS[code] }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="muted billing-skip">
|
||||
این کاربر عضو زیرمجموعه است و اشتراک جدا ندارد؛ اشتراک روی مالک محیط است.
|
||||
</p>
|
||||
|
||||
<p v-if="!user.memberships.length" class="muted">عضو هیچ محیطی نیست.</p>
|
||||
<ul v-else>
|
||||
<li v-for="mem in user.memberships" :key="mem.membershipId">
|
||||
@@ -246,44 +298,50 @@ onMounted(() => {
|
||||
<style scoped>
|
||||
.page {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
max-width: 1040px;
|
||||
gap: 0.95rem;
|
||||
max-width: 1080px;
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
gap: 0.85rem;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.head h1 {
|
||||
margin: 0 0 0.3rem;
|
||||
}
|
||||
|
||||
.lead,
|
||||
.head p,
|
||||
.muted {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
.search {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
gap: 0.45rem;
|
||||
padding: 0.25rem;
|
||||
border-radius: 14px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--line-light);
|
||||
box-shadow: 0 6px 18px rgba(15, 23, 42, 0.04);
|
||||
}
|
||||
|
||||
.search input,
|
||||
.reset-panel input,
|
||||
.member-actions select {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 0.65rem 0.8rem;
|
||||
border-radius: 12px;
|
||||
padding: 0.6rem 0.75rem;
|
||||
font: inherit;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.search input {
|
||||
min-width: 220px;
|
||||
min-width: 180px;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.error {
|
||||
@@ -304,11 +362,12 @@ onMounted(() => {
|
||||
.row {
|
||||
background: #fff;
|
||||
border: 1px solid #eef2f7;
|
||||
border-radius: 14px;
|
||||
padding: 0.85rem 1rem;
|
||||
border-radius: 18px;
|
||||
padding: 0.95rem 1rem;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 0.7rem 1rem;
|
||||
box-shadow: 0 8px 22px rgba(15, 23, 42, 0.035);
|
||||
}
|
||||
|
||||
.row-main {
|
||||
@@ -412,6 +471,26 @@ onMounted(() => {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.billing {
|
||||
margin-bottom: 0.85rem;
|
||||
padding: 0.75rem;
|
||||
border-radius: 12px;
|
||||
background: #f8fafc;
|
||||
border: 1px solid var(--line);
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
}
|
||||
|
||||
.plan-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.billing-skip {
|
||||
margin: 0 0 0.75rem;
|
||||
}
|
||||
|
||||
.member-actions {
|
||||
display: flex;
|
||||
gap: 0.45rem;
|
||||
|
||||
+5
-1
@@ -210,7 +210,11 @@ cd /var/www/crm/apps/api
|
||||
npx prisma db seed
|
||||
```
|
||||
|
||||
اگر حساب با همان موبایل از قبل باشد، seed آن را عوض نمیکند. ادمینهای بعدی را از داخل پنل (`/adm/admins`) اضافه کنید.
|
||||
اگر حساب با همان موبایل از قبل باشد، seed رمز را هم از `.env` بهروز میکند. ادمینهای بعدی را از داخل پنل (`/adm/admins`) اضافه کنید.
|
||||
|
||||
### اشتراک و ماژولها
|
||||
|
||||
بعد از این نسخه، `prisma migrate deploy` جدول `BillingAccount` و ستون `enabledModules` را میسازد و برای مالکان فعلی trial **۱۵ روزه** میسازد. از `/adm/users` پلن را تمدید کنید و از `/adm/organizations` ماژول هر محیط را تنظیم کنید.
|
||||
|
||||
3. ورود: `https://crm.montzar.ir/adm` → داشبورد `/adm/dashboard`
|
||||
توکن سوپرادمین جدا از JWT کاربران سازمانی است.
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# BillingAccount + Modules Implementation Plan
|
||||
|
||||
> **For agentic workers:** Execute task-by-task. Checkboxes track progress.
|
||||
|
||||
**Goal:** Owner-level `BillingAccount` (plans/expiry/max orgs), per-org `enabledModules`, CRM enforcement + remaining-days UI, `/adm` controls and polish.
|
||||
|
||||
**Architecture:** Shared module catalog; Prisma `BillingAccount` + `Organization.enabledModules`; billing checks on login/org-create; module guards on API + filtered nav; platform admin APIs/UI for plans and modules.
|
||||
|
||||
**Tech Stack:** NestJS, Prisma, Vue 3, `@mento/shared`, existing CRM CSS tokens.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Manual activation only (no payment gateway).
|
||||
- Existing owners: trial 15 days; `maxOrganizations >=` current owned org count.
|
||||
- Expiry: block CRM login; header days remaining; warn ≤3 days.
|
||||
- Vue + CRM CSS only for `/adm`.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Shared catalog + DTOs
|
||||
|
||||
- [ ] Add `ORG_MODULE_KEYS`, labels, plan presets, billing DTOs to `packages/shared/src/index.ts`
|
||||
- [ ] Extend org/login DTOs with `enabledModules` + `subscription` summary
|
||||
|
||||
## Task 2: Prisma
|
||||
|
||||
- [ ] `BillingAccount` model; `Organization.enabledModules String[]`
|
||||
- [ ] Migration SQL + data backfill (trial 15d, full modules)
|
||||
|
||||
## Task 3: Billing service + auth/org enforcement
|
||||
|
||||
- [ ] `BillingService` resolve/require active for org; apply plan; ensure account
|
||||
- [ ] Hook login / switch org / create org
|
||||
- [ ] Module require helper for key controllers (or lightweight guard)
|
||||
|
||||
## Task 4: Platform API + /adm UI
|
||||
|
||||
- [ ] Endpoints: get/apply billing, patch org modules
|
||||
- [ ] Adm users: billing card; adm orgs: module checklist; light shell polish
|
||||
|
||||
## Task 5: Web CRM
|
||||
|
||||
- [ ] Filter nav hubs by modules
|
||||
- [ ] Header subscription chip + warn
|
||||
- [ ] Router guard for disabled modules
|
||||
@@ -0,0 +1,202 @@
|
||||
# Design: BillingAccount + per-org modules + /adm polish
|
||||
|
||||
**Date:** 2026-09-20
|
||||
**Status:** Approved for planning
|
||||
**Scope:** Superadmin (`/adm`) subscription control, per-organization module entitlements, CRM enforcement, and visual polish of the platform admin UI.
|
||||
|
||||
## Goals
|
||||
|
||||
1. **Subscription on account owner** via a dedicated `BillingAccount` (not raw fields on `Organization`).
|
||||
2. **Modules per environment** — every CRM menu surface can be enabled/disabled per org from `/adm`.
|
||||
3. **Manual plan activation now**; structure ready for a future landing-page payment gateway (no gateway in this phase).
|
||||
4. **Expiry UX:** show remaining days in the CRM app header; warn from 3 days before; after expiry **block login** with a clear “اشتراک منقضی شده” message.
|
||||
5. **Migrate existing accounts:** create a `BillingAccount` with plan `trial` and **15 days from migration time** so current customers keep working until extended.
|
||||
6. **Polish `/adm` UI** to feel more app-like (same Vue + CRM CSS tokens; no separate Ant Design/Tailwind app).
|
||||
|
||||
## Non-goals (later)
|
||||
|
||||
- Online payment gateway / landing checkout
|
||||
- Impersonate user login
|
||||
- Complex multi-tier platform-admin roles
|
||||
- Automatic invoice generation for Mentekt SaaS itself
|
||||
|
||||
## Decisions (locked)
|
||||
|
||||
| Topic | Choice |
|
||||
|---|---|
|
||||
| Account vs org | Both: subscription on owner (`BillingAccount`); modules on each `Organization` |
|
||||
| Toggleable modules | Entire menu surface (not only add-ons) |
|
||||
| Payment | Manual in `/adm` now; `planCode` + optional payment ref reserved for gateway |
|
||||
| On expiry | Block CRM login; header shows remaining days; warn ≤3 days |
|
||||
| Existing orgs/users | Backfill trial **15 days** from migrate/seed time |
|
||||
| Data model style | Dedicated `BillingAccount` entity (approach 2) |
|
||||
|
||||
---
|
||||
|
||||
## Data model
|
||||
|
||||
### `BillingAccount`
|
||||
|
||||
One billing account per **owner user** (the SaaS customer).
|
||||
|
||||
| Field | Type | Notes |
|
||||
|---|---|---|
|
||||
| `id` | cuid | PK |
|
||||
| `ownerUserId` | string unique | FK → `User` — the account holder |
|
||||
| `planCode` | string | `trial` \| `monthly` \| `quarterly` \| `semiannual` \| `yearly` \| `custom` |
|
||||
| `status` | string | `active` \| `expired` \| `suspended` |
|
||||
| `startsAt` | DateTime | |
|
||||
| `expiresAt` | DateTime | |
|
||||
| `maxOrganizations` | int | e.g. trial demo = 1 |
|
||||
| `externalPaymentRef` | string? | Reserved for future gateway / landing |
|
||||
| `notes` | string? | Superadmin internal note |
|
||||
| `createdAt` / `updatedAt` | DateTime | |
|
||||
|
||||
Indexes: `ownerUserId` unique; `expiresAt`; `status`.
|
||||
|
||||
**Ownership rule:** The billing owner is the user who first registered / is treated as account holder. Membership in other orgs does not create extra billing accounts. Creating a new org as owner still counts against `maxOrganizations` of that user’s `BillingAccount`.
|
||||
|
||||
### `Organization.enabledModules`
|
||||
|
||||
- `enabledModules String[]` on `Organization` (Prisma).
|
||||
- Canonical keys live in `@mento/shared` (see Module catalog).
|
||||
- Empty array after migration for existing orgs means **all modules enabled** (backward compatible), OR we backfill the full catalog — prefer **backfill full catalog** so “empty” can later mean “nothing enabled” if needed.
|
||||
**Locked choice:** migration sets `enabledModules` to the **full default catalog** for existing orgs. New orgs get a default catalog from the plan template (trial = core set configurable in code; superadmin can change immediately).
|
||||
|
||||
### Plan presets (manual buttons in `/adm`)
|
||||
|
||||
| planCode | Default duration | Default maxOrgs |
|
||||
|---|---|---|
|
||||
| `trial` | 15 days | 1 |
|
||||
| `monthly` | 30 days | configurable (default 3) |
|
||||
| `quarterly` | 90 days | configurable (default 5) |
|
||||
| `semiannual` | 180 days | configurable (default 10) |
|
||||
| `yearly` | 365 days | configurable (default 20) |
|
||||
| `custom` | superadmin picks `expiresAt` + `maxOrganizations` | as set |
|
||||
|
||||
Extending an active plan from `/adm` sets `startsAt` (if missing), `expiresAt` = now + duration (or custom date), `status = active`, updates `planCode`.
|
||||
|
||||
### Backfill migration
|
||||
|
||||
1. For every `User` who has at least one `Membership` with `role = owner` (or is the sole owner of an org), ensure one `BillingAccount`:
|
||||
- Prefer: one account per distinct owner user who owns ≥1 org.
|
||||
- `planCode = trial`, `status = active`, `startsAt = now`, `expiresAt = now + 15 days`, `maxOrganizations = max(1, current org count they own)` so nobody is suddenly blocked for having multiple orgs already.
|
||||
2. Set `Organization.enabledModules` to full catalog for all existing orgs.
|
||||
|
||||
---
|
||||
|
||||
## Module catalog
|
||||
|
||||
Keys align with nav hubs/cards (and API surfaces). Shared constant e.g. `ORG_MODULE_KEYS` / labels in `@mento/shared`.
|
||||
|
||||
Suggested keys (final list in implementation may split cards 1:1 with nav):
|
||||
|
||||
- `customers` (people + companies)
|
||||
- `pipeline` (sales pipeline / deals)
|
||||
- `products`
|
||||
- `invoices`
|
||||
- `quotes`
|
||||
- `commissions`
|
||||
- `sales_forecast`
|
||||
- `activities`
|
||||
- `tickets`
|
||||
- `workflow_automations`
|
||||
- `message_automations`
|
||||
- `lead_forms`
|
||||
- `project_boards`
|
||||
- `inventory`
|
||||
- `cheques`
|
||||
- `attachments`
|
||||
- `loyalty` (if present in nav/settings)
|
||||
- `reports` (if in nav)
|
||||
- `notes` / smart notes if separately gated
|
||||
- `tahesab`
|
||||
- `custom_fields`
|
||||
- `currencies`
|
||||
- `team_settings` (keep always-on for owners? **Locked:** still toggleable, but warn in UI that disabling team settings locks self-service; login/org switcher remain available)
|
||||
|
||||
Settings hub items are individually toggleable. Core shell (home, profile, logout, org switcher) stays available when subscription is active.
|
||||
|
||||
---
|
||||
|
||||
## Enforcement
|
||||
|
||||
### Login / session
|
||||
|
||||
On CRM password login and org switch / token refresh:
|
||||
|
||||
1. Resolve `BillingAccount` for the user (by `ownerUserId`).
|
||||
- If user is **not** a billing owner (invited member only): use the **org owner’s** billing account for the active organization (subscription is per owner account that owns the env).
|
||||
- **Locked rule:** Entitlement for entering an org is the billing account of that org’s **active owner membership** (any active owner). If multiple owners, any one’s active billing is enough; prefer the earliest owner membership’s user.
|
||||
2. If `status !== active` OR `expiresAt < now` → reject with message اشتراک منقضی / معلق؛ mark status `expired` lazily when detected.
|
||||
3. Members of an expired owner cannot log into that org either.
|
||||
|
||||
### Create organization
|
||||
|
||||
- Only if caller has `BillingAccount` with `status = active` and `expiresAt >= now`.
|
||||
- Count orgs where user has `role = owner` membership; must be `< maxOrganizations`.
|
||||
|
||||
### Modules
|
||||
|
||||
- **Web:** filter `NAV_HUBS` cards/shortcuts and router guards by `organization.enabledModules` (loaded with org/session payload).
|
||||
- **API:** guard controllers/services for module-gated routes; return 403 with clear Persian message if module disabled.
|
||||
- Role permissions (`RolePermissionKey`) remain orthogonal: module must be on **and** role must allow.
|
||||
|
||||
### Remaining days UI
|
||||
|
||||
- Include `subscription: { planCode, status, expiresAt, daysRemaining, warn }` in login/me/org bootstrap DTO.
|
||||
- App header chip: «N روز باقیمانده».
|
||||
- If `daysRemaining <= 3` and `> 0`: warning style banner/chip.
|
||||
- If expired: user never reaches shell (login blocked).
|
||||
|
||||
---
|
||||
|
||||
## Platform admin (`/adm`) API
|
||||
|
||||
Authenticated with existing platform-admin JWT.
|
||||
|
||||
- `GET/PATCH` billing for a user: plan, dates, maxOrgs, status, notes.
|
||||
- Shortcuts: `POST .../billing/apply-plan` with `{ planCode, maxOrganizations?, expiresAt? }`.
|
||||
- `PATCH /platform/organizations/:id/modules` with `{ enabledModules: string[] }`.
|
||||
- List users/orgs already exists; extend DTOs with billing summary + module flags.
|
||||
|
||||
---
|
||||
|
||||
## Platform admin UI polish
|
||||
|
||||
Keep Vue 3 + existing CSS variables (`--accent`, `--line`, cards). Improvements:
|
||||
|
||||
- Denserv app-like shell: clearer hierarchy, sticky subheaders, soft gradients consistent with CRM auth pages.
|
||||
- User detail: billing card with plan chips + date picker (Jalali) + max orgs.
|
||||
- Org detail: module checklist grouped by hub (مشتریان / فروش / …) with select-all per group.
|
||||
- Dashboard KPIs: optional counts of expiring ≤3 days / expired (nice-to-have in same phase if cheap).
|
||||
|
||||
No Ant Design / Tailwind.
|
||||
|
||||
---
|
||||
|
||||
## Future gateway hook
|
||||
|
||||
Landing page later will:
|
||||
|
||||
1. Create/find `BillingAccount` by owner.
|
||||
2. After payment success, set `planCode`, `expiresAt`, `externalPaymentRef`, `status = active`.
|
||||
|
||||
No payment code in this phase; do not invent webhook handlers yet.
|
||||
|
||||
---
|
||||
|
||||
## Risks & edge cases
|
||||
|
||||
- Users with multiple owned orgs today: backfill `maxOrganizations` ≥ current owned count.
|
||||
- Invited users: gated by org owner’s subscription.
|
||||
- Disabling a module mid-use: existing data kept; API/UI blocked until re-enabled.
|
||||
- Superadmin `/adm` login unaffected by BillingAccount.
|
||||
|
||||
## Testing (manual)
|
||||
|
||||
1. Fresh seed/migrate → existing owner has 15-day trial; can log in; header shows days.
|
||||
2. Set expiresAt to yesterday → login fails with expiry message.
|
||||
3. Disable `message_automations` on an org → menu gone + API 403.
|
||||
4. Trial maxOrgs=1 with one owned org → create second org rejected.
|
||||
5. Apply `monthly` from `/adm` → expiresAt ~+30d, status active.
|
||||
@@ -37,6 +37,223 @@ export interface AuthUserDto {
|
||||
organizationId: string;
|
||||
organizationName?: string;
|
||||
hasAvatar?: boolean;
|
||||
/** مالک محیط فعلی — اشتراک متعلق به مالک است نه عضو زیرمجموعه */
|
||||
isOrgOwner?: boolean;
|
||||
enabledModules?: OrgModuleKey[];
|
||||
/** خلاصه اشتراک مالک محیط (برای اعضا فقط جهت نمایش/گیت ورود) */
|
||||
subscription?: SubscriptionSummaryDto | null;
|
||||
}
|
||||
|
||||
export type BillingPlanCode =
|
||||
| "trial"
|
||||
| "monthly"
|
||||
| "quarterly"
|
||||
| "semiannual"
|
||||
| "yearly"
|
||||
| "custom";
|
||||
|
||||
export type BillingAccountStatus = "active" | "expired" | "suspended";
|
||||
|
||||
export const BILLING_PLAN_CODES: BillingPlanCode[] = [
|
||||
"trial",
|
||||
"monthly",
|
||||
"quarterly",
|
||||
"semiannual",
|
||||
"yearly",
|
||||
"custom",
|
||||
];
|
||||
|
||||
export const BILLING_PLAN_LABELS: Record<BillingPlanCode, string> = {
|
||||
trial: "دمو ۱۵ روزه",
|
||||
monthly: "ماهانه",
|
||||
quarterly: "سهماهه",
|
||||
semiannual: "ششماهه",
|
||||
yearly: "یکساله",
|
||||
custom: "سفارشی",
|
||||
};
|
||||
|
||||
/** مدت پیشفرض پلنها (روز) — custom ندارد */
|
||||
export const BILLING_PLAN_DAYS: Record<Exclude<BillingPlanCode, "custom">, number> = {
|
||||
trial: 15,
|
||||
monthly: 30,
|
||||
quarterly: 90,
|
||||
semiannual: 180,
|
||||
yearly: 365,
|
||||
};
|
||||
|
||||
export const BILLING_PLAN_DEFAULT_MAX_ORGS: Record<
|
||||
Exclude<BillingPlanCode, "custom">,
|
||||
number
|
||||
> = {
|
||||
trial: 1,
|
||||
monthly: 3,
|
||||
quarterly: 5,
|
||||
semiannual: 10,
|
||||
yearly: 20,
|
||||
};
|
||||
|
||||
export type OrgModuleKey =
|
||||
| "customers"
|
||||
| "pipeline"
|
||||
| "products"
|
||||
| "invoices"
|
||||
| "quotes"
|
||||
| "commissions"
|
||||
| "sales_forecast"
|
||||
| "activities"
|
||||
| "tickets"
|
||||
| "workflow_automations"
|
||||
| "message_automations"
|
||||
| "lead_forms"
|
||||
| "project_boards"
|
||||
| "inventory"
|
||||
| "cheques"
|
||||
| "attachments"
|
||||
| "loyalty"
|
||||
| "reports"
|
||||
| "notes"
|
||||
| "tahesab"
|
||||
| "custom_fields"
|
||||
| "currencies"
|
||||
| "team_settings"
|
||||
| "faq";
|
||||
|
||||
export const ORG_MODULE_KEYS: OrgModuleKey[] = [
|
||||
"customers",
|
||||
"pipeline",
|
||||
"products",
|
||||
"invoices",
|
||||
"quotes",
|
||||
"commissions",
|
||||
"sales_forecast",
|
||||
"activities",
|
||||
"tickets",
|
||||
"workflow_automations",
|
||||
"message_automations",
|
||||
"lead_forms",
|
||||
"project_boards",
|
||||
"inventory",
|
||||
"cheques",
|
||||
"attachments",
|
||||
"loyalty",
|
||||
"reports",
|
||||
"notes",
|
||||
"tahesab",
|
||||
"custom_fields",
|
||||
"currencies",
|
||||
"team_settings",
|
||||
"faq",
|
||||
];
|
||||
|
||||
export const ORG_MODULE_LABELS: Record<OrgModuleKey, string> = {
|
||||
customers: "مشتریان",
|
||||
pipeline: "کاریز فروش",
|
||||
products: "محصولات",
|
||||
invoices: "فاکتورها",
|
||||
quotes: "پیشفاکتورها",
|
||||
commissions: "پورسانت",
|
||||
sales_forecast: "هدف و پیشبینی",
|
||||
activities: "فعالیتها",
|
||||
tickets: "تیکتها",
|
||||
workflow_automations: "اتوماسیون گردش کار",
|
||||
message_automations: "اتوماسیون پیامک",
|
||||
lead_forms: "فرمساز سرنخ",
|
||||
project_boards: "کاریز پروژه",
|
||||
inventory: "انبار",
|
||||
cheques: "چکها",
|
||||
attachments: "پیوستها",
|
||||
loyalty: "باشگاه مشتریان",
|
||||
reports: "گزارشها",
|
||||
notes: "یادداشتها",
|
||||
tahesab: "تهحساب",
|
||||
custom_fields: "فیلدهای سفارشی",
|
||||
currencies: "ارزها",
|
||||
team_settings: "تیم و تنظیمات سازمان",
|
||||
faq: "FAQ",
|
||||
};
|
||||
|
||||
export const ORG_MODULE_GROUPS: Array<{
|
||||
title: string;
|
||||
keys: OrgModuleKey[];
|
||||
}> = [
|
||||
{ title: "مشتریان", keys: ["customers"] },
|
||||
{
|
||||
title: "فروش",
|
||||
keys: [
|
||||
"pipeline",
|
||||
"products",
|
||||
"invoices",
|
||||
"quotes",
|
||||
"commissions",
|
||||
"sales_forecast",
|
||||
],
|
||||
},
|
||||
{ title: "فعالیتها", keys: ["activities", "notes"] },
|
||||
{ title: "پشتیبانی", keys: ["tickets", "faq"] },
|
||||
{
|
||||
title: "اتوماسیون",
|
||||
keys: ["workflow_automations", "message_automations"],
|
||||
},
|
||||
{
|
||||
title: "ابزارها",
|
||||
keys: [
|
||||
"lead_forms",
|
||||
"project_boards",
|
||||
"inventory",
|
||||
"cheques",
|
||||
"attachments",
|
||||
"loyalty",
|
||||
"reports",
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "تنظیمات",
|
||||
keys: ["team_settings", "custom_fields", "currencies", "tahesab"],
|
||||
},
|
||||
];
|
||||
|
||||
export function isOrgModuleKey(value: string): value is OrgModuleKey {
|
||||
return (ORG_MODULE_KEYS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
export function defaultEnabledModules(): OrgModuleKey[] {
|
||||
return [...ORG_MODULE_KEYS];
|
||||
}
|
||||
|
||||
export interface SubscriptionSummaryDto {
|
||||
planCode: BillingPlanCode;
|
||||
status: BillingAccountStatus;
|
||||
startsAt: string;
|
||||
expiresAt: string;
|
||||
maxOrganizations: number;
|
||||
daysRemaining: number;
|
||||
warn: boolean;
|
||||
}
|
||||
|
||||
export interface BillingAccountDto {
|
||||
id: string;
|
||||
ownerUserId: string;
|
||||
planCode: BillingPlanCode;
|
||||
status: BillingAccountStatus;
|
||||
startsAt: string;
|
||||
expiresAt: string;
|
||||
maxOrganizations: number;
|
||||
externalPaymentRef?: string | null;
|
||||
notes?: string | null;
|
||||
daysRemaining: number;
|
||||
warn: boolean;
|
||||
}
|
||||
|
||||
export interface ApplyBillingPlanRequest {
|
||||
planCode: BillingPlanCode;
|
||||
maxOrganizations?: number;
|
||||
expiresAt?: string;
|
||||
notes?: string | null;
|
||||
status?: BillingAccountStatus;
|
||||
}
|
||||
|
||||
export interface UpdateOrgModulesRequest {
|
||||
enabledModules: OrgModuleKey[];
|
||||
}
|
||||
|
||||
export interface OrgUserDto {
|
||||
@@ -245,6 +462,7 @@ export interface OrganizationDto {
|
||||
baseCurrency: string;
|
||||
enabledCurrencies: string[];
|
||||
exchangeRates: ExchangeRateDto[];
|
||||
enabledModules: OrgModuleKey[];
|
||||
}
|
||||
|
||||
export interface UpdateOrganizationRequest {
|
||||
@@ -2552,6 +2770,8 @@ export interface PlatformStatsDto {
|
||||
userCount: number;
|
||||
activeUserCount: number;
|
||||
membershipCount: number;
|
||||
expiringSoonCount?: number;
|
||||
expiredBillingCount?: number;
|
||||
}
|
||||
|
||||
export interface PlatformOrgMemberDto {
|
||||
@@ -2575,6 +2795,7 @@ export interface PlatformOrganizationDto {
|
||||
memberCount: number;
|
||||
personCount: number;
|
||||
dealCount: number;
|
||||
enabledModules?: OrgModuleKey[];
|
||||
members?: PlatformOrgMemberDto[];
|
||||
}
|
||||
|
||||
@@ -2596,6 +2817,9 @@ export interface PlatformUserDto {
|
||||
lastLoginAt?: string | null;
|
||||
createdAt: string;
|
||||
memberships: PlatformUserMembershipDto[];
|
||||
/** فقط اگر حداقل یک عضویت مالک فعال دارد */
|
||||
isBillingOwner?: boolean;
|
||||
billing?: BillingAccountDto | null;
|
||||
}
|
||||
|
||||
export interface UpdatePlatformStatusRequest {
|
||||
|
||||
Reference in New Issue
Block a user