This commit is contained in:
2026-03-10 09:57:37 +03:30
parent 97a0abba7e
commit d07f7d3777
25 changed files with 46 additions and 1833 deletions
+2 -4
View File
@@ -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,
+2 -4
View File
@@ -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),
@@ -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;
}
+12 -46
View File
@@ -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;
@@ -30,7 +30,7 @@ export class AdminRepository extends EntityRepository<Admin> {
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<Admin> {
}
// 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<Admin[]> {
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;
}
+4 -20
View File
@@ -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) {
+5 -7
View File
@@ -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 {
@@ -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<AdminLoginResponse> {
// 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,
};
}
}
@@ -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)
}
@@ -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();
}
}
-14
View File
@@ -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[];
}
-14
View File
@@ -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[];
}
@@ -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<Role>(this);
}
-25
View File
@@ -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<Permission>(this);
@ManyToOne(() => Restaurant, { nullable: true })
restaurant?: Restaurant;
@OneToMany(() => AdminRole, adminRole => adminRole.role)
admins = new Collection<AdminRole>(this);
}
@@ -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 خودداری کن مگر بخوای نام/نوع ستون را سفارشی کنی.
}
@@ -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<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
}
/**
* 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);
}
}
@@ -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<Role>,
@InjectRepository(Permission)
private readonly permissionRepository: EntityRepository<Permission>,
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<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.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);
}
}
-20
View File
@@ -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 {}
+6 -17
View File
@@ -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`);
+4 -7
View File
@@ -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<string, Role>, restaurantsMap: Map<string, Restaurant>): Promise<void> {
async run(em: EntityManager, restaurantsMap: Map<string, Restaurant>): Promise<void> {
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);
-37
View File
@@ -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,
},
];
-28
View File
@@ -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<PermissionEntity[]> {
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;
}
}
-35
View File
@@ -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<Map<string, Role>> {
const rolesMap = new Map<string, Role>();
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;
}
}