84 lines
2.0 KiB
TypeScript
84 lines
2.0 KiB
TypeScript
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
|
import { UsersService } from '../users/providers/users.service';
|
|
import { CreateResellerDto } from './dto/create-reseller.dto';
|
|
import { ResellerRepository } from './repositories/reseller.repository';
|
|
import { AuthMessage } from '../../common/enums/message.enum';
|
|
|
|
@Injectable()
|
|
export class ResellerService {
|
|
constructor(
|
|
private readonly usersService: UsersService,
|
|
private readonly resellerRepository: ResellerRepository,
|
|
) { }
|
|
|
|
async create(dto: CreateResellerDto) {
|
|
const { name, phone } = dto
|
|
|
|
const user = await this.usersService.findOneWithPhone(phone)
|
|
|
|
if (!user) {
|
|
throw new BadRequestException(AuthMessage.USER_NOT_FOUND)
|
|
}
|
|
|
|
const reseller = this.resellerRepository.create({
|
|
name,
|
|
owner: user
|
|
})
|
|
|
|
await this.resellerRepository.save(reseller)
|
|
|
|
return reseller
|
|
}
|
|
|
|
async findAll() {
|
|
return this.resellerRepository.find({
|
|
relations: {
|
|
owner: true
|
|
}
|
|
})
|
|
}
|
|
|
|
async finResellerAgents(userId: string) {
|
|
const reseller = await this.FindOneOrFailByUserId(userId)
|
|
|
|
return reseller.agents
|
|
}
|
|
|
|
async FindOneOrFailByUserId(userId: string) {
|
|
const reseller = await this.resellerRepository.findOne({
|
|
where: { owner: { id: userId } },
|
|
relations: { agents: true }
|
|
})
|
|
|
|
if (!reseller) {
|
|
throw new NotFoundException()
|
|
}
|
|
|
|
return reseller
|
|
}
|
|
|
|
async createResellerAgent(userId: string, userTobeAgent: string) {
|
|
const reseller = await this.FindOneOrFailByUserId(userId)
|
|
|
|
const { user } = await this.usersService.findOneById(userTobeAgent)
|
|
|
|
user.reseller = reseller
|
|
|
|
await this.usersService.save(user)
|
|
|
|
return user
|
|
}
|
|
|
|
async removeResellerAgent(userId: string, agentToBeDeleted: string) {
|
|
await this.FindOneOrFailByUserId(userId)
|
|
|
|
const { user } = await this.usersService.findOneById(agentToBeDeleted)
|
|
|
|
user.reseller = undefined
|
|
|
|
await this.usersService.save(user)
|
|
|
|
return user
|
|
}
|
|
}
|