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;
}
}
-561
View File
@@ -1,561 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Notifications Socket.IO Test</title>
<script src="https://cdn.socket.io/4.8.1/socket.io.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
border-radius: 12px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 28px;
margin-bottom: 10px;
}
.header p {
opacity: 0.9;
}
.content {
padding: 30px;
}
.section {
margin-bottom: 30px;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #667eea;
}
.section h2 {
color: #333;
margin-bottom: 15px;
font-size: 20px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
color: #555;
font-weight: 500;
}
input,
select {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 6px;
font-size: 14px;
transition: border-color 0.3s;
}
input:focus,
select:focus {
outline: none;
border-color: #667eea;
}
.button-group {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
button {
padding: 12px 24px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
flex: 1;
min-width: 120px;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn-success {
background: #28a745;
color: white;
}
.btn-success:hover {
background: #218838;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(40, 167, 69, 0.4);
}
.btn-danger {
background: #dc3545;
color: white;
}
.btn-danger:hover {
background: #c82333;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4);
}
.btn-secondary {
background: #6c757d;
color: white;
}
.btn-secondary:hover {
background: #5a6268;
}
.status {
padding: 15px;
border-radius: 6px;
margin-bottom: 20px;
font-weight: 500;
}
.status.connected {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.status.disconnected {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.status.connecting {
background: #fff3cd;
color: #856404;
border: 1px solid #ffeaa7;
}
.events {
max-height: 400px;
overflow-y: auto;
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 6px;
font-family: 'Courier New', monospace;
font-size: 13px;
}
.event-item {
margin-bottom: 10px;
padding: 10px;
background: #2d2d2d;
border-radius: 4px;
border-left: 3px solid #667eea;
}
.event-time {
color: #858585;
font-size: 11px;
margin-bottom: 5px;
}
.event-type {
color: #4ec9b0;
font-weight: bold;
margin-bottom: 5px;
}
.event-data {
color: #ce9178;
white-space: pre-wrap;
word-break: break-all;
}
.clear-btn {
margin-top: 10px;
}
.notifications-list {
max-height: 300px;
overflow-y: auto;
background: #f8f9fa;
border-radius: 6px;
padding: 15px;
margin-top: 15px;
}
.notification-item {
background: white;
padding: 12px;
margin-bottom: 10px;
border-radius: 6px;
border-left: 3px solid #667eea;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.notification-title {
font-weight: 600;
color: #333;
margin-bottom: 5px;
}
.notification-content {
color: #666;
font-size: 14px;
margin-bottom: 5px;
}
.notification-meta {
font-size: 12px;
color: #999;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🔔 Notifications Socket.IO Test Client</h1>
<p>Test real-time admin notifications</p>
</div>
<div class="content">
<!-- Connection Section -->
<div class="section">
<h2>Connection</h2>
<div class="form-group">
<label for="serverUrl">Server URL:</label>
<input type="text" id="serverUrl" value="https://dmenuplus-api.dev.danakcorp.com"
placeholder="https://dmenuplus-api.dev.danakcorp.com" />
</div>
<div class="form-group">
<label for="authToken">Admin Token:</label>
<input type="text" id="authToken" placeholder="Bearer token (required)" />
<small style="color: #666; display: block; margin-top: 5px"
>Enter JWT token for admin authentication. Restaurant ID will be extracted from token.</small
>
</div>
<div class="button-group">
<button class="btn-primary" onclick="connect()">Connect</button>
<button class="btn-danger" onclick="disconnect()">Disconnect</button>
</div>
<div id="connectionStatus" class="status disconnected">Status: Disconnected</div>
</div>
<!-- Notifications Section -->
<div class="section">
<h2>Get Notifications</h2>
<div class="form-group">
<label for="limit">Limit (optional):</label>
<input type="number" id="limit" placeholder="50" value="50" min="1" max="100" />
<small style="color: #666; display: block; margin-top: 5px"
>Number of notifications to retrieve (default: 50)</small
>
</div>
<div class="button-group">
<button class="btn-success" onclick="getNotifications()">Get Notifications</button>
</div>
</div>
<!-- Notifications List Section -->
<div class="section">
<h2>Notifications List</h2>
<div id="notificationsList" class="notifications-list">
<div style="text-align: center; color: #999; padding: 20px">
No notifications loaded yet. Click "Get Notifications" to fetch.
</div>
</div>
</div>
<!-- Events Section -->
<div class="section">
<h2>Events Log <button class="btn-secondary clear-btn" onclick="clearEvents()">Clear</button></h2>
<div id="events" class="events">
<div class="event-item">
<div class="event-time">Ready to connect...</div>
<div class="event-type">INFO</div>
<div class="event-data">Enter server URL and admin token, then click Connect to start</div>
</div>
</div>
</div>
</div>
</div>
<script>
let socket = null;
function connect() {
const serverUrl = document.getElementById('serverUrl').value || 'http://localhost:4000';
const token = document.getElementById('authToken').value.trim();
if (socket && socket.connected) {
addEvent('WARNING', 'Already connected!');
return;
}
if (!token) {
addEvent('ERROR', 'Admin token is required!');
return;
}
updateStatus('connecting', 'Connecting...');
addEvent('INFO', `Connecting to ${serverUrl}/notifications...`);
const authOptions = {};
if (token) {
// Remove "Bearer " prefix if present
const cleanToken = token.startsWith('Bearer ') ? token.substring(7) : token;
authOptions.token = cleanToken;
addEvent('INFO', 'Using authentication token');
}
socket = io(`${serverUrl}/notifications`, {
transports: ['websocket', 'polling'],
reconnection: true,
reconnectionDelay: 1000,
reconnectionAttempts: 5,
auth: authOptions,
});
socket.on('connect', () => {
updateStatus('connected', 'Connected');
addEvent('SUCCESS', `Connected! Socket ID: ${socket.id}`);
});
socket.on('disconnect', reason => {
updateStatus('disconnected', 'Disconnected');
addEvent('WARNING', `Disconnected: ${reason}`);
});
socket.on('connect_error', error => {
updateStatus('disconnected', 'Connection Failed');
addEvent('ERROR', `Connection error: ${error.message}`);
});
socket.on('joined', data => {
addEvent('SUCCESS', `Joined room: ${data.room || 'unknown'}`, data);
});
// Handle notifications event - can be either:
// 1. List response: { notifications: [...] }
// 2. Real-time notification: { subject: string, body: string }
socket.on('notifications', data => {
if (Array.isArray(data.notifications)) {
// List of notifications response
addEvent('SUCCESS', `Received ${data.notifications.length} notifications`, data);
displayNotifications(data.notifications);
} else if (data.subject || data.body) {
// Real-time single notification
addEvent('NOTIFICATION', 'New notification received', data);
addRealTimeNotification(data);
} else if (Array.isArray(data)) {
// Direct array response
addEvent('SUCCESS', `Received ${data.length} notifications`, data);
displayNotifications(data);
} else {
// Unknown format, try to extract notifications from various possible structures
addEvent('INFO', 'Received notifications data', data);
const notifications = data.notifications || data.data || (Array.isArray(data) ? data : [data]);
if (Array.isArray(notifications) && notifications.length > 0) {
displayNotifications(notifications);
}
}
});
socket.on('error', data => {
addEvent('ERROR', data.message || 'Error occurred', data);
});
// Handle authentication errors
socket.on('exception', data => {
addEvent('ERROR', `Server error: ${data.message || JSON.stringify(data)}`, data);
});
}
function disconnect() {
if (socket) {
socket.disconnect();
socket = null;
updateStatus('disconnected', 'Disconnected');
addEvent('INFO', 'Manually disconnected');
}
}
function getNotifications() {
if (!socket || !socket.connected) {
addEvent('ERROR', 'Please connect first!');
return;
}
const limitInput = document.getElementById('limit');
const limit = limitInput.value ? parseInt(limitInput.value, 10) : 50;
if (limit < 1 || limit > 100) {
addEvent('ERROR', 'Limit must be between 1 and 100');
return;
}
socket.emit('get:notifications', { limit });
addEvent('INFO', `Requesting notifications (limit: ${limit})...`);
}
function displayNotifications(notifications) {
const listDiv = document.getElementById('notificationsList');
if (!notifications || notifications.length === 0) {
listDiv.innerHTML =
'<div style="text-align: center; color: #999; padding: 20px;">No notifications found.</div>';
return;
}
let html = '';
notifications.forEach(notification => {
// Handle both full notification objects and simple payloads
const title = notification.title || notification.subject || 'N/A';
const content = notification.content || notification.body || 'No content';
const id = notification.id || 'N/A';
const date = notification.createdAt
? new Date(notification.createdAt).toLocaleString()
: notification.created_at
? new Date(notification.created_at).toLocaleString()
: 'N/A';
const userName = notification.user
? `${notification.user.firstName || ''} ${notification.user.lastName || ''}`.trim()
: notification.userName || '';
html += `
<div class="notification-item">
<div class="notification-title">${escapeHtml(title)}</div>
<div class="notification-content">${escapeHtml(content)}</div>
<div class="notification-meta">
ID: ${id} | Created: ${date}
${userName ? ` | User: ${escapeHtml(userName)}` : ''}
${notification.admin ? ` | Admin: ${notification.admin.firstName || ''} ${notification.admin.lastName || ''}` : ''}
</div>
</div>
`;
});
listDiv.innerHTML = html;
}
function addRealTimeNotification(notification) {
const listDiv = document.getElementById('notificationsList');
const title = notification.subject || notification.title || 'New Notification';
const content = notification.body || notification.content || 'No content';
const currentTime = new Date().toLocaleString();
const notificationHtml = `
<div class="notification-item" style="animation: slideIn 0.3s ease-out;">
<div class="notification-title">${escapeHtml(title)}</div>
<div class="notification-content">${escapeHtml(content)}</div>
<div class="notification-meta">
Received: ${currentTime}
</div>
</div>
`;
// Add to the top of the list
if (listDiv.children.length === 1 && listDiv.children[0].textContent.includes('No notifications')) {
listDiv.innerHTML = notificationHtml;
} else {
listDiv.insertAdjacentHTML('afterbegin', notificationHtml);
}
}
function escapeHtml(text) {
if (!text) return '';
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function updateStatus(status, message) {
const statusEl = document.getElementById('connectionStatus');
statusEl.className = `status ${status}`;
statusEl.textContent = `Status: ${message}`;
}
function addEvent(type, message, data = null) {
const eventsDiv = document.getElementById('events');
const eventItem = document.createElement('div');
eventItem.className = 'event-item';
const time = new Date().toLocaleTimeString();
const typeColors = {
INFO: '#4ec9b0',
SUCCESS: '#4ec9b0',
WARNING: '#dcdcaa',
ERROR: '#f48771',
NOTIFICATIONS_LIST: '#4fc1ff',
NOTIFICATION: '#9cdcfe',
};
eventItem.innerHTML = `
<div class="event-time">${time}</div>
<div class="event-type" style="color: ${typeColors[type] || '#4ec9b0'}">[${type}]</div>
<div class="event-data">${message}</div>
${data ? `<div class="event-data" style="margin-top: 8px; color: #9cdcfe;">${JSON.stringify(data, null, 2)}</div>` : ''}
`;
eventsDiv.insertBefore(eventItem, eventsDiv.firstChild);
}
function clearEvents() {
document.getElementById('events').innerHTML = '';
addEvent('INFO', 'Events log cleared');
}
</script>
</body>
</html>
-494
View File
@@ -1,494 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pager Socket.IO Test</title>
<script src="https://cdn.socket.io/4.8.1/socket.io.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
border-radius: 12px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 28px;
margin-bottom: 10px;
}
.header p {
opacity: 0.9;
}
.content {
padding: 30px;
}
.section {
margin-bottom: 30px;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #667eea;
}
.section h2 {
color: #333;
margin-bottom: 15px;
font-size: 20px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
color: #555;
font-weight: 500;
}
input, select {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 6px;
font-size: 14px;
transition: border-color 0.3s;
}
input:focus, select:focus {
outline: none;
border-color: #667eea;
}
.button-group {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
button {
padding: 12px 24px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
flex: 1;
min-width: 120px;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn-success {
background: #28a745;
color: white;
}
.btn-success:hover {
background: #218838;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(40, 167, 69, 0.4);
}
.btn-danger {
background: #dc3545;
color: white;
}
.btn-danger:hover {
background: #c82333;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4);
}
.btn-secondary {
background: #6c757d;
color: white;
}
.btn-secondary:hover {
background: #5a6268;
}
.status {
padding: 15px;
border-radius: 6px;
margin-bottom: 20px;
font-weight: 500;
}
.status.connected {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.status.disconnected {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.status.connecting {
background: #fff3cd;
color: #856404;
border: 1px solid #ffeaa7;
}
.events {
max-height: 400px;
overflow-y: auto;
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 6px;
font-family: 'Courier New', monospace;
font-size: 13px;
}
.event-item {
margin-bottom: 10px;
padding: 10px;
background: #2d2d2d;
border-radius: 4px;
border-left: 3px solid #667eea;
}
.event-time {
color: #858585;
font-size: 11px;
margin-bottom: 5px;
}
.event-type {
color: #4ec9b0;
font-weight: bold;
margin-bottom: 5px;
}
.event-data {
color: #ce9178;
white-space: pre-wrap;
word-break: break-all;
}
.room-badge {
display: inline-block;
padding: 4px 12px;
background: #667eea;
color: white;
border-radius: 12px;
font-size: 12px;
margin-left: 10px;
}
.clear-btn {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🔔 Pager Socket.IO Test Client</h1>
<p>Test real-time pager notifications</p>
</div>
<div class="content">
<!-- Connection Section -->
<div class="section">
<h2>Connection</h2>
<div class="form-group">
<label for="serverUrl">Server URL:</label>
<input type="text" id="serverUrl" value="http://localhost:4000" placeholder="http://localhost:4000">
</div>
<div class="form-group">
<label for="authToken">Admin Token (for Restaurant rooms):</label>
<input type="text" id="authToken" placeholder="Bearer token (optional, required for restaurant rooms)">
<small style="color: #666; display: block; margin-top: 5px;">Enter JWT token for admin authentication. Required when joining restaurant rooms.</small>
</div>
<div class="button-group">
<button class="btn-primary" onclick="connect()">Connect</button>
<button class="btn-danger" onclick="disconnect()">Disconnect</button>
</div>
<div id="connectionStatus" class="status disconnected">
Status: Disconnected
</div>
</div>
<!-- Room Management Section -->
<div class="section">
<h2>Room Management</h2>
<div class="form-group">
<label for="userType">User Type:</label>
<select id="userType" onchange="updateRoomInputs()">
<option value="restaurant">Restaurant (Admin/Staff)</option>
<option value="session">Session (Public User)</option>
</select>
</div>
<div class="form-group" id="restaurantGroup">
<label for="restId">Restaurant ID:</label>
<input type="text" id="restId" placeholder="Auto-extracted from token" disabled>
<small style="color: #666; display: block; margin-top: 5px;">Restaurant ID is automatically extracted from your admin token. No need to enter manually.</small>
</div>
<div class="form-group" id="sessionGroup" style="display: none;">
<label for="cookieId">Cookie ID:</label>
<input type="text" id="cookieId" placeholder="Enter cookie ID (from pager cookie)">
</div>
<div class="button-group">
<button class="btn-success" onclick="joinRoom()">Join Room</button>
<button class="btn-secondary" onclick="leaveRoom()">Leave Room</button>
</div>
<div id="roomStatus" style="margin-top: 15px;">
<strong>Current Room:</strong> <span id="currentRoom">None</span>
</div>
</div>
<!-- Events Section -->
<div class="section">
<h2>Events Log <button class="btn-secondary clear-btn" onclick="clearEvents()">Clear</button></h2>
<div id="events" class="events">
<div class="event-item">
<div class="event-time">Ready to connect...</div>
<div class="event-type">INFO</div>
<div class="event-data">Enter server URL and click Connect to start</div>
</div>
</div>
</div>
</div>
</div>
<script>
let socket = null;
let currentRoom = null;
function updateRoomInputs() {
const userType = document.getElementById('userType').value;
const restaurantGroup = document.getElementById('restaurantGroup');
const sessionGroup = document.getElementById('sessionGroup');
if (userType === 'restaurant') {
restaurantGroup.style.display = 'block';
sessionGroup.style.display = 'none';
} else {
restaurantGroup.style.display = 'none';
sessionGroup.style.display = 'block';
}
}
function connect() {
const serverUrl = document.getElementById('serverUrl').value || 'http://localhost:4000';
const token = document.getElementById('authToken').value.trim();
if (socket && socket.connected) {
addEvent('WARNING', 'Already connected!');
return;
}
updateStatus('connecting', 'Connecting...');
addEvent('INFO', `Connecting to ${serverUrl}/pager...`);
const authOptions = {};
if (token) {
// Remove "Bearer " prefix if present
const cleanToken = token.startsWith('Bearer ') ? token.substring(7) : token;
authOptions.token = cleanToken;
addEvent('INFO', 'Using authentication token');
}
socket = io(`${serverUrl}/pager`, {
transports: ['websocket', 'polling'],
reconnection: true,
reconnectionDelay: 1000,
reconnectionAttempts: 5,
auth: authOptions
});
socket.on('connect', () => {
updateStatus('connected', 'Connected');
addEvent('SUCCESS', `Connected! Socket ID: ${socket.id}`);
});
socket.on('disconnect', (reason) => {
updateStatus('disconnected', 'Disconnected');
addEvent('WARNING', `Disconnected: ${reason}`);
currentRoom = null;
document.getElementById('currentRoom').textContent = 'None';
});
socket.on('connect_error', (error) => {
updateStatus('disconnected', 'Connection Failed');
addEvent('ERROR', `Connection error: ${error.message}`);
});
socket.on('joined', (data) => {
addEvent('SUCCESS', `Joined room: ${data.room}`, data);
currentRoom = data.room;
document.getElementById('currentRoom').textContent = data.room;
// If it's a restaurant room, extract and display the restId
if (data.room && data.room.startsWith('restaurant:')) {
const restId = data.room.replace('restaurant:', '');
document.getElementById('restId').value = restId;
}
});
socket.on('left', (data) => {
addEvent('INFO', `Left room: ${data.room}`, data);
if (currentRoom === data.room) {
currentRoom = null;
document.getElementById('currentRoom').textContent = 'None';
}
});
socket.on('error', (data) => {
addEvent('ERROR', data.message || 'Error occurred', data);
});
// Pager events
socket.on('pager:created', (data) => {
addEvent('PAGER_CREATED', 'New pager request created!', data);
});
socket.on('pager:status:updated', (data) => {
addEvent('PAGER_STATUS_UPDATED', 'Pager status updated!', data);
});
// Handle authentication errors
socket.on('exception', (data) => {
addEvent('ERROR', `Server error: ${data.message || JSON.stringify(data)}`, data);
});
}
function disconnect() {
if (socket) {
socket.disconnect();
socket = null;
updateStatus('disconnected', 'Disconnected');
addEvent('INFO', 'Manually disconnected');
currentRoom = null;
document.getElementById('currentRoom').textContent = 'None';
}
}
function joinRoom() {
if (!socket || !socket.connected) {
addEvent('ERROR', 'Please connect first!');
return;
}
const userType = document.getElementById('userType').value;
if (userType === 'restaurant') {
const token = document.getElementById('authToken').value.trim();
if (!token) {
addEvent('ERROR', 'Admin token is required for restaurant rooms. Please enter your JWT token in the Connection section.');
return;
}
// Restaurant ID is extracted from token automatically, no need to send it
socket.emit('join:restaurant', {});
addEvent('INFO', 'Joining restaurant room (restId will be extracted from token)...');
} else {
const cookieId = document.getElementById('cookieId').value;
if (!cookieId) {
addEvent('ERROR', 'Please enter Cookie ID');
return;
}
socket.emit('join:session', { cookieId });
addEvent('INFO', `Joining session room: cookie:${cookieId}`);
}
}
function leaveRoom() {
if (!socket || !socket.connected) {
addEvent('ERROR', 'Please connect first!');
return;
}
if (!currentRoom) {
addEvent('WARNING', 'Not in any room');
return;
}
socket.emit('leave:room', { room: currentRoom });
}
function updateStatus(status, message) {
const statusEl = document.getElementById('connectionStatus');
statusEl.className = `status ${status}`;
statusEl.textContent = `Status: ${message}`;
}
function addEvent(type, message, data = null) {
const eventsDiv = document.getElementById('events');
const eventItem = document.createElement('div');
eventItem.className = 'event-item';
const time = new Date().toLocaleTimeString();
const typeColors = {
'INFO': '#4ec9b0',
'SUCCESS': '#4ec9b0',
'WARNING': '#dcdcaa',
'ERROR': '#f48771',
'PAGER_CREATED': '#4fc1ff',
'PAGER_STATUS_UPDATED': '#4fc1ff'
};
eventItem.innerHTML = `
<div class="event-time">${time}</div>
<div class="event-type" style="color: ${typeColors[type] || '#4ec9b0'}">[${type}]</div>
<div class="event-data">${message}</div>
${data ? `<div class="event-data" style="margin-top: 8px; color: #9cdcfe;">${JSON.stringify(data, null, 2)}</div>` : ''}
`;
eventsDiv.insertBefore(eventItem, eventsDiv.firstChild);
}
function clearEvents() {
document.getElementById('events').innerHTML = '';
addEvent('INFO', 'Events log cleared');
}
// Initialize
updateRoomInputs();
</script>
</body>
</html>