Files
zod-backend/src/junior/services/junior.service.ts
2025-01-13 16:42:27 +03:00

154 lines
6.0 KiB
TypeScript

import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { Transactional } from 'typeorm-transactional';
import { Roles } from '~/auth/enums';
import { PageOptionsRequestDto } from '~/core/dtos';
import { CustomerService } from '~/customer/services';
import { DocumentService, OciService } from '~/document/services';
import { UserService } from '~/user/services';
import { CreateJuniorRequestDto, SetThemeRequestDto } from '../dtos/request';
import { Junior } from '../entities';
import { JuniorRepository } from '../repositories';
import { JuniorTokenService } from './junior-token.service';
@Injectable()
export class JuniorService {
private readonly logger = new Logger(JuniorService.name);
constructor(
private readonly juniorRepository: JuniorRepository,
private readonly juniorTokenService: JuniorTokenService,
private readonly userService: UserService,
private readonly customerService: CustomerService,
private readonly documentService: DocumentService,
private readonly ociService: OciService,
) {}
@Transactional()
async createJuniors(body: CreateJuniorRequestDto, guardianId: string) {
this.logger.log(`Creating junior for guardian ${guardianId}`);
const existingUser = await this.userService.findUser([{ email: body.email }, { phoneNumber: body.phoneNumber }]);
if (existingUser) {
this.logger.error(`User with email ${body.email} or phone number ${body.phoneNumber} already exists`);
throw new BadRequestException('USER.ALREADY_EXISTS');
}
await this.validateJuniorDocuments(guardianId, body.civilIdFrontId, body.civilIdBackId);
const user = await this.userService.createUser({
email: body.email,
countryCode: body.countryCode,
phoneNumber: body.phoneNumber,
roles: [Roles.JUNIOR],
});
await this.customerService.createJuniorCustomer(guardianId, user.id, body);
this.logger.log(`Junior ${user.id} created successfully`);
return this.juniorTokenService.generateToken(user.id);
}
async findJuniorById(juniorId: string, withGuardianRelation = false, guardianId?: string) {
this.logger.log(`Finding junior ${juniorId}`);
const junior = await this.juniorRepository.findJuniorById(juniorId, withGuardianRelation, guardianId);
if (!junior) {
this.logger.error(`Junior ${juniorId} not found`);
throw new BadRequestException('JUNIOR.NOT_FOUND');
}
this.logger.log(`Junior ${juniorId} found successfully`);
return junior;
}
@Transactional()
async setTheme(body: SetThemeRequestDto, juniorId: string) {
this.logger.log(`Setting theme for junior ${juniorId}`);
const document = await this.documentService.findDocumentById(body.avatarId);
if (!document || document.createdById !== juniorId) {
this.logger.error(`Document ${body.avatarId} not found or not created by junior ${juniorId}`);
throw new BadRequestException('DOCUMENT.NOT_FOUND');
}
const junior = await this.findJuniorById(juniorId);
if (junior.theme) {
this.logger.log(`Removing existing theme for junior ${juniorId}`);
await this.juniorRepository.removeTheme(junior.theme);
}
await this.juniorRepository.setTheme(body, junior);
this.logger.log(`Theme set for junior ${juniorId}`);
return this.juniorRepository.findThemeForJunior(juniorId);
}
async findJuniorsByGuardianId(guardianId: string, pageOptions: PageOptionsRequestDto): Promise<[Junior[], number]> {
this.logger.log(`Finding juniors for guardian ${guardianId}`);
const [juniors, itemCount] = await this.juniorRepository.findJuniorsByGuardianId(guardianId, pageOptions);
this.logger.log(`Juniors found for guardian ${guardianId}`);
await this.prepareJuniorImages(juniors);
return [juniors, itemCount];
}
async validateToken(token: string) {
this.logger.log(`Validating token ${token}`);
const juniorId = await this.juniorTokenService.validateToken(token);
return this.findJuniorById(juniorId, true);
}
generateToken(juniorId: string) {
this.logger.log(`Generating token for junior ${juniorId}`);
return this.juniorTokenService.generateToken(juniorId);
}
async doesJuniorBelongToGuardian(guardianId: string, juniorId: string) {
this.logger.log(`Checking if junior ${juniorId} belongs to guardian ${guardianId}`);
const junior = await this.findJuniorById(juniorId, false, guardianId);
return !!junior;
}
private async validateJuniorDocuments(userId: string, civilIdFrontId: string, civilIdBackId: string) {
this.logger.log(`Validating junior documents`);
if (!civilIdFrontId || !civilIdBackId) {
this.logger.error('Civil id front and back are required');
throw new BadRequestException('JUNIOR.CIVIL_ID_REQUIRED');
}
const [civilIdFront, civilIdBack] = await Promise.all([
this.documentService.findDocumentById(civilIdFrontId),
this.documentService.findDocumentById(civilIdBackId),
]);
if (!civilIdFront || !civilIdBack) {
this.logger.error('Civil id front or back not found');
throw new BadRequestException('JUNIOR.CIVIL_ID_REQUIRED');
}
if (civilIdFront.createdById !== userId || civilIdBack.createdById !== userId) {
this.logger.error(`Civil id front or back not created by user with id ${userId}`);
throw new BadRequestException('JUNIOR.CIVIL_ID_NOT_CREATED_BY_GUARDIAN');
}
const juniorWithSameCivilId = await this.juniorRepository.findJuniorByCivilId(civilIdFrontId, civilIdBackId);
if (juniorWithSameCivilId) {
this.logger.error(
`Junior with civil id front ${civilIdFrontId} and civil id back ${civilIdBackId} already exists`,
);
throw new BadRequestException('JUNIOR.CIVIL_ID_ALREADY_EXISTS');
}
}
private async prepareJuniorImages(juniors: Junior[]) {
this.logger.log(`Preparing junior images`);
await Promise.all(
juniors.map(async (junior) => {
const profilePicture = junior.customer.profilePicture;
if (profilePicture) {
profilePicture.url = await this.ociService.generatePreSignedUrl(profilePicture);
}
}),
);
}
}