Skip to content
Snippets Groups Projects
onlineMediation.service.ts 2.52 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
    import { InjectModel } from '@nestjs/mongoose';
    
    import { Cron, CronExpression } from '@nestjs/schedule';
    
    import { Model } from 'mongoose';
    
    import { ConfigurationService } from '../configuration/configuration.service';
    import { MailerService } from '../mailer/mailer.service';
    
    import { OnlineMediationDto } from './dto/onlineMediation.dto';
    import { IOnlineMediation } from './interfaces/onlineMediation.interface';
    import { OnlineMediation, OnlineMediationDocument } from './onlineMediation.schema';
    
    import * as ejs from 'ejs';
    
    @Injectable()
    export class OnlineMediationService {
      private readonly logger = new Logger(OnlineMediationService.name);
    
    
      constructor(
        @InjectModel(OnlineMediation.name) private OnlineMediationModel: Model<OnlineMediationDocument>,
        private configurationService: ConfigurationService,
        private readonly mailerService: MailerService
      ) {}
    
    
      public async create(newMediation: OnlineMediationDto): Promise<IOnlineMediation> {
        try {
    
          newMediation.surname = newMediation.surname.toUpperCase();
    
          return await this.OnlineMediationModel.create(newMediation);
        } catch (err) {
          this.logger.error(`Creation Error : ${err}`);
          throw new HttpException('Creation Error', HttpStatus.BAD_REQUEST);
        }
      }
    
      public async getAll(): Promise<IOnlineMediation[]> {
        return this.OnlineMediationModel.find().sort({ NamedNodeMap: 1 }).exec();
      }
    
    
      @Cron(CronExpression.EVERY_DAY_AT_11PM)
      public async sendMailAndResetDb(): Promise<{ deletedCount?: number }> {
        this.logger.debug('sendMailAndResetDb');
        const docs = await this.getAll();
        const isProd = this.configurationService.isProdConf();
        //To test it locally, comment the isProd condition, change the mail receiver and edit cron frequency
        if (docs.length) {
          if (isProd) {
            //send Mail
            const config = this.mailerService.config;
            const ejsPath = this.mailerService.getTemplateLocation(config.templates.sosTechEMail.ejs);
            const jsonConfig = this.mailerService.loadJsonConfig(config.templates.sosTechEMail.json);
            this.logger.debug(`sendMaildetails: ${docs}`);
    
            const html = await ejs.renderFile(ejsPath, {
              config,
              demands: docs,
            });
            this.mailerService.send(process.env.MAIL_SOSTECH, jsonConfig.subject, html);
          }
          //reset docs
          this.logger.debug('deletedocs');
    
          return this.OnlineMediationModel.deleteMany({ _id: { $in: docs.map((doc) => doc._id) } }).exec();