role module

This commit is contained in:
2026-01-13 23:28:33 +03:30
parent d630cb844a
commit d046dc21ac
17 changed files with 171 additions and 442 deletions
@@ -1,21 +1,17 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityManager, EntityRepository } from '@mikro-orm/core';
import { EntityRepository } from '@mikro-orm/core';
import { Permission } from '../entities/permission.entity';
import { CacheService } from 'src/modules/util/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() {
@@ -23,83 +19,21 @@ export class PermissionsService {
return permissions;
}
/**
* Get admin permissions from cache or database
* @param adminId - The admin ID
* @param - The restaurant ID
* @returns Array of permission names (string[])
*/
async getAdminPermissions(adminId: string, : string): Promise<string[]> {
const cacheKey = `${this.ADMIN_PERMISSIONS_KEY}:${adminId}:${}`;
// 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
}
}
async getAdminPermissions(adminId: string) {
// If not in cache, fetch from database
const admin = await this.adminRepository.findOne(
{ id: adminId, roles: { restaurant: { id: } } },
{ populate: ['roles', 'roles.role', 'roles.role.permissions'] },
{ id: adminId },
{ populate: ['role', 'role.permissions'] },
);
if (!admin || !admin.roles) {
if (!admin || !admin.role) {
return [];
}
// Ensure roles collection is loaded
await admin.roles.loadItems();
const permissions = admin.role.permissions.map(p => p)
// 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);
return permissions
}
async getAdminFullPermissions(adminId: string, : string): Promise<Permission[]> {
const listOfPermissions = []
const adminRoles = await this.em.findOne(AdminRole, {
admin: {
id: adminId,
},
restaurant: {
id: ,
},
}, { populate: ['role', 'role.permissions'] });
if (adminRoles) {
listOfPermissions.push(...adminRoles.role.permissions.getItems());
}
return listOfPermissions.map(permission => permission);
}
/**
* Invalidate admin permissions cache
* @param adminId - The admin ID
* @param - The restaurant ID
*/
async invalidateAdminPermissionsCache(adminId: string, : string): Promise<void> {
const cacheKey = `${this.ADMIN_PERMISSIONS_KEY}:${adminId}:${}`;
await this.cacheService.del(cacheKey);
}
}
+23 -40
View File
@@ -3,42 +3,33 @@ 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 { RoleRepository } from '../respository/role.repository';
@Injectable()
export class RolesService {
constructor(
@InjectRepository(Role)
private readonly roleRepository: EntityRepository<Role>,
private readonly roleRepository: RoleRepository,
@InjectRepository(Permission)
private readonly permissionRepository: EntityRepository<Permission>,
private readonly em: EntityManager,
) { }
async createRestaurantRole(dto: CreateRoleDto, : string) {
const { name, permissionIds } = dto;
async create(dto: CreateRoleDto) {
const { name, title, permissionIds } = dto;
// Check if role already exists
const existing = await this.roleRepository.findOne({ name, restaurant: ? { id: } : null });
const existing = await this.roleRepository.findOne({ name });
if (existing) {
throw new BadRequestException('Role with this name already exists for the restaurant');
}
let restaurant: Restaurant | null = null;
if () {
restaurant = await this.em.findOne(Restaurant, { id: });
if (!restaurant) {
throw new NotFoundException('Restaurant not found');
}
throw new BadRequestException('Role with this key already exists');
}
const role = this.roleRepository.create({
name,
restaurant,
title,
isSystem: false,
});
@@ -55,21 +46,21 @@ export class RolesService {
return role;
}
async findAllGeneralAndRestaurantRoles(: string) {
const where: FilterQuery<Role> = { $or: [{ restaurant: }, { restaurant: null }], isSystem: false };
async findAll() {
const where: FilterQuery<Role> = { isSystem: false };
const roles = await this.roleRepository.find(where, {
orderBy: { createdAt: 'desc' },
populate: ['permissions', 'restaurant'],
populate: ['permissions'],
});
return roles;
}
async findOne(: string, id: string) {
async findOne(id: string) {
const role = await this.roleRepository.findOne(
{ id, restaurant: { id: } },
{ populate: ['permissions', 'restaurant'] },
{ id },
{ populate: ['permissions'] },
);
if (!role) {
throw new NotFoundException('Role not found');
@@ -77,10 +68,10 @@ export class RolesService {
return role;
}
async update(: string, id: string, dto: UpdateRoleDto) {
async update(id: string, dto: UpdateRoleDto) {
const role = await this.roleRepository.findOne(
{ id, restaurant: { id: } },
{ populate: ['permissions', 'restaurant'] },
{ id },
{ populate: ['permissions'] },
);
if (!role) {
throw new NotFoundException('Role not found');
@@ -90,6 +81,10 @@ export class RolesService {
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();
@@ -104,22 +99,10 @@ export class RolesService {
return role;
}
async findAllSystemRoles() {
const roles = await this.roleRepository.find(
{ isSystem: true },
{
orderBy: { createdAt: 'desc' },
populate: ['permissions', 'restaurant'],
},
);
return roles;
}
async remove(: string, id: string) {
async remove(id: string) {
const role = await this.roleRepository.findOne(
{ id, restaurant: { id: } },
{ populate: ['permissions', 'restaurant'] },
{ id },
{ populate: ['permissions'] },
);
if (!role) {
throw new NotFoundException('Role not found');