Skip to content
Snippets Groups Projects
Select Git revision
  • 04ccf0b7819edd39aec0f7d6a421c4edb7f041e4
  • dev default protected
  • renovate/ghcr.io-browserless-chromium-2.x
  • 168-pro-connect
  • renovate/major-nest-monorepo
  • renovate/luxon-3.x
  • renovate/gouvfr-anct-timetable-to-osm-opening-hours-2.x
  • renovate/major-typescript-eslint-monorepo
  • renovate/npm-11.x
  • renovate/mysql-9.x
  • renovate/mongo-express-1.x
  • renovate/major-jest-monorepo
  • renovate/tsconfig-paths-4.x
  • renovate/jest-junit-16.x
  • renovate/express-5.x
  • renovate/elastic-elasticsearch-8.x
  • renovate/ghost-5.x
  • renovate/elasticsearch-7.x
  • renovate/devdependencies-(non-major)
  • 722-envsubst-client-side-conf
  • master protected
  • v4.0.3
  • v4.0.1
  • v4.0.0
  • v3.4.3
  • v3.4.2
  • v3.4.1
  • v3.4.0
  • v3.3.1
  • v3.3.0
  • v3.2.0
  • v3.1.0
  • v3.0.1
  • v3.0.0
  • v2.5.0
  • v2.4.2
  • v2.4.1
  • v2.4.0
  • v2.3.2
  • v2.3.1
  • v2.3.0
41 results

temp-user.service.ts

Blame
  • temp-user.service.ts 4.88 KiB
    import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
    import { InjectModel } from '@nestjs/mongoose';
    import * as ejs from 'ejs';
    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);
        return this.findOne(createTempUser.email);
      }
    
      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) {
          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> {
        // Find the user by email
        const userInDb = await this.tempUserModel.findOne({ email: createTempUser.email }).exec();
    
        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);
        }
    
        // Add the new structure to structuresLink
        userInDb.structuresLink.push(createTempUser.structuresLink[0]);
    
        // Save the updated user
        const updatedUser = await userInDb.save();
    
        return updatedUser;
      }
    
      /**
       * 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[]> {
        return this.tempUserModel
          .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);
        }
    
        // Remove the specified structureId from the user's structuresLink
        user.structuresLink = user.structuresLink.filter((structureId) => {
          return !structureId.equals(idStructure);
        });
    
        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;
      }
    }