Newer
Older
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { MailerService } from '../mailer/mailer.service';
import { CreateTempUserDto } from './dto/create-temp-user.dto';
import { ITempUser } from './temp-user.interface';
import { TempUser } from './temp-user.schema';
@Injectable()
export class TempUserService {
private readonly logger = new Logger(TempUserService.name);
constructor(
private readonly mailerService: MailerService,
@InjectModel(TempUser.name) private tempUserModel: Model<ITempUser>
) {}
public async create(createTempUser: CreateTempUserDto, structureName: string): Promise<TempUser> {
const userInDb = await this.findOne(createTempUser.email);
if (userInDb) {
throw new HttpException('User already exists', HttpStatus.BAD_REQUEST);
}
const createUser = await this.tempUserModel.create(createTempUser);
this.logger.debug(`TempUsersService | tempUser created`);
// Send email
this.sendUserMail(createUser, structureName);

Marlène SIMONDANT
committed
public async findAll(): Promise<ITempUser[]> {
try {
const tempUsers = await this.tempUserModel
.find()
.populate({
path: 'structuresLink',
select: 'structureName',
})
.exec();
return tempUsers;
} catch (error) {
throw new Error('An error occurred while fetching temp users: ' + error.message);
}
}
public async findOne(mail: string): Promise<ITempUser> {
return this.tempUserModel.findOne({ email: mail }).exec();
public async findById(id: string): Promise<TempUser> {
return this.tempUserModel.findById(new Types.ObjectId(id)).exec();
}
public async delete(mail: string): Promise<TempUser> {
const userInDb = await this.findOne(mail);
if (!userInDb) {

Marlène SIMONDANT
committed
throw new HttpException('User does not exist', HttpStatus.BAD_REQUEST);
await this.tempUserModel.deleteOne({ email: mail }).exec();
return userInDb;
}
public async updateStructureLinked(createTempUser: CreateTempUserDto): Promise<TempUser> {

Marlène SIMONDANT
committed
// Find the user by email
const userInDb = await this.tempUserModel.findOne({ email: createTempUser.email }).exec();

Marlène SIMONDANT
committed
if (!userInDb) {
throw new HttpException('User not found', HttpStatus.NOT_FOUND);
}
// Check if the structuresLink already contains the provided structure
if (userInDb.structuresLink.includes(createTempUser.structuresLink[0])) {
throw new HttpException('User already linked', HttpStatus.UNPROCESSABLE_ENTITY);
}

Marlène SIMONDANT
committed
// Add the new structure to structuresLink
userInDb.structuresLink.push(createTempUser.structuresLink[0]);
// Save the updated user
const updatedUser = await userInDb.save();
return updatedUser;

Marlène SIMONDANT
committed
* Send email in order to tell the user that an account is already filled with his structure info.
public async sendUserMail(user: ITempUser, structureName: string, existingUser?: boolean): Promise<void> {
const config = this.mailerService.config;
const ejsPath = this.mailerService.getTemplateLocation(
existingUser ? config.templates.userAddedToStructure.ejs : config.templates.tempUserRegistration.ejs
);
const jsonConfig = this.mailerService.loadJsonConfig(
existingUser ? config.templates.userAddedToStructure.json : config.templates.tempUserRegistration.json
);
const html = await ejs.renderFile(ejsPath, {
config,
id: user._id,
name: structureName,
});
this.mailerService.send(user.email, jsonConfig.subject, html);
}
public async getStructureTempUsers(structureId: string): Promise<ITempUser[]> {
.find({ structuresLink: new Types.ObjectId(structureId) })
.select('email updatedAt')
.exec();
}
public async removeFromStructureLinked(userEmail: string, idStructure: string): Promise<Types.ObjectId[]> {
const user = await this.findOne(userEmail);
this.logger.debug(`find user : ${JSON.stringify(user)}`);
if (!user) {
throw new HttpException('Invalid temp user', HttpStatus.NOT_FOUND);
}
if (!user.structuresLink.includes(new Types.ObjectId(idStructure))) {
throw new HttpException("Temp user doesn't belong to this structure", HttpStatus.NOT_FOUND);
}

Marlène SIMONDANT
committed
// Remove the specified structureId from the user's structuresLink
user.structuresLink = user.structuresLink.filter((structureId) => {
return !structureId.equals(idStructure);
});

Marlène SIMONDANT
committed
if (user.structuresLink.length === 0) {
// If there are no more structures linked, delete the user document
await this.tempUserModel.findByIdAndDelete(user._id).exec();
} else {
// Save the updated user if there are remaining structures
await user.save();
}
return user.structuresLink;