This commit is contained in:
2025-11-24 19:48:29 +03:30
parent 414f7e179f
commit cfc7e1ffb9
4 changed files with 16 additions and 62 deletions
@@ -1,10 +1,9 @@
import { Controller, Get, Post, Body, Param, Patch, Delete, Query, UseGuards } from '@nestjs/common'; import { Controller, Get, Post, Body, Param, Patch, Delete, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBody, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'; import { ApiTags, ApiOperation, ApiBody, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { RolesService } from '../providers/roles.service'; import { RolesService } from '../providers/roles.service';
import { PermissionsService } from '../providers/permissions.service'; import { PermissionsService } from '../providers/permissions.service';
import { CreateRoleDto } from '../dto/create-role.dto'; import { CreateRoleDto } from '../dto/create-role.dto';
import { UpdateRoleDto } from '../dto/update-role.dto'; import { UpdateRoleDto } from '../dto/update-role.dto';
import { FindRolesDto } from '../dto/find-roles.dto';
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard'; import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
import { Permissions } from 'src/modules/auth/decorators/permissions.decorator'; import { Permissions } from 'src/modules/auth/decorators/permissions.decorator';
import { RestId } from 'src/common/decorators'; import { RestId } from 'src/common/decorators';
@@ -21,17 +20,17 @@ export class RolesController {
) {} ) {}
@Get() @Get()
@ApiOperation({ summary: 'Get all roles with pagination and filters' }) @ApiOperation({ summary: 'Get all through restaurant roles with pagination and filters' })
@ApiResponse({ status: 200, description: 'Roles retrieved successfully' }) @ApiResponse({ status: 200, description: 'Restaurant roles retrieved successfully' })
findAll(@Query() dto: FindRolesDto, @RestId() restId: string) { findAll(@RestId() restId: string) {
return this.roleService.findAll(restId, dto); return this.roleService.findAllGeneralAndRestaurantRoles(restId);
} }
@Get('permissions') @Get('permissions')
@ApiOperation({ summary: 'Get all permissions that the admin has' }) @ApiOperation({ summary: 'Get all permissions that the admin has' })
@ApiResponse({ status: 200, description: 'Permissions retrieved successfully' }) @ApiResponse({ status: 200, description: 'Permissions retrieved successfully' })
async findAllPermissions(@AdminId() adminId: string, @RestId() restId: string) { async findAllPermissions(@AdminId() adminId: string, @RestId() restId: string) {
const adminPermissionNames = await this.permissionService.getFullAdminPermissions(adminId, restId); const adminPermissionNames = await this.permissionService.getAdminFullPermissions(adminId, restId);
return adminPermissionNames; return adminPermissionNames;
} }
@@ -42,7 +41,7 @@ export class RolesController {
@ApiBody({ type: CreateRoleDto }) @ApiBody({ type: CreateRoleDto })
@ApiResponse({ status: 201, description: 'Role created successfully' }) @ApiResponse({ status: 201, description: 'Role created successfully' })
create(@Body() dto: CreateRoleDto, @RestId() restId: string) { create(@Body() dto: CreateRoleDto, @RestId() restId: string) {
return this.roleService.create(restId, dto); return this.roleService.createRestaurantRole(dto, restId);
} }
@Get(':id') @Get(':id')
-24
View File
@@ -1,24 +0,0 @@
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: '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;
}
@@ -75,7 +75,7 @@ export class PermissionsService {
return permissions.flat().map(p => p.name); return permissions.flat().map(p => p.name);
} }
async getFullAdminPermissions(adminId: string, restId: string): Promise<Permission[]> { async getAdminFullPermissions(adminId: string, restId: string): Promise<Permission[]> {
const admin = await this.adminRepository.findOne( const admin = await this.adminRepository.findOne(
{ id: adminId, roles: { restaurant: { id: restId } } }, { id: adminId, roles: { restaurant: { id: restId } } },
{ populate: ['roles', 'roles.role', 'roles.role.permissions'] }, { populate: ['roles', 'roles.role', 'roles.role.permissions'] },
+8 -29
View File
@@ -1,13 +1,12 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common'; import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs'; import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityRepository } from '@mikro-orm/core'; import { EntityRepository, FilterQuery } from '@mikro-orm/core';
import { Role } from '../entities/role.entity'; import { Role } from '../entities/role.entity';
import { Permission } from '../entities/permission.entity'; import { Permission } from '../entities/permission.entity';
import { Restaurant } from '../../restaurants/entities/restaurant.entity'; import { Restaurant } from '../../restaurants/entities/restaurant.entity';
import { EntityManager } from '@mikro-orm/postgresql'; import { EntityManager } from '@mikro-orm/postgresql';
import { CreateRoleDto } from '../dto/create-role.dto'; import { CreateRoleDto } from '../dto/create-role.dto';
import { UpdateRoleDto } from '../dto/update-role.dto'; import { UpdateRoleDto } from '../dto/update-role.dto';
import { FindRolesDto } from '../dto/find-roles.dto';
import { RolePermission } from '../entities/rolePermission.entity'; import { RolePermission } from '../entities/rolePermission.entity';
@Injectable() @Injectable()
@@ -20,7 +19,7 @@ export class RolesService {
private readonly em: EntityManager, private readonly em: EntityManager,
) {} ) {}
async create(restId: string, dto: CreateRoleDto) { async createRestaurantRole(dto: CreateRoleDto, restId: string) {
const { name, permissionIds } = dto; const { name, permissionIds } = dto;
// Check if role already exists // Check if role already exists
@@ -51,7 +50,7 @@ export class RolesService {
// Check if any permission is special // Check if any permission is special
const specialPermissions = permissions.filter(p => p.group === 'special'); const specialPermissions = permissions.filter(p => p.group === 'special');
if (specialPermissions.length > 0) { if (specialPermissions.length > 0) {
throw new BadRequestException('Special permissions cannot be assigned to roles'); throw new BadRequestException('Special permissions cannot be assigned');
} }
permissions.forEach(p => role.permissions.add(p)); permissions.forEach(p => role.permissions.add(p));
} }
@@ -60,35 +59,15 @@ export class RolesService {
return role; return role;
} }
async findAll(restId: string, dto: FindRolesDto) { async findAllGeneralAndRestaurantRoles(restId: string) {
const { name, page = 1, limit = 20 } = dto; const where: FilterQuery<Role> = { $or: [{ restaurant: restId }, { restaurant: null }] };
const offset = (page - 1) * limit;
// Build query dynamically const roles = await this.roleRepository.find(where, {
const query: Record<string, unknown> = restId ? { restaurant: { id: restId } } : {}; orderBy: { createdAt: 'desc' },
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const [roles, count] = await this.roleRepository.findAndCount(query as any, {
offset,
limit,
populate: ['permissions', 'restaurant'], populate: ['permissions', 'restaurant'],
}); });
// Filter by name in memory if provided return roles;
let filtered = roles;
if (name) {
filtered = roles.filter(
r => r.name.toLowerCase().includes(name.toLowerCase()),
);
}
return {
data: filtered,
total: count,
page,
limit,
totalPages: Math.ceil(count / limit),
};
} }
async findOne(restId: string, id: string) { async findOne(restId: string, id: string) {