This commit is contained in:
2026-01-07 12:13:45 +03:30
parent 27ebf4a7b6
commit f2284c103d
235 changed files with 180468 additions and 1 deletions
@@ -0,0 +1,93 @@
import { Controller, Get, Post, Body, Param, Patch, Delete, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBody, ApiBearerAuth, ApiHeader } from '@nestjs/swagger';
import { RolesService } from '../providers/roles.service';
import { PermissionsService } from '../providers/permissions.service';
import { CreateRoleDto } from '../dto/create-role.dto';
import { UpdateRoleDto } from '../dto/update-role.dto';
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
import { SuperAdminAuthGuard } from 'src/modules/auth/guards/superAdminAuth.guard';
import { Permissions } from 'src/common/decorators/permissions.decorator';
import { RestId } from 'src/common/decorators';
import { AdminId } from 'src/common/decorators/admin-id.decorator';
import { Permission } from 'src/common/enums/permission.enum';
@ApiTags('roles')
@Controller()
export class RolesController {
constructor(
private readonly roleService: RolesService,
private readonly permissionService: PermissionsService,
) { }
@Get('admin/roles')
@UseGuards(AdminAuthGuard)
@Permissions(Permission.MANAGE_ROLES)
@ApiBearerAuth()
@ApiOperation({ summary: 'Get all through restaurant roles with pagination and filters' })
findAll(@RestId() restId: string) {
return this.roleService.findAllGeneralAndRestaurantRoles(restId);
}
@Get('admin/roles/permissions')
@UseGuards(AdminAuthGuard)
@Permissions(Permission.MANAGE_ROLES)
@ApiBearerAuth()
@ApiOperation({ summary: 'Get all permissions that the admin has' })
async findAllPermissions(@AdminId() adminId: string, @RestId() restId: string) {
const adminPermissionNames = await this.permissionService.getAdminFullPermissions(adminId, restId);
return adminPermissionNames;
}
@Post('admin/roles')
@UseGuards(AdminAuthGuard)
@Permissions(Permission.MANAGE_ROLES)
@ApiBearerAuth()
@ApiOperation({ summary: 'Create a new role' })
@ApiBody({ type: CreateRoleDto })
create(@Body() dto: CreateRoleDto, @RestId() restId: string) {
return this.roleService.createRestaurantRole(dto, restId);
}
@Get('admin/roles/:id')
@UseGuards(AdminAuthGuard)
@Permissions(Permission.MANAGE_ROLES)
@ApiBearerAuth()
@ApiOperation({ summary: 'Get a specific role by ID' })
findOne(@Param('id') id: string, @RestId() restId: string) {
return this.roleService.findOne(restId, id);
}
@Patch('admin/roles/:id')
@UseGuards(AdminAuthGuard)
@Permissions(Permission.MANAGE_ROLES)
@ApiBearerAuth()
@ApiOperation({ summary: 'Update a role' })
@ApiBody({ type: UpdateRoleDto })
update(@Param('id') id: string, @Body() dto: UpdateRoleDto, @RestId() restId: string) {
return this.roleService.update(restId, id, dto);
}
@Delete('admin/roles/:id')
@UseGuards(AdminAuthGuard)
@Permissions(Permission.MANAGE_ROLES)
@ApiBearerAuth()
@ApiOperation({ summary: 'Delete a role' })
remove(@Param('id') id: string, @RestId() restId: string) {
return this.roleService.remove(restId, id);
}
/** Super Admin Endpoints */
@UseGuards(SuperAdminAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: 'Get all system roles for super-admin' })
@Get('super-admin/system-roles')
@ApiOperation({ summary: 'Get all system roles for super-admin' })
findAllSystemRoles() {
return this.roleService.findAllSystemRoles();
}
}
+14
View File
@@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsArray, IsOptional } from 'class-validator';
export class CreateRoleDto {
@ApiProperty({ description: 'Role name' })
@IsNotEmpty()
@IsString()
name!: string;
@ApiProperty({ description: 'List of permission IDs', isArray: true, required: false })
@IsOptional()
@IsArray()
permissionIds?: string[];
}
+14
View File
@@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsOptional, IsString, IsArray } from 'class-validator';
export class UpdateRoleDto {
@ApiProperty({ description: 'Role name', required: false })
@IsOptional()
@IsString()
name?: string;
@ApiProperty({ description: 'List of permission IDs', isArray: true, required: false })
@IsOptional()
@IsArray()
permissionIds?: string[];
}
+17
View File
@@ -0,0 +1,17 @@
import { Entity, Property, Unique, ManyToMany, Collection } from '@mikro-orm/core';
import { BaseEntity } from '../../../common/entities/base.entity';
import { Role } from './role.entity';
@Entity({ tableName: 'permissions' })
export class Permission extends BaseEntity {
@Property()
@Unique()
name!: string;
@Property()
title!: string;
@ManyToMany({ entity: () => Role, mappedBy: 'permissions' })
roles = new Collection<Role>(this);
}
+25
View File
@@ -0,0 +1,25 @@
import { Collection, Entity, Index, ManyToMany, OneToMany, ManyToOne, Property } from '@mikro-orm/core';
import { BaseEntity } from '../../../common/entities/base.entity';
import { Permission } from './permission.entity';
import { Restaurant } from '../../restaurants/entities/restaurant.entity';
import { RolePermission } from './rolePermission.entity';
import { AdminRole } from 'src/modules/admin/entities/adminRole.entity';
@Entity({ tableName: 'roles' })
@Index({ properties: ['restaurant'] })
export class Role extends BaseEntity {
@Property()
name!: string;
@Property({ default: false })
isSystem: boolean = false;
@ManyToMany({ entity: () => Permission, pivotEntity: () => RolePermission, inversedBy: p => p.roles })
permissions = new Collection<Permission>(this);
@ManyToOne(() => Restaurant, { nullable: true })
restaurant?: Restaurant;
@OneToMany(() => AdminRole, adminRole => adminRole.role)
admins = new Collection<AdminRole>(this);
}
@@ -0,0 +1,16 @@
import { Entity, ManyToOne } from '@mikro-orm/core';
import { Role } from './role.entity';
import { Permission } from './permission.entity';
@Entity({ tableName: 'role_permissions' })
export class RolePermission {
// دو ManyToOne دقیقاً؛ هر کدام می‌تونن primary: true باشند برای composite PK
@ManyToOne(() => Role, { primary: true })
role!: Role;
@ManyToOne(() => Permission, { primary: true })
permission!: Permission;
// **نکته:** اینجا *فقط* همین دو خصوصیت کافی است —
// از تعریف جداگانه‌ی roleId / permissionId با @PrimaryKey خودداری کن مگر بخوای نام/نوع ستون را سفارشی کنی.
}
@@ -0,0 +1,105 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityManager, EntityRepository } from '@mikro-orm/core';
import { Permission } from '../entities/permission.entity';
import { CacheService } from 'src/modules/utils/cache.service';
import { AdminRepository } from 'src/modules/admin/repositories/admin.repository';
import { AdminRole } from 'src/modules/admin/entities/adminRole.entity';
@Injectable()
export class PermissionsService {
private readonly ADMIN_PERMISSIONS_KEY = 'admin-perms';
constructor(
@InjectRepository(Permission)
private readonly permissionRepository: EntityRepository<Permission>,
private readonly cacheService: CacheService,
private readonly adminRepository: AdminRepository,
private readonly em: EntityManager,
) { }
async findAll() {
const permissions = await this.permissionRepository.findAll();
return permissions;
}
/**
* Get admin permissions from cache or database
* @param adminId - The admin ID
* @param restId - The restaurant ID
* @returns Array of permission names (string[])
*/
async getAdminPermissions(adminId: string, restId: string): Promise<string[]> {
const cacheKey = `${this.ADMIN_PERMISSIONS_KEY}:${adminId}:${restId}`;
// Try to get from cache first
const cachedPermissions = await this.cacheService.get<string>(cacheKey);
if (cachedPermissions) {
try {
const parsed: unknown = JSON.parse(cachedPermissions);
// Ensure it's an array of strings
if (Array.isArray(parsed) && parsed.every((p): p is string => typeof p === 'string')) {
return parsed;
}
// If invalid format, continue to fetch from DB
} catch {
// If parsing fails, continue to fetch from DB
}
}
// If not in cache, fetch from database
const admin = await this.adminRepository.findOne(
{ id: adminId, roles: { restaurant: { id: restId } } },
{ populate: ['roles', 'roles.role', 'roles.role.permissions'] },
);
if (!admin || !admin.roles) {
return [];
}
// Ensure roles collection is loaded
await admin.roles.loadItems();
// Extract permission names as array of strings
const permissions = await Promise.all(
admin.roles
.getItems()
.filter(r => r.role) // Filter out any null/undefined roles
.map(async r => {
// Ensure permissions collection is initialized
if (!r.role.permissions.isInitialized()) {
await r.role.permissions.loadItems();
}
return r.role.permissions.getItems();
}),
);
return permissions.flat().map(p => p.name);
}
async getAdminFullPermissions(adminId: string, restId: string): Promise<Permission[]> {
const listOfPermissions = []
const adminRoles = await this.em.findOne(AdminRole, {
admin: {
id: adminId,
},
restaurant: {
id: restId,
},
}, { populate: ['role', 'role.permissions'] });
if (adminRoles) {
listOfPermissions.push(...adminRoles.role.permissions.getItems());
}
return listOfPermissions.map(permission => permission);
}
/**
* Invalidate admin permissions cache
* @param adminId - The admin ID
* @param restId - The restaurant ID
*/
async invalidateAdminPermissionsCache(adminId: string, restId: string): Promise<void> {
const cacheKey = `${this.ADMIN_PERMISSIONS_KEY}:${adminId}:${restId}`;
await this.cacheService.del(cacheKey);
}
}
@@ -0,0 +1,138 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityRepository, FilterQuery } from '@mikro-orm/core';
import { Role } from '../entities/role.entity';
import { Permission } from '../entities/permission.entity';
import { Restaurant } from '../../restaurants/entities/restaurant.entity';
import { EntityManager } from '@mikro-orm/postgresql';
import { CreateRoleDto } from '../dto/create-role.dto';
import { UpdateRoleDto } from '../dto/update-role.dto';
import { RolePermission } from '../entities/rolePermission.entity';
@Injectable()
export class RolesService {
constructor(
@InjectRepository(Role)
private readonly roleRepository: EntityRepository<Role>,
@InjectRepository(Permission)
private readonly permissionRepository: EntityRepository<Permission>,
private readonly em: EntityManager,
) { }
async createRestaurantRole(dto: CreateRoleDto, restId: string) {
const { name, permissionIds } = dto;
// Check if role already exists
const existing = await this.roleRepository.findOne({ name, restaurant: restId ? { id: restId } : null });
if (existing) {
throw new BadRequestException('Role with this name already exists for the restaurant');
}
let restaurant: Restaurant | null = null;
if (restId) {
restaurant = await this.em.findOne(Restaurant, { id: restId });
if (!restaurant) {
throw new NotFoundException('Restaurant not found');
}
}
const role = this.roleRepository.create({
name,
restaurant,
isSystem: false,
});
// Add permissions if provided
if (permissionIds && permissionIds.length > 0) {
const permissions = await this.permissionRepository.find({ id: { $in: permissionIds } });
if (permissions.length !== permissionIds.length) {
throw new BadRequestException('One or more permissions not found');
}
permissions.forEach(p => role.permissions.add(p));
}
await this.em.persistAndFlush(role);
return role;
}
async findAllGeneralAndRestaurantRoles(restId: string) {
const where: FilterQuery<Role> = { $or: [{ restaurant: restId }, { restaurant: null }], isSystem: false };
const roles = await this.roleRepository.find(where, {
orderBy: { createdAt: 'desc' },
populate: ['permissions', 'restaurant'],
});
return roles;
}
async findOne(restId: string, id: string) {
const role = await this.roleRepository.findOne(
{ id, restaurant: { id: restId } },
{ populate: ['permissions', 'restaurant'] },
);
if (!role) {
throw new NotFoundException('Role not found');
}
return role;
}
async update(restId: string, id: string, dto: UpdateRoleDto) {
const role = await this.roleRepository.findOne(
{ id, restaurant: { id: restId } },
{ populate: ['permissions', 'restaurant'] },
);
if (!role) {
throw new NotFoundException('Role not found');
}
if (dto.name) {
role.name = dto.name;
}
if (dto.permissionIds && dto.permissionIds.length >= 0) {
// Clear existing permissions and add new ones
role.permissions.removeAll();
const permissions = await this.permissionRepository.find({ id: { $in: dto.permissionIds } });
if (permissions.length !== dto.permissionIds.length) {
throw new BadRequestException('One or more permissions not found');
}
permissions.forEach(p => role.permissions.add(p));
}
await this.em.persistAndFlush(role);
return role;
}
async findAllSystemRoles() {
const roles = await this.roleRepository.find(
{ isSystem: true },
{
orderBy: { createdAt: 'desc' },
populate: ['permissions', 'restaurant'],
},
);
return roles;
}
async remove(restId: string, id: string) {
const role = await this.roleRepository.findOne(
{ id, restaurant: { id: restId } },
{ populate: ['permissions', 'restaurant'] },
);
if (!role) {
throw new NotFoundException('Role not found');
}
if (!role.admins.isEmpty()) {
throw new BadRequestException('Role has admins');
}
// Hard delete pivot table entries (role_permissions) before soft deleting the role
await this.em.nativeDelete(RolePermission, { role: { id: role.id } });
// Soft delete the role
role.deletedAt = new Date();
return this.em.persistAndFlush(role);
}
}
+20
View File
@@ -0,0 +1,20 @@
import { Global, Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { RolesService } from './providers/roles.service';
import { RolesController } from './controllers/roles.controller';
import { PermissionsService } from './providers/permissions.service';
import { Role } from './entities/role.entity';
import { Permission } from './entities/permission.entity';
import { RolePermission } from './entities/rolePermission.entity';
import { JwtModule } from '@nestjs/jwt';
import { UtilsModule } from '../utils/utils.module';
import { AdminModule } from '../admin/admin.module';
@Global()
@Module({
imports: [MikroOrmModule.forFeature([Role, Permission, RolePermission]), JwtModule, UtilsModule, AdminModule],
controllers: [RolesController],
providers: [RolesService, PermissionsService],
exports: [RolesService, PermissionsService],
})
export class RolesModule {}