Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task 13 and 16 michael #18

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.

84 changes: 74 additions & 10 deletions server/src/controllers/birthdayRequest.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,16 @@ import {
getRequestById,
deleteRequestByID,
createBirthdayRequestByID,
getAllBoxesDelivered,
} from '../services/birthdayRequest.service.ts';
import { getChapterById } from '../services/chapter.service.ts';
import {
emailRequestUpdate,
emailRequestDelete,
emailRequestCreate,
emailRequestApproved,
emailRequestDelivered,
emailRequestDenied,
} from '../services/mail.service.ts';
import {
ChildGender,
Expand Down Expand Up @@ -46,6 +51,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 @@ -86,7 +105,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 @@ -102,10 +137,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 @@ -200,14 +235,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 @@ -306,10 +358,22 @@ const createRequest = async (
agreeFeedback,
agreeLiability,
});
res.sendStatus(StatusCode.CREATED).json(birthdayRequest);

emailRequestCreate(agencyWorkerEmail, childName)
.then(() => {
res.status(StatusCode.CREATED).send({
message: `Request created and email has been sent.`,
birthdayRequest,
});
})
.catch((err) => {
console.log(err);
next(ApiError.internal('Failed to send confirmation email.'));
});
} catch (err) {
console.log(err)
next(ApiError.internal('Unable to register user.'));
}
};

export { getAllRequests, updateRequestStatus, deleteRequest, createRequest };
export { getAllRequests, updateRequestStatus, deleteRequest, createRequest, getTotalBoxesDelivered };
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,
} from '../controllers/birthdayRequest.controller.ts';
import { isAuthenticated } from '../controllers/auth.middleware.ts';
import 'dotenv/config';
Expand All @@ -14,10 +15,15 @@ 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,

export default router;
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 @@ -61,4 +67,5 @@ export {
getRequestById,
deleteRequestByID,
createBirthdayRequestByID,
getAllBoxesDelivered,
};
140 changes: 140 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,148 @@ 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);
};

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