update admin
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { EntityRepository } from '@mikro-orm/core';
|
||||
import { Admin } from '../entities/admin.entity';
|
||||
@@ -7,6 +7,8 @@ import { Restaurant } from '../../restaurants/entities/restaurant.entity';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { CacheService } from '../../utils/cache.service';
|
||||
import { CreateMyRestaurantAdminDto } from '../dto/create-my-restaurant-admin.dto';
|
||||
import { UpdateAdminDto } from '../dto/update-admin.dto';
|
||||
import { AdminRole } from '../entities/adminRole.entity';
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
@@ -74,4 +76,62 @@ export class AdminService {
|
||||
await this.em.persistAndFlush(admin);
|
||||
return admin;
|
||||
}
|
||||
|
||||
async update(id: string, restId: string, dto: UpdateAdminDto): Promise<Admin> {
|
||||
const admin = await this.adminRepository.findOne({ id }, { populate: ['roles', 'roles.role', 'roles.restaurant'] });
|
||||
|
||||
if (!admin) {
|
||||
throw new NotFoundException('Admin not found');
|
||||
}
|
||||
|
||||
const { roleId, ...rest } = dto;
|
||||
|
||||
// Update scalar fields (firstName, lastName, phone)
|
||||
if (rest.firstName !== undefined) {
|
||||
admin.firstName = rest.firstName;
|
||||
}
|
||||
if (rest.lastName !== undefined) {
|
||||
admin.lastName = rest.lastName;
|
||||
}
|
||||
if (rest.phone !== undefined) {
|
||||
admin.phone = rest.phone;
|
||||
}
|
||||
|
||||
// Update role if roleId is provided
|
||||
if (roleId) {
|
||||
const role = await this.em.findOne(Role, { id: roleId });
|
||||
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');
|
||||
}
|
||||
|
||||
// Find existing AdminRole for this admin and restaurant
|
||||
const existingAdminRole = await this.em.findOne(AdminRole, {
|
||||
admin: { id },
|
||||
restaurant: { id: restId },
|
||||
});
|
||||
|
||||
if (existingAdminRole) {
|
||||
// Update existing role
|
||||
existingAdminRole.role = role;
|
||||
await this.em.persistAndFlush(existingAdminRole);
|
||||
} else {
|
||||
// Create new AdminRole
|
||||
const newAdminRole = this.em.create(AdminRole, {
|
||||
admin,
|
||||
role,
|
||||
restaurant,
|
||||
});
|
||||
admin.roles.add(newAdminRole);
|
||||
await this.em.persistAndFlush(newAdminRole);
|
||||
}
|
||||
}
|
||||
|
||||
await this.em.persistAndFlush(admin);
|
||||
return admin;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user