import { level } from 'winston'; import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { UserRoleMapping } from '../entity/user-role-mapping.entity'; import { Repository } from 'typeorm'; @Injectable() export class UserRoleMappingRepository { constructor( @InjectRepository(UserRoleMapping) private readonly userRoleMappingRepository: Repository, ) {} async save( userRoleMapping: UserRoleMapping, ): Promise { return await this.userRoleMappingRepository.save(userRoleMapping); } async update( id: number, userRoleMapping: UserRoleMapping, ): Promise { await this.userRoleMappingRepository.update(id, userRoleMapping); return await this.userRoleMappingRepository.findOneBy({ id }); } async findByUserId(userId: number): Promise { return await this.userRoleMappingRepository.find({ where: { user_id: userId }, }); } async getDefaultForUser(userId: number): Promise { return await this.userRoleMappingRepository.findOne({ where: { user_id: userId, is_default: 1 }, }); } async findByUserIdAndRoleId( userId: number, roleId: number, appcode?: string, level_id?: string, level_type?: string, ): Promise { return await this.userRoleMappingRepository.findOne({ where: { user_id: userId, role_id: roleId, appcode, level_id, level_type, }, }); } async findByUSRId(usrId: number): Promise { if (usrId) { return null; } return await this.userRoleMappingRepository.findOne({ where: { id: usrId, }, }); } async delete(userId: number, roleId: number) { await this.userRoleMappingRepository.delete({ user_id: userId, role_id: roleId, }); } async deleteByUserId(userId: number, levelType?: string, levelId?: string) { if (levelType && levelId) { await this.userRoleMappingRepository.delete({ user_id: userId, level_type: levelType, level_id: levelId, }); return; } await this.userRoleMappingRepository.delete({ user_id: userId }); } async findDistinctAppcodeByUserId( userId: number, ): Promise<{ appcode: string[] }> { const result = await this.userRoleMappingRepository .createQueryBuilder('urm') .select('DISTINCT urm.appcode', 'appcode') .where('urm.user_id = :userId', { userId }) .getRawMany(); const appcodeArray = result.map((row) => row.appcode); return { appcode: appcodeArray }; } async findByUserIdAndAppCode( userId: number, appCode: string, ): Promise { return await this.userRoleMappingRepository.findOne({ where: { user_id: userId, appcode: appCode }, }); } async findByUserIdAndAppCodeAndLevel( userId: number, appCode: string, levelType: string, levelId: string, ): Promise { return await this.userRoleMappingRepository.findOne({ where: { user_id: userId, appcode: appCode, level_type: levelType, level_id: levelId, }, }); } }