Files
cedetec_api_nest/src/email/email.service.ts
T

120 lines
4.1 KiB
TypeScript

import { HttpException, HttpStatus, Inject, Injectable, Res, UploadedFile } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm';
import * as nodemailer from 'nodemailer';
import { EventosService } from 'src/eventos/eventos.service';
import { Participante } from 'src/participante/participante.entity';
import { Repository } from 'typeorm';
import { EmailDto } from './dto/emailDto.dto';
import * as xlsx from 'xlsx';
import * as pdfMake from 'pdfmake/build/pdfmake';
import * as pdfFonts from 'pdfmake/build/vfs_fonts';
/* import * as PDFDocument from 'pdfkit'; */
import * as fs from 'fs';
import * as path from 'path';
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
@Injectable()
export class EmailService {
private transporter;
constructor(
@InjectRepository(Participante)
private participanteRepository: Repository<Participante>,
private configService: ConfigService,
) {
this.transporter = nodemailer.createTransport({
service: this.configService.get('NODEMAILER_SERVICE'),
auth: {
user: this.configService.get<string>('NODEMAILER_USER'),
pass: this.configService.get<string>('NODEMAILER_PASWORD'),
},
});
}
async sendEmail(id: number, message: EmailDto) {
const participantes = await this.getEmailDeParticipantes(id);
participantes.map((res) => {
const emailDestinatario = res.email;
this.transporter.sendMail({
to: emailDestinatario,
subject: message.subject,
text: message.text,
});
/*console.log("Email enviado a: ", res)*/
});
}
async getEmailDeParticipantes(idEvento: number) {
const participantes = await this.participanteRepository
.createQueryBuilder('participante')
.innerJoin('participante.eventosParticipante', 'eventoParticipante')
.innerJoin('eventoParticipante.evento', 'evento')
.where('evento.id_evento = :idEvento', { idEvento })
.select(['participante.email'])
.getMany();
return participantes;
}
async sendConstancias(file, nombreEvento) {
/* console.log(file) */
const workbook = xlsx.read(file.buffer);
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const data = xlsx.utils.sheet_to_json(worksheet);
for (const row of data as Row[]) {
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage();
page.setSize(792, 612);
const font = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
const fontSize = 30;
const text = 'Constancia de asistencia';
const textWidth = font.widthOfTextAtSize(text, fontSize);
const textHeight = font.heightAtSize(fontSize);
page.drawText(text, {
x: (page.getWidth() - textWidth) / 2,
y: (page.getHeight() - textHeight) / 2,
size: fontSize,
font: font,
color: rgb(0/255, 0/255, 0/255),
});
const { width, height } = page.getSize();
page.drawText(
`Se le otorga la constancia por su asistencia al evento: ${nombreEvento}`,
{
x: 50,
y: height - 50,
size: 12,
font: await pdfDoc.embedFont('Helvetica'),
},
);
page.drawText(
`A ${row['Apellido Paterno']} ${row['Apellido Materno']} ${row.Nombre}`,
{
x: 50,
y: height - 80,
size: 12,
font: await pdfDoc.embedFont('Helvetica'),
},
);
const pdfBytes = await pdfDoc.save();
const attachment = {
filename: `Constancia ${nombreEvento} - ${row.Nombre}_${row['Apellido Paterno']}.pdf`,
content: pdfBytes,
};
/* const blob = new Blob([pdfBytes], { type: 'application/pdf' });
const url = URL.createObjectURL(blob); */
this.transporter.sendMail({
to: row.Email,
subject: `Constancia de asistencia a "${nombreEvento}"`,
text: `¡Un saludo ${row.Nombre}! Aquí está tu constancia de asistencia por el evento "${nombreEvento}". Agradecemos tu asistencia y constancia, esperamos seguir viéndote en eventos futuros.`,
attachments: [attachment],
});
}
}
}