From d07f7d3777175e74e603968d9a269067fa85d759 Mon Sep 17 00:00:00 2001 From: morteza-mortezai Date: Tue, 10 Mar 2026 09:57:37 +0330 Subject: [PATCH] admin --- src/app.module.ts | 6 +- src/modules/admin/admin.module.ts | 6 +- .../admin/entities/adminRole.entity.ts | 7 +- src/modules/admin/providers/admin.service.ts | 58 +- .../admin/repositories/admin.repository.ts | 13 +- src/modules/auth/guards/adminAuth.guard.ts | 24 +- src/modules/auth/services/auth.service.ts | 12 +- .../transformers/admin-login.transformer.ts | 93 --- .../providers/restaurants.service.ts | 33 +- .../roles/controllers/roles.controller.ts | 93 --- src/modules/roles/dto/create-role.dto.ts | 14 - src/modules/roles/dto/update-role.dto.ts | 14 - .../roles/entities/permission.entity.ts | 17 - src/modules/roles/entities/role.entity.ts | 25 - .../roles/entities/rolePermission.entity.ts | 16 - .../roles/providers/permissions.service.ts | 105 ---- src/modules/roles/providers/roles.service.ts | 134 ----- src/modules/roles/roles.module.ts | 20 - src/seeders/DatabaseSeeder.ts | 23 +- src/seeders/admins.seeder.ts | 11 +- src/seeders/data/roles.data.ts | 37 -- src/seeders/permissions.seeder.ts | 28 - src/seeders/roles.seeder.ts | 35 -- test-notifications-socket.html | 561 ------------------ test-pager-socket.html | 494 --------------- 25 files changed, 46 insertions(+), 1833 deletions(-) delete mode 100644 src/modules/auth/transformers/admin-login.transformer.ts delete mode 100644 src/modules/roles/controllers/roles.controller.ts delete mode 100644 src/modules/roles/dto/create-role.dto.ts delete mode 100644 src/modules/roles/dto/update-role.dto.ts delete mode 100755 src/modules/roles/entities/permission.entity.ts delete mode 100755 src/modules/roles/entities/role.entity.ts delete mode 100644 src/modules/roles/entities/rolePermission.entity.ts delete mode 100644 src/modules/roles/providers/permissions.service.ts delete mode 100644 src/modules/roles/providers/roles.service.ts delete mode 100644 src/modules/roles/roles.module.ts delete mode 100644 src/seeders/data/roles.data.ts delete mode 100644 src/seeders/permissions.seeder.ts delete mode 100644 src/seeders/roles.seeder.ts delete mode 100644 test-notifications-socket.html delete mode 100644 test-pager-socket.html diff --git a/src/app.module.ts b/src/app.module.ts index 6808bc1..1bf4bca 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -10,8 +10,7 @@ import { ThrottlerModule } from '@nestjs/throttler'; import { ScheduleModule } from '@nestjs/schedule'; import { RestaurantsModule } from './modules/restaurants/restaurants.module'; import { FoodModule } from './modules/foods/food.module'; -import { RolesModule } from './modules/roles/roles.module'; -import { NotificationsModule } from './modules/notifications/notifications.module'; + import { NotificationsModule } from './modules/notifications/notifications.module'; import { EventEmitterModule } from '@nestjs/event-emitter'; import { CacheModule } from '@nestjs/cache-manager'; import { cacheConfig } from './config/cache.config'; @@ -36,8 +35,7 @@ import { CatalogueModule } from './modules/catalogue/catalogue.module'; ScheduleModule.forRoot(), RestaurantsModule, FoodModule, - RolesModule, - NotificationsModule, + NotificationsModule, EventEmitterModule.forRoot(), BusinessModule, CatalogueModule, diff --git a/src/modules/admin/admin.module.ts b/src/modules/admin/admin.module.ts index eced9fc..612d7aa 100644 --- a/src/modules/admin/admin.module.ts +++ b/src/modules/admin/admin.module.ts @@ -4,9 +4,7 @@ import { MikroOrmModule } from '@mikro-orm/nestjs'; import { Admin } from './entities/admin.entity'; import { JwtModule } from '@nestjs/jwt'; import { AdminRepository } from './repositories/admin.repository'; -import { Role } from '../roles/entities/role.entity'; -import { Permission } from '../roles/entities/permission.entity'; -import { RolePermission } from '../roles/entities/rolePermission.entity'; + import { AdminController } from './controllers/admin.controller'; import { UtilsModule } from '../utils/utils.module'; import { RestaurantsModule } from '../restaurants/restaurants.module'; @@ -17,7 +15,7 @@ import { AdminRoleRepository } from './repositories/admin-role.repository'; providers: [AdminService, AdminRepository, AdminRoleRepository], controllers: [AdminController], imports: [ - MikroOrmModule.forFeature([Admin, Role, Permission, RolePermission, AdminRole]), + MikroOrmModule.forFeature([Admin, AdminRole]), JwtModule, UtilsModule, forwardRef(() => RestaurantsModule), diff --git a/src/modules/admin/entities/adminRole.entity.ts b/src/modules/admin/entities/adminRole.entity.ts index 1e001c3..9f16f94 100644 --- a/src/modules/admin/entities/adminRole.entity.ts +++ b/src/modules/admin/entities/adminRole.entity.ts @@ -1,7 +1,6 @@ import { Entity, Index, ManyToOne, Unique } from '@mikro-orm/core'; import { BaseEntity } from '../../../common/entities/base.entity'; -import { Role } from '../../roles/entities/role.entity'; -import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity'; + import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity'; import { Admin } from './admin.entity'; @Entity({ tableName: 'admin_roles' }) @@ -13,9 +12,7 @@ export class AdminRole extends BaseEntity { @ManyToOne(() => Admin) admin!: Admin; - @ManyToOne(() => Role) - role!: Role; - + @ManyToOne(() => Restaurant, { nullable: true }) restaurant?: Restaurant; } diff --git a/src/modules/admin/providers/admin.service.ts b/src/modules/admin/providers/admin.service.ts index 9c5f803..b92e083 100644 --- a/src/modules/admin/providers/admin.service.ts +++ b/src/modules/admin/providers/admin.service.ts @@ -1,7 +1,6 @@ import { ConflictException, Injectable, NotFoundException } from '@nestjs/common'; import { Admin } from '../entities/admin.entity'; -import { Role } from '../../roles/entities/role.entity'; -import { Restaurant } from '../../restaurants/entities/restaurant.entity'; + import { Restaurant } from '../../restaurants/entities/restaurant.entity'; import { wrap } from '@mikro-orm/core'; import { EntityManager } from '@mikro-orm/postgresql'; import { CreateMyRestaurantAdminDto } from '../dto/create-my-restaurant-admin.dto'; @@ -38,11 +37,11 @@ export class AdminService { const adminPlain = wrap(admin).toObject(); const adminRole = await this.adminRoleRepository.findOne({ admin: admin, restaurant: { id: restId } }); - return { ...adminPlain, role: adminRole?.role }; + return { ...adminPlain }; } async findAllByRestaurantId(restId: string) { - return this.adminRepository.find({ roles: { restaurant: { id: restId } } }, { populate: ['roles', 'roles.role'] }); + return this.adminRepository.find({ roles: { restaurant: { id: restId } } }, { populate: [] }); } async createAdminForMyRestaurant(restId: string, dto: CreateMyRestaurantAdminDto) { @@ -60,9 +59,7 @@ export class AdminService { }); await this.em.persistAndFlush(admin); } - const role = await this.em.findOne(Role, { id: roleId, isSystem: false }); - if (!role) throw new NotFoundException('Role not found'); - + const restaurant = await this.em.findOne(Restaurant, { id: restId }); if (!restaurant) throw new NotFoundException('Restaurant not found'); @@ -74,11 +71,10 @@ export class AdminService { if (!adminRole) { adminRole = this.adminRoleRepository.create({ admin: admin, - role, - restaurant, + restaurant, }); } else { - adminRole.role = role; + } await this.em.persistAndFlush(adminRole); @@ -100,9 +96,7 @@ export class AdminService { }); await this.em.persistAndFlush(admin); } - const role = await this.em.findOne(Role, { id: roleId }); - if (!role) throw new NotFoundException('Role* not found' + roleId); - + const restaurant = await this.em.findOne(Restaurant, { id: restId }); if (!restaurant) throw new NotFoundException('Restaurant not found'); @@ -114,12 +108,10 @@ export class AdminService { if (!adminRole) { adminRole = this.adminRoleRepository.create({ admin: admin, - role, - restaurant, + restaurant, }); } else { - adminRole.role = role; - } + } await this.em.persistAndFlush(adminRole); return admin; @@ -129,13 +121,13 @@ export class AdminService { const restaurant = await this.em.findOne(Restaurant, { id: restId }); if (!restaurant) throw new NotFoundException('Restaurant not found'); - return this.adminRepository.find({ roles: { restaurant: restaurant } }, { populate: ['roles', 'roles.role'] }); + return this.adminRepository.find({ roles: { restaurant: restaurant } }, { populate: [ ] }); } async update(adminId: string, restId: string, dto: UpdateAdminDto) { const admin = await this.adminRepository.findOne( { id: adminId, roles: { restaurant: { id: restId } } }, - { populate: ['roles', 'roles.role', 'roles.restaurant'] }, + { populate: [ ] }, ); if (!admin) { @@ -161,33 +153,7 @@ export class AdminService { } // Update role if roleId is provided - if (roleId) { - const role = await this.em.findOne(Role, { id: roleId, isSystem: false }); - if (!role) { - throw new NotFoundException('Role not found'); - } - - // Find existing AdminRole for this admin and restaurant - const existingAdminRole = await this.em.findOne(AdminRole, { - admin: { id: adminId }, - restaurant: { id: restId }, - }); - - if (existingAdminRole) { - // Update existing role - existingAdminRole.role = role; - } else { - const restaurant = await this.em.findOne(Restaurant, { id: restId }); - if (!restaurant) throw new NotFoundException('Restaurant not found'); - // Create new AdminRole - const newAdminRole = this.em.create(AdminRole, { - admin, - role, - restaurant, - }); - admin.roles.add(newAdminRole); - } - } + await this.em.persistAndFlush(admin); return admin; diff --git a/src/modules/admin/repositories/admin.repository.ts b/src/modules/admin/repositories/admin.repository.ts index 04868a5..50030f7 100644 --- a/src/modules/admin/repositories/admin.repository.ts +++ b/src/modules/admin/repositories/admin.repository.ts @@ -30,7 +30,7 @@ export class AdminRepository extends EntityRepository { admin: { phone: normalizedPhone }, restaurant: { id: restaurant.id }, }, - { populate: ['admin', 'admin.roles', 'role', 'role.permissions', 'restaurant'] }, + { populate: ['admin', 'restaurant'] }, ); if (!adminRole || !adminRole.admin) { @@ -38,20 +38,15 @@ export class AdminRepository extends EntityRepository { } // Ensure all roles are populated - await adminRole.admin.roles.loadItems(); - for (const role of adminRole.admin.roles.getItems()) { - if (role.role && role.role.permissions && !role.role.permissions.isInitialized()) { - await role.role.permissions.loadItems(); - } - } + return adminRole.admin; } async findAdminsWithPermission(restaurantId: string, permission: string): Promise { const admins = await this.em.find( Admin, - { roles: { restaurant: { id: restaurantId }, role: { permissions: { name: permission } } } }, - { populate: ['roles', 'roles.role', 'roles.role.permissions'] }, + { roles: { restaurant: { id: restaurantId }, } }, + { populate: [] }, ); return admins; } diff --git a/src/modules/auth/guards/adminAuth.guard.ts b/src/modules/auth/guards/adminAuth.guard.ts index 1683ea9..3093f55 100644 --- a/src/modules/auth/guards/adminAuth.guard.ts +++ b/src/modules/auth/guards/adminAuth.guard.ts @@ -13,8 +13,7 @@ import { JwtService } from '@nestjs/jwt'; import { ConfigService } from '@nestjs/config'; import { IAdminTokenPayload } from '../interfaces/IToken-payload'; import { PERMISSIONS_KEY } from '../../../common/decorators/permissions.decorator'; -import { PermissionsService } from 'src/modules/roles/providers/permissions.service'; - + export interface AdminAuthRequest extends Request { adminId: string; restId: string; @@ -29,8 +28,7 @@ export class AdminAuthGuard implements CanActivate { private readonly jwtService: JwtService, @Inject(ConfigService) private readonly configService: ConfigService, - private readonly permissionsService: PermissionsService, - private readonly reflector: Reflector, + private readonly reflector: Reflector, ) { } async canActivate(context: ExecutionContext) { @@ -71,23 +69,9 @@ export class AdminAuthGuard implements CanActivate { return true; } - const adminPermission = await this.permissionsService.getAdminPermissions(payload.adminId, payload.restId); - if (!adminPermission || !Array.isArray(adminPermission)) { - this.logger.error('No permissions found', { adminId: payload.adminId, restId: payload.restId }); - throw new ForbiddenException('No permissions found'); - } + - const hasPermission = requiredPermissions.every(p => adminPermission.includes(p)); - - if (!hasPermission) { - this.logger.warn('Insufficient permissions', { - adminId: payload.adminId, - restId: payload.restId, - required: requiredPermissions, - has: adminPermission, - }); - throw new ForbiddenException('You are not authorized to access this resource'); - } + return true; } catch (err) { diff --git a/src/modules/auth/services/auth.service.ts b/src/modules/auth/services/auth.service.ts index ca9e649..da368ee 100644 --- a/src/modules/auth/services/auth.service.ts +++ b/src/modules/auth/services/auth.service.ts @@ -7,8 +7,7 @@ import { TokensService } from './tokens.service'; import { RestRepository } from 'src/modules/restaurants/repositories/rest.repository'; import { AuthMessage, RestMessage } from 'src/common/enums/message.enum'; import { AdminRepository } from 'src/modules/admin/repositories/admin.repository'; -import { AdminLoginTransformer } from '../transformers/admin-login.transformer'; - import { ConfigService } from '@nestjs/config'; + import { ConfigService } from '@nestjs/config'; import { normalizePhone } from '../../utils/phone.util'; @Injectable() @@ -79,9 +78,9 @@ export class AuthService { const tokens = await this.tokensService.generateAccessAndRefreshToken(admin.id, rest.id, true, slug); - const adminResponse = await AdminLoginTransformer.transform(admin, rest); + - return { tokens, admin: adminResponse }; + return { tokens, admin }; } /** * @@ -103,9 +102,8 @@ export class AuthService { const tokens = await this.tokensService.generateAccessAndRefreshToken(admin.id, rest.id, true, slug); - const adminResponse = await AdminLoginTransformer.transform(admin, rest); - - return { tokens, admin: adminResponse }; + + return { tokens, admin }; } private generateOtpCode(): string { diff --git a/src/modules/auth/transformers/admin-login.transformer.ts b/src/modules/auth/transformers/admin-login.transformer.ts deleted file mode 100644 index c58ed4b..0000000 --- a/src/modules/auth/transformers/admin-login.transformer.ts +++ /dev/null @@ -1,93 +0,0 @@ -import type { Admin } from '../../admin/entities/admin.entity'; -import type { Restaurant } from '../../restaurants/entities/restaurant.entity'; - -export interface AdminLoginResponse { - id: string; - firstName?: string; - lastName?: string; - phone: string; - role: string; - permissions: string[]; - restaurant?: { - id: string; - name: string; - slug: string; - }; -} - -export class AdminLoginTransformer { - static async transform(admin: Admin, restaurant?: Restaurant): Promise { - // Find the AdminRole that matches the restaurant (or get the first one) - let adminRole = admin.roles.getItems().find(r => (restaurant ? r.restaurant?.id === restaurant.id : true)); - - // If no match found, get the first one - if (!adminRole && admin.roles.getItems().length > 0) { - adminRole = admin.roles.getItems()[0]; - } - - if (!adminRole) { - return { - id: admin.id, - firstName: admin.firstName, - lastName: admin.lastName, - phone: admin.phone, - role: '', - permissions: [], - restaurant: restaurant - ? { - id: restaurant.id, - name: restaurant.name, - slug: restaurant.slug, - } - : undefined, - }; - } - - // Get the role from AdminRole - const role = adminRole.role; - if (!role) { - return { - id: admin.id, - firstName: admin.firstName, - lastName: admin.lastName, - phone: admin.phone, - role: '', - permissions: [], - restaurant: restaurant - ? { - id: restaurant.id, - name: restaurant.name, - slug: restaurant.slug, - } - : undefined, - }; - } - - // Extract permissions - ensure collection is loaded if needed - let permissions: string[] = []; - if (role.permissions) { - if (role.permissions.isInitialized()) { - permissions = role.permissions.getItems().map(p => p.name); - } else { - await role.permissions.loadItems(); - permissions = role.permissions.getItems().map(p => p.name); - } - } - - return { - id: admin.id, - firstName: admin.firstName, - lastName: admin.lastName, - phone: admin.phone, - role: role.name, - permissions, - restaurant: restaurant - ? { - id: restaurant.id, - name: restaurant.name, - slug: restaurant.slug, - } - : undefined, - }; - } -} diff --git a/src/modules/restaurants/providers/restaurants.service.ts b/src/modules/restaurants/providers/restaurants.service.ts index 43b3d3e..adb326a 100644 --- a/src/modules/restaurants/providers/restaurants.service.ts +++ b/src/modules/restaurants/providers/restaurants.service.ts @@ -11,8 +11,7 @@ import { PaginatedResult } from 'src/common/interfaces/pagination.interface'; import { PlanEnum } from '../interface/plan.interface'; import { Admin } from '../../admin/entities/admin.entity'; import { AdminRole } from '../../admin/entities/adminRole.entity'; -import { Role } from '../../roles/entities/role.entity'; -import { normalizePhone } from 'src/modules/utils/phone.util'; + import { normalizePhone } from 'src/modules/utils/phone.util'; import slugify from 'slugify'; import { Category } from '../../foods/entities/category.entity'; import { Food } from '../../foods/entities/food.entity'; @@ -59,10 +58,7 @@ export class RestaurantsService { // Find the appropriate role based on plan const roleName = dto.plan === PlanEnum.Base ? 'مدیر (پلن پایه)' : 'مدیر ( پلن ویژه)'; - const role = await em.findOne(Role, { name: roleName }); - if (!role) { - throw new BadRequestException(`Role not found for plan: ${dto.plan}`); - } + const normalizedPhone = normalizePhone(dto.phone); let admin = await em.findOne(Admin, { phone: normalizedPhone }); @@ -77,8 +73,7 @@ export class RestaurantsService { // Create admin role relationship const adminRole = em.create(AdminRole, { admin, - role, - restaurant, + restaurant, }); @@ -148,26 +143,8 @@ export class RestaurantsService { if (dto.plan && dto.plan !== restaurant.plan) { const isPremium = dto.plan === PlanEnum.Premium - // find admins and make them premium or base - const adminRoles = await this.em.find(AdminRole, { - restaurant: { - id - }, - role: { - name: isPremium ? 'مدیر (پلن پایه)' : 'مدیر ( پلن ویژه)' - } - }) - const newRole = await this.em.findOne(Role, { - name: isPremium ? 'مدیر ( پلن ویژه)' : 'مدیر (پلن پایه)' - }) - if (!newRole) { - throw new BadRequestException("Role Not Found") - } - adminRoles.forEach(a => { - a.role = newRole - }) - - this.em.persistAndFlush(adminRoles) + + } diff --git a/src/modules/roles/controllers/roles.controller.ts b/src/modules/roles/controllers/roles.controller.ts deleted file mode 100644 index f727fc0..0000000 --- a/src/modules/roles/controllers/roles.controller.ts +++ /dev/null @@ -1,93 +0,0 @@ -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(); - } -} diff --git a/src/modules/roles/dto/create-role.dto.ts b/src/modules/roles/dto/create-role.dto.ts deleted file mode 100644 index 8048ef3..0000000 --- a/src/modules/roles/dto/create-role.dto.ts +++ /dev/null @@ -1,14 +0,0 @@ -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[]; -} diff --git a/src/modules/roles/dto/update-role.dto.ts b/src/modules/roles/dto/update-role.dto.ts deleted file mode 100644 index ccf9939..0000000 --- a/src/modules/roles/dto/update-role.dto.ts +++ /dev/null @@ -1,14 +0,0 @@ -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[]; -} diff --git a/src/modules/roles/entities/permission.entity.ts b/src/modules/roles/entities/permission.entity.ts deleted file mode 100755 index 2dab209..0000000 --- a/src/modules/roles/entities/permission.entity.ts +++ /dev/null @@ -1,17 +0,0 @@ -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(this); -} diff --git a/src/modules/roles/entities/role.entity.ts b/src/modules/roles/entities/role.entity.ts deleted file mode 100755 index 620d681..0000000 --- a/src/modules/roles/entities/role.entity.ts +++ /dev/null @@ -1,25 +0,0 @@ -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(this); - - @ManyToOne(() => Restaurant, { nullable: true }) - restaurant?: Restaurant; - - @OneToMany(() => AdminRole, adminRole => adminRole.role) - admins = new Collection(this); -} diff --git a/src/modules/roles/entities/rolePermission.entity.ts b/src/modules/roles/entities/rolePermission.entity.ts deleted file mode 100644 index a99538a..0000000 --- a/src/modules/roles/entities/rolePermission.entity.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 خودداری کن مگر بخوای نام/نوع ستون را سفارشی کنی. -} diff --git a/src/modules/roles/providers/permissions.service.ts b/src/modules/roles/providers/permissions.service.ts deleted file mode 100644 index b3f9b41..0000000 --- a/src/modules/roles/providers/permissions.service.ts +++ /dev/null @@ -1,105 +0,0 @@ -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, - 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 { - const cacheKey = `${this.ADMIN_PERMISSIONS_KEY}:${adminId}:${restId}`; - - // Try to get from cache first - const cachedPermissions = await this.cacheService.get(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 { - 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 - } - - /** - * Invalidate admin permissions cache - * @param adminId - The admin ID - * @param restId - The restaurant ID - */ - async invalidateAdminPermissionsCache(adminId: string, restId: string): Promise { - const cacheKey = `${this.ADMIN_PERMISSIONS_KEY}:${adminId}:${restId}`; - await this.cacheService.del(cacheKey); - } -} diff --git a/src/modules/roles/providers/roles.service.ts b/src/modules/roles/providers/roles.service.ts deleted file mode 100644 index c13bc4e..0000000 --- a/src/modules/roles/providers/roles.service.ts +++ /dev/null @@ -1,134 +0,0 @@ -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'; -import { RoleMessage } from 'src/common/enums/message.enum'; - -@Injectable() -export class RolesService { - constructor( - @InjectRepository(Role) - private readonly roleRepository: EntityRepository, - @InjectRepository(Permission) - private readonly permissionRepository: EntityRepository, - private readonly em: EntityManager, - ) { } - - async createRestaurantRole(dto: CreateRoleDto, restId: string) { - const { name, permissionIds } = dto; - - const restaurant = await this.em.findOne(Restaurant, { id: restId }); - - if (!restaurant) { - throw new NotFoundException('Restaurant not found'); - } - // Check if role already exists - const existing = await this.roleRepository.findOne({ name, restaurant }); - if (existing) { - throw new BadRequestException('Role with this name already exists for the restaurant'); - } - - - 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 = { $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.findOneOrFail(id); - if (role.restaurant && role.restaurant.id !== restId) { - throw new NotFoundException('Role not found'); - } - return role; - } - - async findOneOrFail(id: string) { - const role = await this.roleRepository.findOne( - { id }, - { populate: ['permissions', 'restaurant','admins'] }, - ); - if (!role) { - throw new NotFoundException('Role not found'); - } - return role; - } - - async update(restId: string, id: string, dto: UpdateRoleDto) { - const role = await this.findOne(restId, id); - - 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.findOne(restId, id); - - if (!role.admins.isEmpty()) { - throw new BadRequestException(RoleMessage.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); - } -} diff --git a/src/modules/roles/roles.module.ts b/src/modules/roles/roles.module.ts deleted file mode 100644 index 3367e3c..0000000 --- a/src/modules/roles/roles.module.ts +++ /dev/null @@ -1,20 +0,0 @@ -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 {} diff --git a/src/seeders/DatabaseSeeder.ts b/src/seeders/DatabaseSeeder.ts index ea30bce..47485d7 100644 --- a/src/seeders/DatabaseSeeder.ts +++ b/src/seeders/DatabaseSeeder.ts @@ -1,9 +1,7 @@ import type { EntityManager } from '@mikro-orm/core'; import { Seeder } from '@mikro-orm/seeder'; import { Restaurant } from '../modules/restaurants/entities/restaurant.entity'; -import { PermissionsSeeder } from './permissions.seeder'; -import { RolesSeeder } from './roles.seeder'; -import { RestaurantsSeeder } from './restaurants.seeder'; + import { RestaurantsSeeder } from './restaurants.seeder'; import { FoodsSeeder } from './foods.seeder'; import { AdminsSeeder } from './admins.seeder'; @@ -12,16 +10,7 @@ export class DatabaseSeeder extends Seeder { const TOTAL_STEPS = 15; console.info('[Seeder] Starting database seed'); // 1. Create Permissions - console.info(`[Seeder] Step 1/${TOTAL_STEPS}: Creating permissions`); - const permissionsSeeder = new PermissionsSeeder(); - const permissions = await permissionsSeeder.run(em); - console.info(`[Seeder] Step 1/${TOTAL_STEPS}: Done`); - - // 2. Create Roles - console.info(`[Seeder] Step 2/${TOTAL_STEPS}: Creating roles`); - const rolesSeeder = new RolesSeeder(); - const rolesMap = await rolesSeeder.run(em, permissions); - console.info(`[Seeder] Step 2/${TOTAL_STEPS}: Done`); + // 3. Create Restaurants console.info(`[Seeder] Step 3/${TOTAL_STEPS}: Creating restaurants`); @@ -46,10 +35,10 @@ export class DatabaseSeeder extends Seeder { // 12. Create Admins - console.info(`[Seeder] Step 12/${TOTAL_STEPS}: Creating admins`); - const adminsSeeder = new AdminsSeeder(); - await adminsSeeder.run(em, rolesMap, restaurantsMap); - console.info(`[Seeder] Step 12/${TOTAL_STEPS}: Done`); + // console.info(`[Seeder] Step 12/${TOTAL_STEPS}: Creating admins`); + // const adminsSeeder = new AdminsSeeder(); + // await adminsSeeder.run(em, restaurantsMap); + // console.info(`[Seeder] Step 12/${TOTAL_STEPS}: Done`); diff --git a/src/seeders/admins.seeder.ts b/src/seeders/admins.seeder.ts index 17699e1..750e671 100644 --- a/src/seeders/admins.seeder.ts +++ b/src/seeders/admins.seeder.ts @@ -1,19 +1,17 @@ import type { EntityManager } from '@mikro-orm/core'; import { Admin } from '../modules/admin/entities/admin.entity'; import { AdminRole } from '../modules/admin/entities/adminRole.entity'; -import type { Role } from '../modules/roles/entities/role.entity'; -import type { Restaurant } from '../modules/restaurants/entities/restaurant.entity'; + import type { Restaurant } from '../modules/restaurants/entities/restaurant.entity'; import { adminsData } from './data/admins.data'; import { normalizePhone } from '../modules/utils/phone.util'; export class AdminsSeeder { - async run(em: EntityManager, rolesMap: Map, restaurantsMap: Map): Promise { + async run(em: EntityManager, restaurantsMap: Map): Promise { for (const adminData of adminsData) { const existingAdmin = await em.findOne(Admin, { phone: adminData.phone }); if (existingAdmin) continue; - const role = rolesMap.get(adminData.roleName); - if (!role) continue; + const restaurant = adminData.restaurantSlug ? restaurantsMap.get(adminData.restaurantSlug) : null; @@ -30,8 +28,7 @@ export class AdminsSeeder { // Create AdminRole linking admin to role and restaurant const adminRole = em.create(AdminRole, { admin, - role, - restaurant: adminData.restaurantSlug ? restaurant : null, + restaurant: adminData.restaurantSlug ? restaurant : null, }); em.persist(adminRole); admin.roles.add(adminRole); diff --git a/src/seeders/data/roles.data.ts b/src/seeders/data/roles.data.ts deleted file mode 100644 index 312cae4..0000000 --- a/src/seeders/data/roles.data.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Permission } from '../../common/enums/permission.enum'; - -export interface RoleConfig { - name: string; - isSystem: boolean; - permissionFilter: (permissionName: Permission) => boolean; -} - -export const rolesData: RoleConfig[] = [ - { - name: 'مدیر (پلن پایه)', - isSystem: false, - permissionFilter: (name: Permission) => - name === Permission.MANAGE_FOODS || - name === Permission.MANAGE_CATEGORIES || - name === Permission.MANAGE_SCHEDULES || - name === Permission.MANAGE_PAGER || - name === Permission.MANAGE_CONTACTS || - name === Permission.MANAGE_ROLES || - - name === Permission.MANAGE_SETTINGS || - name === Permission.MANAGE_ADMINS || - name == Permission.VIEW_REPORTS || - name == Permission.UPDATE_RESTAURANT - }, - { - name: 'مدیر ( پلن ویژه)', - isSystem: false, - permissionFilter: () => true, // All permissions for restaurant role - }, - { - name: 'حسابدار ', - isSystem: false, - permissionFilter: (name: Permission) => - name === Permission.VIEW_REPORTS || name === Permission.MANAGE_PAYMENTS || name === Permission.MANAGE_ORDERS, - }, -]; diff --git a/src/seeders/permissions.seeder.ts b/src/seeders/permissions.seeder.ts deleted file mode 100644 index 5db378d..0000000 --- a/src/seeders/permissions.seeder.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { EntityManager } from '@mikro-orm/core'; -import { Permission as PermissionEntity } from '../modules/roles/entities/permission.entity'; -import { getPermissionsData } from './data/permissions.data'; - -export class PermissionsSeeder { - async run(em: EntityManager): Promise { - const permissions = getPermissionsData(); - const createdPermissions: PermissionEntity[] = []; - - for (const permData of permissions) { - let permission = await em.findOne(PermissionEntity, { name: permData.name }); - if (!permission) { - permission = em.create(PermissionEntity, permData); - em.persist(permission); - } else { - // Update existing permission's title if it changed - if (permission.title !== permData.title) { - permission.title = permData.title; - em.persist(permission); - } - } - createdPermissions.push(permission); - } - - await em.flush(); - return createdPermissions; - } -} diff --git a/src/seeders/roles.seeder.ts b/src/seeders/roles.seeder.ts deleted file mode 100644 index 3f07cb5..0000000 --- a/src/seeders/roles.seeder.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { EntityManager } from '@mikro-orm/core'; -import { Role } from '../modules/roles/entities/role.entity'; -import type { Permission } from '../common/enums/permission.enum'; -import type { Permission as PermissionEntity } from '../modules/roles/entities/permission.entity'; -import { rolesData } from './data/roles.data'; - -export class RolesSeeder { - async run(em: EntityManager, permissions: PermissionEntity[]): Promise> { - const rolesMap = new Map(); - - for (const roleConfig of rolesData) { - let role = await em.findOne(Role, { name: roleConfig.name }); - if (!role) { - role = em.create(Role, { - name: roleConfig.name, - isSystem: true, - }); - - // Add permissions based on role configuration - // TypeScript knows role is not null here because we just created it - const newRole = role; - // Use the permission filter for all roles - const filteredPermissions = permissions.filter(p => roleConfig.permissionFilter(p.name as Permission)); - filteredPermissions.forEach(p => newRole.permissions.add(p)); - - em.persist(newRole); - } - // Always add to map, whether existing or newly created - rolesMap.set(roleConfig.name, role); - } - - await em.flush(); - return rolesMap; - } -} diff --git a/test-notifications-socket.html b/test-notifications-socket.html deleted file mode 100644 index 6e7defa..0000000 --- a/test-notifications-socket.html +++ /dev/null @@ -1,561 +0,0 @@ - - - - - - Notifications Socket.IO Test - - - - -
-
-

🔔 Notifications Socket.IO Test Client

-

Test real-time admin notifications

-
- -
- -
-

Connection

-
- - -
-
- - - Enter JWT token for admin authentication. Restaurant ID will be extracted from token. -
-
- - -
-
Status: Disconnected
-
- - -
-

Get Notifications

-
- - - Number of notifications to retrieve (default: 50) -
-
- -
-
- - -
-

Notifications List

-
-
- No notifications loaded yet. Click "Get Notifications" to fetch. -
-
-
- - -
-

Events Log

-
-
-
Ready to connect...
-
INFO
-
Enter server URL and admin token, then click Connect to start
-
-
-
-
-
- - - - diff --git a/test-pager-socket.html b/test-pager-socket.html deleted file mode 100644 index 4602af1..0000000 --- a/test-pager-socket.html +++ /dev/null @@ -1,494 +0,0 @@ - - - - - - Pager Socket.IO Test - - - - -
-
-

🔔 Pager Socket.IO Test Client

-

Test real-time pager notifications

-
- -
- -
-

Connection

-
- - -
-
- - - Enter JWT token for admin authentication. Required when joining restaurant rooms. -
-
- - -
-
- Status: Disconnected -
-
- - -
-

Room Management

-
- - -
-
- - - Restaurant ID is automatically extracted from your admin token. No need to enter manually. -
- -
- - -
-
- Current Room: None -
-
- - -
-

Events Log

-
-
-
Ready to connect...
-
INFO
-
Enter server URL and click Connect to start
-
-
-
-
-
- - - - -