forked from Ynov/ptitspas-ynov-back
57 lines
2.4 KiB
TypeScript
57 lines
2.4 KiB
TypeScript
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { BaseService } from 'src/common/base.service';
|
|
import { Parents } from 'src/entities/parents.entity';
|
|
import { RoleType, Users } from 'src/entities/users.entity';
|
|
import { DeepPartial, Repository } from 'typeorm';
|
|
import { CreateParentDto } from './dto/create_parents.dto';
|
|
|
|
@Injectable()
|
|
export class ParentsService extends BaseService<Parents> {
|
|
constructor(
|
|
@InjectRepository(Parents) private readonly parentsRepository: Repository<Parents>,
|
|
@InjectRepository(Users) private readonly usersRepository: Repository<Users>,
|
|
) {
|
|
super(parentsRepository);
|
|
}
|
|
|
|
override async create(data: DeepPartial<Parents>): Promise<Parents> {
|
|
const dto = data as CreateParentDto;
|
|
|
|
const user = await this.usersRepository.findOneBy({ id: dto.id_utilisateur });
|
|
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
|
if (user.role !== RoleType.PARENT) throw new BadRequestException('Acces reserve aux parents');
|
|
|
|
const exist = await this.parentsRepository.findOneBy({ user_id: dto.id_utilisateur });
|
|
if (exist) throw new ConflictException('Ce parent existe deja');
|
|
|
|
let co_parent: Users | null = null;
|
|
if (dto.co_parent_id) {
|
|
co_parent = await this.usersRepository.findOneBy({ id: dto.co_parent_id });
|
|
if (!co_parent) throw new NotFoundException('Co-parent introuvable');
|
|
if (co_parent.role !== RoleType.PARENT) throw new BadRequestException('Acces reserve aux parents');
|
|
}
|
|
const entity = this.parentsRepository.create({
|
|
user_id: dto.id_utilisateur,
|
|
user,
|
|
co_parent: co_parent ?? undefined,
|
|
}) as DeepPartial<Parents>;
|
|
return this.parentsRepository.save(entity)
|
|
}
|
|
|
|
override async findAll(): Promise<Parents[]> {
|
|
return this.parentsRepository.find({
|
|
relations: ['user', 'co_parent',
|
|
'parentChildren', 'dossiers'],
|
|
});
|
|
}
|
|
|
|
override async findOne(user_id: string): Promise<Parents> {
|
|
const parent = await this.parentsRepository.findOne({
|
|
where: { user_id },
|
|
relations: ['user', 'co_parent', 'parentChildren', 'dossiers'],
|
|
});
|
|
if (!parent) throw new NotFoundException('Parent introuvable');
|
|
return parent;
|
|
}
|
|
} |