Skip to content

Commit

Permalink
Task 13 and 16 michael (#18)
Browse files Browse the repository at this point in the history
* created new photos folder with email footnote and created emailrequestcreated sendgrid function

* adding getTotalBoxesDelivered function for Wix live update

* fixed controller function to return a json with count as a var rather than just an int

* encoded image as 64bit string but doesn't work

* added sendgrid emails for all the emails that BoB wanted

* added email to chapter after birthday request created

---------

Co-authored-by: kygchng <[email protected]>
  • Loading branch information
michaelfenggg and kygchng authored Jan 20, 2025
1 parent 5dc470e commit 970b830
Show file tree
Hide file tree
Showing 8 changed files with 266 additions and 11 deletions.
Binary file added .DS_Store
Binary file not shown.
Binary file added server/.DS_Store
Binary file not shown.
Binary file added server/photos/email_footnote.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions server/photos/email_footnote.txt

Large diffs are not rendered by default.

95 changes: 86 additions & 9 deletions server/src/controllers/birthdayRequest.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,18 @@ import {
getRequestById,
deleteRequestByID,
createBirthdayRequestByID,
getAllBoxesDelivered,
getMonthlyOverviewByDate,
} from '../services/birthdayRequest.service.ts';
import { getUserById } from '../services/user.service.ts';
import {
emailRequestUpdate,
emailRequestDelete,
emailRequestCreate,
emailRequestApproved,
emailRequestDelivered,
emailRequestDenied,
emailChapterRequestCreate,
} from '../services/mail.service.ts';
import {
ChildGender,
Expand Down Expand Up @@ -47,6 +53,20 @@ const getAllRequests = async (
);
};

const getTotalBoxesDelivered = async (
req: express.Request,
res: express.Response,
next: express.NextFunction,
) => {
return getAllBoxesDelivered()
.then((countDelivered) => {
res.status(StatusCode.OK).json({ count: countDelivered });
})
.catch((e) => {
next(ApiError.internal('Unable to get total number of delivered boxes'));
});
};

const updateRequestStatus = async (
req: express.Request,
res: express.Response,
Expand Down Expand Up @@ -87,7 +107,23 @@ const updateRequestStatus = async (
return (
updateRequestStatusByID(id, updatedValue)
.then(() => {
emailRequestUpdate(agencyEmail, updatedValue, request.childName)
let emailFunction;
switch (updatedValue) {
case 'Approved':
emailFunction = emailRequestApproved;
break;
case 'Delivered':
emailFunction = emailRequestDelivered;
break;
case 'Denied':
emailFunction = emailRequestDenied;
break;
default:
next(ApiError.internal('Invalid status'));
return;
}
console.log(emailFunction);
emailFunction(agencyEmail, request.childName)
.then(() => {
emailRequestUpdate(chapterEmail, updatedValue, request.childName)
.then(() =>
Expand All @@ -103,10 +139,10 @@ const updateRequestStatus = async (
next(ApiError.internal('Failed to send agency update email.'));
});
})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.catch((e) => {
next(ApiError.internal('Unable to retrieve all requests'));
})

);
};

Expand Down Expand Up @@ -201,14 +237,31 @@ const createRequest = async (
next(ApiError.notFound(`chapterId does not exist or is invalid`));
return;
}
if (!deadlineDate || !(deadlineDate instanceof Date)) {
next(ApiError.notFound(`deadlineDate does not exist or is invalid`));
return;

if (deadlineDate !== undefined && deadlineDate !== null) {
try {
req.body.deadlineDate = new Date(deadlineDate);
if (isNaN(req.body.deadlineDate.getTime())) {
throw new Error('Invalid date');
}
} catch (e) {
next(ApiError.notFound(`deadlineDate must be a valid date string, null, or undefined`));
return;
}
}
if (!childBirthday || !(childBirthday instanceof Date)) {
next(ApiError.notFound(`childBirthday does not exist or is invalid`));
return;

if (childBirthday !== undefined && childBirthday !== null) {
try {
req.body.childBirthday = new Date(childBirthday);
if (isNaN(req.body.childBirthday.getTime())) {
throw new Error('Invalid date');
}
} catch (e) {
next(ApiError.notFound(`childBirthday must be a valid date string, null, or undefined`));
return;
}
}

if (!childName || typeof childName !== 'string') {
next(ApiError.notFound(`childName does not exist or is invalid`));
return;
Expand Down Expand Up @@ -307,8 +360,31 @@ const createRequest = async (
agreeFeedback,
agreeLiability,
});
res.sendStatus(StatusCode.CREATED).json(birthdayRequest);

// Get chapter email
const chapter = await getChapterById(chapterId);
if (!chapter) {
next(ApiError.notFound(`Chapter does not exist`));
return;
}

// Send emails to both agency worker and chapter
Promise.all([
emailRequestCreate(agencyWorkerEmail, childName),
emailChapterRequestCreate(chapter.email, childName)
])
.then(() => {
res.status(StatusCode.CREATED).send({
message: `Request created and emails have been sent.`,
birthdayRequest,
});
})
.catch((err) => {
console.log(err);
next(ApiError.internal('Failed to send confirmation emails.'));
});
} catch (err) {
console.log(err)
next(ApiError.internal('Unable to register user.'));
}
};
Expand Down Expand Up @@ -340,5 +416,6 @@ export {
updateRequestStatus,
deleteRequest,
createRequest,
getTotalBoxesDelivered
getMonthlyOverview,
};
10 changes: 8 additions & 2 deletions server/src/routes/birthdayRequest.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
updateRequestStatus,
deleteRequest,
createRequest,
getTotalBoxesDelivered,
getMonthlyOverview,
} from '../controllers/birthdayRequest.controller.ts';
import { isAuthenticated } from '../controllers/auth.middleware.ts';
Expand All @@ -15,11 +16,16 @@ const router = express.Router();

router.get('/all/:id', isAuthenticated, isAdmin, getAllRequests);

router.put('/updatestatus/:id', isAuthenticated, isAdmin, updateRequestStatus);
router.get('/totalboxesdelivered', getTotalBoxesDelivered);
//isAuthenticated, isAdmin,

router.put('/updatestatus/:id', updateRequestStatus);
//isAuthenticated, isAdmin,

router.delete('/deleterequest/:id', isAuthenticated, isAdmin, deleteRequest);

router.post('/createrequest', isAuthenticated, isAdmin, createRequest);
router.post('/createrequest', createRequest);
//isAuthenticated, isAdmin,

router.get('/monthly-overview', isAuthenticated, isAdmin, getMonthlyOverview);

Expand Down
7 changes: 7 additions & 0 deletions server/src/services/birthdayRequest.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,17 @@ const getAllRequestsByID = async (id: string) => {
return requestsList;
};

const getAllBoxesDelivered = async () => {
const countDelivered = await BirthdayRequest.countDocuments({ status: 'Delivered' }).exec();
return countDelivered;
};

const updateRequestStatusByID = async (id: string, updatedValue: string) => {
const updatedRequest = await BirthdayRequest.findByIdAndUpdate(id, [
{ $set: { status: updatedValue } },
// { $eq: [updatedValue, '$status'] }
]).exec();
//console.log(updatedRequest)
return updatedRequest;
};

Expand Down Expand Up @@ -253,5 +259,6 @@ export {
getRequestById,
deleteRequestByID,
createBirthdayRequestByID,
getAllBoxesDelivered,
getMonthlyOverviewByDate,
};
164 changes: 164 additions & 0 deletions server/src/services/mail.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
*/
import 'dotenv/config';
import SGmail, { MailDataRequired } from '@sendgrid/mail';
// @ts-ignore
import footnote from '../../photos/email_footnote.txt';

const appName = 'Boilerplate'; // Replace with a relevant project name
const senderName = 'Hack4Impact UPenn'; // Replace with a relevant project sender
Expand Down Expand Up @@ -128,10 +130,172 @@ const emailRequestDelete = async (email: string, childName: string) => {
await SGmail.send(mailSettings);
};

const emailRequestCreate = async (email: string, childName: string) => {
const mailSettings: MailDataRequired = {
from: {
email: process.env.SENDGRID_EMAIL_ADDRESS || '[email protected]',
name: 'Box of Balloons, Inc.',
},
to: email,
subject: 'Box of Balloons Request Received!',
html: `
<p>Hello,</p>
<p>Thank you for your request. Box of Balloons has received your request and you will receive a
response when your request is either approved or denied by your local chapter leader.</p>
<p>If you have any specific questions in the meantime, please reach out to your local chapter by
finding their contact information <a href="https://www.boxofballoons.org/where-are-we-1">here</a>.</p>
<p>We appreciate your patience as all our chapters are run 100% by volunteers so response time,
while often quick, may sometimes be delayed.</p>
<p>Thank you,</p>
<p>Box of Balloons, Inc. - Automated response</p>
`,
};

//<img src='data:image/png;base64,${footnote}' alt="Box of Balloons Logo" style="max-width: 100%; height: auto;"/>

// Send the email and propagate the error up if one exists
await SGmail.send(mailSettings);
};

const emailRequestApproved = async (email: string, childName: string) => {
const mailSettings: MailDataRequired = {
from: {
email: process.env.SENDGRID_EMAIL_ADDRESS || '[email protected]',
name: 'Box of Balloons, Inc.',
},
to: email,
subject: 'Box of Balloons Request Approved!',
html: `
<p>Hello,</p>
<p>Congratulations, let the celebrations begin!! Your request for a birthday box has
been approved by your local volunteer-led chapter of Box of Balloons, Inc.</p>
<p>Please watch out for an email or phone call from your local volunteer chapter
leader with instructions on how your box will be delivered.</p>
<p>If you have any specific questions in the meantime, please reach out to your local chapter by
finding their contact information <a href="https://www.boxofballoons.org/where-are-we-1">here</a>.</p>
<p>Thank you,</p>
<p>Box of Balloons, Inc. - Automated response</p>
`,
};
await SGmail.send(mailSettings);
};

const emailRequestDenied = async (email: string, childName: string) => {
const mailSettings: MailDataRequired = {
from: {
email: process.env.SENDGRID_EMAIL_ADDRESS || '[email protected]',
name: 'Box of Balloons, Inc.',
},
to: email,
subject: 'Box of Balloons Request Denied',
html: `
<p>Hello,</p>
<p>Thank you for your request. Unfortunately, your local chapter is unable to fulfill your request
for a birthday box at this time.</p>
<p>As an organization run 100% by volunteers, our ability to accept every request submitted is sometimes
limited by availability and we apologize for the inconvenience this may cause to the families you serve.</p>
<p>We encourage you to reach out to your chapter leaders to explore future opportunities by emailing them
directly. You may find their contact information <a href="https://www.boxofballoons.org/where-are-we-1">here</a>.</p>
<p>Regretfully,</p>
<p>Box of Balloons, Inc. - Automated response</p>
`,
};
await SGmail.send(mailSettings);
};

const emailRequestDelivered = async (email: string, childName: string) => {
const mailSettings: MailDataRequired = {
from: {
email: process.env.SENDGRID_EMAIL_ADDRESS || '[email protected]',
name: 'Box of Balloons, Inc.',
},
to: email,
subject: 'Box of Balloons Request Delivered!',
html: `
<p>Cue the Confetti!</p>
<p>The box you have requested on behalf of the families you serve has been delivered! Our goal is to
ensure every child feels celebrated on their birthday and we are so thrilled to be able to provide our
services to the families your agency helps.</p>
<p>As an organization run mostly by volunteers, while our overhead is small compared to other larger
nonprofits, we still have overhead to cover the costs of running a nonprofit. To help us ensure each
birthday is happy and every child is celebrated we invite you to consider helping us spread more joy
to organizations like yours and the families you serve.</p>
<p>Please consider making a donation today, no amount is too small - <a href="https://boxofballoons.networkforgood.com/">Donate Now</a></p>
<p>Other ways to contribute to our mission is by encouraging the family we provided a birthday box to, to send us an email or write a letter
sharing how impactful our service was to them and their child/children. Letters, thank you cards, and especially pictures can be a catalyst
in supporting our mission.</p>
<p>If it is safe to do so and the family assisted is comfortable doing so, we ask that these small but large displays of gratitude be emailed
to: <a href="[email protected]">[email protected]</a> or mailed to P.O. Box 28, Sun Prairie WI. 53590.</p>
<p>Please note any pictures received will be used to advance our fundraising efforts, if a child's identity needs to be hidden please note so
in the email or letter and an emoji will be used to protect the family and child/ren served.</p>
<p>Thank you again for everything you do to make our community a better place for children and families in need. We are in this together!</p>
<p>Here to serve,</p>
<p>Box of Balloons, Inc. Volunteer Team</p>
`,
};

//<img src='data:image/png;base64,${footnote}' alt="Box of Balloons Logo" style="max-width: 100%; height: auto;"/>

// Send the email and propagate the error up if one exists
await SGmail.send(mailSettings);
};

const emailChapterRequestCreate = async (email: string, childName: string) => {
const mailSettings: MailDataRequired = {
from: {
email: process.env.SENDGRID_EMAIL_ADDRESS || '[email protected]',
name: 'Box of Balloons, Inc.',
},
to: email,
subject: 'New Birthday Box Request Received',
html: `
<p>Hello,</p>
<p>A new birthday box request has been submitted for ${childName}. Please review this request
in your dashboard and either approve or deny it.</p>
<p>Thank you for your dedication to making birthdays special!</p>
<p>Box of Balloons, Inc. - Automated response</p>
`,
};

await SGmail.send(mailSettings);
};

export {
emailVerificationLink,
emailResetPasswordLink,
emailInviteLink,
emailRequestUpdate,
emailRequestDelete,
emailRequestCreate,
emailRequestApproved,
emailRequestDenied,
emailRequestDelivered,
emailChapterRequestCreate,
};

0 comments on commit 970b830

Please sign in to comment.