import { ForbiddenException } from '@nestjs/common'; import { ASSIGN_SECTION_PERMISSION, type AssignSection, } from '@mento/shared'; import type { PrismaService } from '../prisma/prisma.service'; import { elevated } from './record-scope'; const ASSIGN_NOUN: Record = { customers: 'مشتری', leads: 'لید', sales: 'معامله', activities: 'فعالیت', routines: 'کار روتین', projects: 'کارت پروژه', tickets: 'تیکت', }; type AssignActor = { userId: string; role: string; organizationId: string }; export function assignOthersDeniedMessage(section: AssignSection): string { return `تخصیص ${ASSIGN_NOUN[section]} به دیگران برای نقش شما مجاز نیست. فقط می‌توانید برای خودتان ثبت کنید.`; } export async function actorCanAssignToOthers( prisma: PrismaService, actor: AssignActor, section: AssignSection, ): Promise { if (elevated(actor.role)) return true; const membership = await prisma.membership.findFirst({ where: { userId: actor.userId, organizationId: actor.organizationId, isActive: true, }, select: { orgRole: { select: { permissions: true } } }, }); const permissions = membership?.orgRole?.permissions; const key = ASSIGN_SECTION_PERMISSION[section]; return Array.isArray(permissions) && permissions.includes(key); } /** * بدون مجوز همان بخش، مجموعهٔ مسئولانِ غیر از خود کاربر نباید عوض شود. * ثبت تازه یعنی قبلی خالی است، پس فقط خود کاربر مجاز است. */ export async function assertAssigneeSet( prisma: PrismaService, actor: AssignActor, section: AssignSection, nextIds: Array, previousIds: Array = [], ): Promise { if (await actorCanAssignToOthers(prisma, actor, section)) return; const prev = new Set( previousIds.filter((id): id is string => Boolean(id) && id !== actor.userId), ); const next = nextIds.filter((id): id is string => Boolean(id) && id !== actor.userId); const changed = next.length !== prev.size || next.some((id) => !prev.has(id)); if (changed) throw new ForbiddenException(assignOthersDeniedMessage(section)); }