mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2025-08-25 13:49:40 +00:00
76 lines
2.4 KiB
TypeScript
76 lines
2.4 KiB
TypeScript
import { BadRequestException, forwardRef, Inject, Injectable } from '@nestjs/common';
|
|
import { FindOptionsWhere } from 'typeorm';
|
|
import { CustomerNotificationSettings } from '~/customer/entities/customer-notification-settings.entity';
|
|
import { CustomerService } from '~/customer/services';
|
|
import { Guardian } from '~/guardian/entities/guradian.entity';
|
|
import { CreateUnverifiedUserRequestDto } from '../dtos/request';
|
|
import { User } from '../entities';
|
|
import { Roles } from '../enums';
|
|
import { UserRepository } from '../repositories';
|
|
|
|
@Injectable()
|
|
export class UserService {
|
|
constructor(
|
|
private readonly userRepository: UserRepository,
|
|
@Inject(forwardRef(() => CustomerService)) private readonly customerService: CustomerService,
|
|
) {}
|
|
|
|
findUser(where: FindOptionsWhere<User> | FindOptionsWhere<User>[]) {
|
|
return this.userRepository.findOne(where);
|
|
}
|
|
|
|
async findUserOrThrow(where: FindOptionsWhere<User>) {
|
|
const user = await this.findUser(where);
|
|
|
|
if (!user) {
|
|
throw new BadRequestException('USERS.NOT_FOUND');
|
|
}
|
|
|
|
return user;
|
|
}
|
|
|
|
async findOrCreateUser({ phoneNumber, countryCode }: CreateUnverifiedUserRequestDto) {
|
|
const user = await this.userRepository.findOne({ phoneNumber });
|
|
|
|
if (!user) {
|
|
return this.userRepository.createUnverifiedUser({ phoneNumber, countryCode, roles: [Roles.GUARDIAN] });
|
|
}
|
|
if (user && user.roles.includes(Roles.GUARDIAN) && user.isPasswordSet) {
|
|
throw new BadRequestException('USERS.PHONE_NUMBER_ALREADY_EXISTS');
|
|
}
|
|
|
|
if (user && user.roles.includes(Roles.JUNIOR)) {
|
|
throw new BadRequestException('USERS.JUNIOR_UPGRADE_NOT_SUPPORTED_YET');
|
|
//TODO add role Guardian to the existing user and send OTP
|
|
}
|
|
|
|
return user;
|
|
}
|
|
|
|
async createUser(data: Partial<User>) {
|
|
const user = await this.userRepository.createUser(data);
|
|
|
|
return user;
|
|
}
|
|
|
|
setEmail(userId: string, email: string) {
|
|
return this.userRepository.update(userId, { email });
|
|
}
|
|
|
|
setPasscode(userId: string, passcode: string, salt: string) {
|
|
return this.userRepository.update(userId, { password: passcode, salt, isProfileCompleted: true });
|
|
}
|
|
|
|
async verifyUserAndCreateCustomer(user: User) {
|
|
await this.customerService.createCustomer(
|
|
{
|
|
guardian: Guardian.create({ id: user.id }),
|
|
notificationSettings: new CustomerNotificationSettings(),
|
|
},
|
|
user,
|
|
);
|
|
|
|
return this.findUserOrThrow({ id: user.id });
|
|
}
|
|
}
|