Refactor Admin module by removing role and permission controllers, services, and DTOs; update imports to utilize Roles module for role and permission entities; adjust AdminService and AdminModule accordingly.

This commit is contained in:
2025-11-18 15:43:24 +03:30
parent 0407d4c05a
commit 9abab789fc
18 changed files with 116 additions and 53 deletions
+24
View File
@@ -0,0 +1,24 @@
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: 'Role title' })
@IsNotEmpty()
@IsString()
title!: string;
@ApiProperty({ description: 'Restaurant id (optional)', required: false })
@IsOptional()
@IsString()
restId?: string;
@ApiProperty({ description: 'List of permission IDs', isArray: true, required: false })
@IsOptional()
@IsArray()
permissionIds?: string[];
}
+29
View File
@@ -0,0 +1,29 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsOptional, IsString, IsNumber, Min } from 'class-validator';
import { Type } from 'class-transformer';
export class FindRolesDto {
@ApiProperty({ description: 'Search by role name', required: false })
@IsOptional()
@IsString()
name?: string;
@ApiProperty({ description: 'Restaurant id filter', required: false })
@IsOptional()
@IsString()
restId?: string;
@ApiProperty({ description: 'Page number', required: false, default: 1 })
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(1)
page?: number;
@ApiProperty({ description: 'Items per page', required: false, default: 20 })
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(1)
limit?: number;
}
+19
View File
@@ -0,0 +1,19 @@
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: 'Role title', required: false })
@IsOptional()
@IsString()
title?: string;
@ApiProperty({ description: 'List of permission IDs', isArray: true, required: false })
@IsOptional()
@IsArray()
permissionIds?: string[];
}
+16
View File
@@ -0,0 +1,16 @@
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: r => r.permissions })
roles = new Collection<Role>(this);
}
+21
View File
@@ -0,0 +1,21 @@
// role.entity.ts
import { Collection, Entity, 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';
@Entity({ tableName: 'roles' })
export class Role extends BaseEntity {
@Property()
name!: string;
@Property()
title!: string;
@ManyToMany({ entity: () => Permission, pivotEntity: () => RolePermission, inversedBy: p => p.roles })
permissions = new Collection<Permission>(this);
@ManyToOne(() => Restaurant, { nullable: true })
restaurant?: Restaurant;
}
@@ -0,0 +1,17 @@
// role-permission.entity.ts (pivot)
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,17 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityRepository } from '@mikro-orm/core';
import { Permission } from '../entities/permission.entity';
@Injectable()
export class PermissionsService {
constructor(
@InjectRepository(Permission)
private readonly permissionRepository: EntityRepository<Permission>,
) {}
async findAll() {
const permissions = await this.permissionRepository.findAll();
return permissions;
}
}
@@ -0,0 +1,134 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityRepository } 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 { FindRolesDto } from '../dto/find-roles.dto';
@Injectable()
export class RolesService {
constructor(
@InjectRepository(Role)
private readonly roleRepository: EntityRepository<Role>,
@InjectRepository(Permission)
private readonly permissionRepository: EntityRepository<Permission>,
private readonly em: EntityManager,
) {}
async create(dto: CreateRoleDto) {
const { name, title, restId, 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,
title,
restaurant,
});
// 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 findAll(dto: FindRolesDto) {
const { name, restId, page = 1, limit = 20 } = dto;
const offset = (page - 1) * limit;
// Build query dynamically
const query: Record<string, unknown> = restId ? { restaurant: { id: restId } } : {};
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const [roles, count] = await this.roleRepository.findAndCount(query as any, {
offset,
limit,
populate: ['permissions', 'restaurant'],
});
// Filter by name or title in memory if provided
let filtered = roles;
if (name) {
filtered = roles.filter(
r => r.name.toLowerCase().includes(name.toLowerCase()) || r.title.toLowerCase().includes(name.toLowerCase()),
);
}
return {
data: filtered,
total: count,
page,
limit,
totalPages: Math.ceil(count / limit),
};
}
async findOne(id: string) {
const role = await this.roleRepository.findOne({ id }, { populate: ['permissions', 'restaurant'] });
if (!role) {
throw new NotFoundException('Role not found');
}
return role;
}
async update(id: string, dto: UpdateRoleDto) {
const role = await this.roleRepository.findOne({ id });
if (!role) {
throw new NotFoundException('Role not found');
}
if (dto.name) {
role.name = dto.name;
}
if (dto.title) {
role.title = dto.title;
}
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 remove(id: string) {
const role = await this.roleRepository.findOne({ id });
if (!role) {
throw new NotFoundException('Role not found');
}
await this.roleRepository.nativeUpdate({ id }, { deletedAt: new Date() });
return { message: 'Role deleted successfully' };
}
}
+68
View File
@@ -0,0 +1,68 @@
import { Controller, Get, Post, Body, Param, Patch, Delete, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBody, ApiResponse, ApiBearerAuth } 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 { FindRolesDto } from './dto/find-roles.dto';
import { AdminAuthGuard } from '../auth/guards/adminAuth.guard';
import { Permissions } from '../auth/decorators/permissions.decorator';
@UseGuards(AdminAuthGuard)
@ApiBearerAuth()
@ApiTags('admin/roles')
@Controller('admin/roles')
export class RolesController {
constructor(
private readonly roleService: RolesService,
private readonly permissionService: PermissionsService,
) {}
@Get()
@ApiOperation({ summary: 'Get all roles with pagination and filters' })
@ApiResponse({ status: 200, description: 'Roles retrieved successfully' })
async findAll(@Query() dto: FindRolesDto) {
return this.roleService.findAll(dto);
}
@Get('permissions')
@ApiOperation({ summary: 'Get all permissions' })
@ApiResponse({ status: 200, description: 'Permissions retrieved successfully' })
async findAllPermissions() {
return this.permissionService.findAll();
}
@Permissions('create-role')
@Post()
@ApiOperation({ summary: 'Create a new role' })
@ApiBody({ type: CreateRoleDto })
@ApiResponse({ status: 201, description: 'Role created successfully' })
async create(@Body() dto: CreateRoleDto) {
return this.roleService.create(dto);
}
@Get(':id')
@ApiOperation({ summary: 'Get a specific role by ID' })
@ApiResponse({ status: 200, description: 'Role retrieved successfully' })
@ApiResponse({ status: 404, description: 'Role not found' })
async findOne(@Param('id') id: string) {
return this.roleService.findOne(id);
}
@Patch(':id')
@ApiOperation({ summary: 'Update a role' })
@ApiBody({ type: UpdateRoleDto })
@ApiResponse({ status: 200, description: 'Role updated successfully' })
@ApiResponse({ status: 404, description: 'Role not found' })
async update(@Param('id') id: string, @Body() dto: UpdateRoleDto) {
return this.roleService.update(id, dto);
}
@Delete(':id')
@ApiOperation({ summary: 'Delete a role' })
@ApiResponse({ status: 200, description: 'Role deleted successfully' })
@ApiResponse({ status: 404, description: 'Role not found' })
async remove(@Param('id') id: string) {
return this.roleService.remove(id);
}
}
+20
View File
@@ -0,0 +1,20 @@
import { Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { RolesService } from './providers/roles.service';
import { RolesController } from './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';
@Module({
imports: [
MikroOrmModule.forFeature([Role, Permission, RolePermission]),
JwtModule,
],
controllers: [RolesController],
providers: [RolesService, PermissionsService],
exports: [RolesService, PermissionsService],
})
export class RolesModule {}