Skip to content

Commit

Permalink
Implement Application Completion Workflow with Certificate Generation…
Browse files Browse the repository at this point in the history
… and Email Notification (#130)

Co-authored-by: Dileepa Mabulage <[email protected]>
  • Loading branch information
mayura-andrew and dileepainivossl authored Jul 31, 2024
1 parent c1092f4 commit 21df4b8
Show file tree
Hide file tree
Showing 13 changed files with 158 additions and 44 deletions.
65 changes: 50 additions & 15 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"passport-google-oauth20": "^2.0.0",
"passport-jwt": "^4.0.1",
"passport-linkedin-oauth2": "github:auth0/passport-linkedin-oauth2#v3.0.0",
"pdf-lib": "^1.17.1",
"pg": "^8.10.0",
"reflect-metadata": "^0.1.13",
"ts-node": "^10.9.1",
Expand All @@ -61,7 +62,6 @@
"@types/pg": "^8.10.1",
"@types/prettier": "^2.7.2",
"@types/supertest": "^2.0.12",
"@types/uuid": "^9.0.2",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.59.5",
"eslint": "^8.46.0",
Expand Down
Binary file added src/certificates/certificate_template.pdf
Binary file not shown.
4 changes: 2 additions & 2 deletions src/entities/baseEntity.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { randomUUID } from 'crypto'
import {
BeforeInsert,
BeforeUpdate,
Column,
PrimaryGeneratedColumn
} from 'typeorm'
import { v4 as uuidv4 } from 'uuid'

class BaseEntity {
@PrimaryGeneratedColumn('uuid')
Expand All @@ -28,7 +28,7 @@ class BaseEntity {
@BeforeInsert()
async generateUuid(): Promise<void> {
if (!this.uuid) {
this.uuid = uuidv4()
this.uuid = randomUUID()
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/entities/mentee.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Mentor from './mentor.entity'
import profileEntity from './profile.entity'
import { ApplicationStatus, StatusUpdatedBy } from '../enums'
import BaseEntity from './baseEntity'
import { UUID } from 'typeorm/driver/mongodb/bson.typings'

@Entity('mentee')
class Mentee extends BaseEntity {
Expand All @@ -22,8 +23,8 @@ class Mentee extends BaseEntity {
@Column({ type: 'json' })
application: Record<string, unknown>

@Column({ type: 'bigint', nullable: true, default: null })
certificate_id!: bigint
@Column({ type: 'uuid', nullable: true, default: null })
certificate_id!: UUID

@Column({ default: null, nullable: true })
journal!: string
Expand Down
3 changes: 2 additions & 1 deletion src/enums/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ export enum EmailStatusTypes {
export enum ApplicationStatus {
PENDING = 'pending',
REJECTED = 'rejected',
APPROVED = 'approved'
APPROVED = 'approved',
COMPLETED = 'completed'
}

export enum StatusUpdatedBy {
Expand Down
6 changes: 4 additions & 2 deletions src/services/admin/email.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ const transporter = nodemailer.createTransport({
export const sendEmail = async (
to: string,
subject: string,
message: string
message: string,
attachments?: Array<{ filename: string; path: string }>
): Promise<{
statusCode: number
message: string
Expand All @@ -35,7 +36,8 @@ export const sendEmail = async (
from: `"Sustainable Education Foundation" <${SMTP_MAIL}>`,
to,
subject,
html
html,
attachments
})

const email = new Email(to, subject, message, EmailStatusTypes.SENT)
Expand Down
40 changes: 40 additions & 0 deletions src/services/admin/generateCertificate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { PDFDocument, rgb } from 'pdf-lib'
import fs from 'fs'

export async function generateCertificate(
menteeName: string,
sourcePdfPath: string,
outputPath: string
): Promise<string> {
try {
const existingPdfBytes = fs.readFileSync(sourcePdfPath)
const pdfDoc = await PDFDocument.load(existingPdfBytes)
const page = pdfDoc.getPage(0)
const fontSize = 24
const datezFontSize = 18

page.drawText(menteeName, {
x: 66,
y: page.getHeight() - 220,
size: fontSize,
color: rgb(0, 0, 0)
})

const issueDate = new Date().toLocaleDateString()

page.drawText(issueDate, {
x: 160,
y: page.getHeight() - 476,
size: datezFontSize,
color: rgb(0, 0, 0)
})

const pdfBytes = await pdfDoc.save()

fs.writeFileSync(outputPath, pdfBytes)
return outputPath
} catch (error) {
console.error('Failed to modify the PDF:', error)
throw error
}
}
32 changes: 17 additions & 15 deletions src/services/admin/mentee.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,23 @@ export const updateStatus = async (
profile: {
uuid: profileUuid
}
}
},
relations: ['mentor']
})

const menteeName =
mentee.application.firstName + ' ' + mentee.application.lastName

const content = await getEmailContent('mentee', state, menteeName)

if (content) {
await sendEmail(
mentee.application.email as string,
content.subject,
content.message,
content.attachment
)
}
// Handle Approve status
if (approvedApplications && state === 'approved') {
return {
Expand All @@ -126,22 +140,10 @@ export const updateStatus = async (
{
state,
status_updated_by: statusUpdatedBy,
status_updated_date: new Date()
status_updated_date: new Date(),
certificate_id: content?.uniqueId
}
)
const content = getEmailContent(
'mentee',
state,
mentee.application.firstName as string
)

if (content) {
await sendEmail(
mentee.application.email as string,
content.subject,
content.message
)
}
return {
statusCode: 200,
message: 'Mentee application state successfully updated'
Expand Down
2 changes: 1 addition & 1 deletion src/services/admin/mentor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const updateMentorStatus = async (

await mentorRepository.update({ uuid: mentorId }, { state: status })

const content = getEmailContent(
const content = await getEmailContent(
'mentor',
status,
mentor.application.firstName as string
Expand Down
2 changes: 1 addition & 1 deletion src/services/mentee.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const addMentee = async (

await menteeRepository.save(newMentee)

const content = getEmailContent(
const content = await getEmailContent(
'mentee',
ApplicationStatus.PENDING,
application.firstName as string
Expand Down
2 changes: 1 addition & 1 deletion src/services/mentor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export const createMentor = async (

const savedMentor = await mentorRepository.save(newMentor)

const content = getEmailContent(
const content = await getEmailContent(
'mentor',
ApplicationStatus.PENDING,
application.firstName as string
Expand Down
39 changes: 36 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import path from 'path'
import multer from 'multer'
import ejs from 'ejs'
import { ApplicationStatus } from './enums'

import { generateCertificate } from './services/admin/generateCertificate'
import { randomUUID } from 'crypto'
export const signAndSetCookie = (res: Response, uuid: string): void => {
const token = jwt.sign({ userId: uuid }, JWT_SECRET ?? '')

Expand Down Expand Up @@ -79,11 +80,19 @@ export const loadTemplate = (
})
}

export const getEmailContent = (
export const getEmailContent = async (
type: 'mentor' | 'mentee',
status: ApplicationStatus,
name: string
): { subject: string; message: string } | undefined => {
): Promise<
| {
subject: string
message: string
attachment?: Array<{ filename: string; path: string }>
uniqueId?: string
}
| undefined
> => {
if (type === 'mentor') {
switch (status) {
case ApplicationStatus.PENDING:
Expand Down Expand Up @@ -166,6 +175,30 @@ export const getEmailContent = (
We do offer the possibility for you to apply again next time if you meet the eligibility criteria. We invite you to stay engaged with us by attending our events, reaching out to our admissions team, and taking advantage of any opportunities to connect with our current students and alumni.<br /><br />
Thank you again for considering our program and for the time you invested in your application. We wish you all the best in your future endeavours.`
}
case ApplicationStatus.COMPLETED: {
const uniqueId = randomUUID()
const pdfFileName = await generateCertificate(
name,
'./src/certificates/certificate_template.pdf',
`./src/certificates/mentee/${uniqueId}_certificate.pdf`
)
return {
subject: 'Congratulations! You have completed ScholarX',
message: `Dear ${name},<br /><br />
We are delighted to inform you that you have successfully completed the ScholarX program. We extend our heartfelt congratulations to you!<br /><br />
We are proud of your dedication, hard work, and commitment to the program. You have demonstrated exceptional talent, and we are confident that you will go on to achieve great success in your academic and professional pursuits.<br /><br />
To commemorate your achievement, we have attached your certificate of completion. Please download and save the certificate for your records.<br /><br />
We look forward to seeing the unique perspective and insights you will bring to the program. We believe that you will flourish in this year's edition of ScholarX, and we are thrilled to be a part of your academic or professional journey.<br /><br />
Once again, congratulations on your completion! We cannot wait to see the great things you will achieve in the future.`,
attachment: [
{
filename: `${name}_certificate.pdf`,
path: pdfFileName
}
],
uniqueId
}
}
default:
return undefined
}
Expand Down

0 comments on commit 21df4b8

Please sign in to comment.