forked from Code-4-Community/scaffolding
-
Notifications
You must be signed in to change notification settings - Fork 0
SSF-233 Pantry Confirm Delivery Email #194
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
Open
Juwang110
wants to merge
4
commits into
main
Choose a base branch
from
jw/ssf-233-pantry-confirm-delivery-email
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -34,7 +34,8 @@ import { DataSource, EntityManager, In } from 'typeorm'; | |
| import { EmailsService } from '../emails/email.service'; | ||
| import { Allocation } from '../allocations/allocations.entity'; | ||
| import { mock } from 'jest-mock-extended'; | ||
| import { emailTemplates } from '../emails/emailTemplates'; | ||
| import { emailTemplates, EMAIL_REDIRECT_URL } from '../emails/emailTemplates'; | ||
| import { ApplicationStatus } from '../shared/types'; | ||
|
|
||
| // Set 1 minute timeout for async DB operations | ||
| jest.setTimeout(60000); | ||
|
|
@@ -1747,4 +1748,175 @@ ${request.pantry.shipmentAddressCity}, ${request.pantry.shipmentAddressState} ${ | |
| warnSpy.mockRestore(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('sendConfirmDeliveryReminders', () => { | ||
| // Orders eligible for a reminder: shipped, approved pantry, and shipped at | ||
| // least a week ago (matching the service query). | ||
| const eligibleOrders = async (): Promise<Order[]> => | ||
| testDataSource | ||
| .getRepository(Order) | ||
| .createQueryBuilder('order') | ||
| .leftJoinAndSelect('order.request', 'request') | ||
| .leftJoinAndSelect('request.pantry', 'pantry') | ||
| .leftJoinAndSelect('pantry.pantryUser', 'pantryUser') | ||
| .leftJoinAndSelect('order.assignee', 'assignee') | ||
| .leftJoinAndSelect('order.foodManufacturer', 'foodManufacturer') | ||
| .where('order.status = :status', { status: OrderStatus.SHIPPED }) | ||
| .andWhere('pantry.status = :pantryStatus', { | ||
| pantryStatus: ApplicationStatus.APPROVED, | ||
| }) | ||
| .andWhere("order.shippedAt <= NOW() - INTERVAL '7 days'") | ||
| .getMany(); | ||
|
|
||
| const expectedMessageFor = (order: Order) => | ||
| emailTemplates.pantryConfirmDeliveryReminder({ | ||
| pantryName: order.request.pantry.pantryName, | ||
| fmName: order.foodManufacturer.foodManufacturerName, | ||
| confirmDeliveryLink: `${EMAIL_REDIRECT_URL}/pantry-order-management?orderId=${order.orderId}&action=confirm-delivery`, | ||
| volunteerName: `${order.assignee.firstName} ${order.assignee.lastName}`, | ||
| volunteerEmail: order.assignee.email, | ||
| }); | ||
|
|
||
| it('logs a warning and sends no emails when there are no unconfirmed deliveries', async () => { | ||
| await testDataSource.query( | ||
| `UPDATE orders SET status = $1 WHERE status = $2`, | ||
| [OrderStatus.DELIVERED, OrderStatus.SHIPPED], | ||
| ); | ||
| const logSpy = jest.spyOn(service['logger'], 'log'); | ||
|
|
||
| await service.sendConfirmDeliveryReminders(); | ||
|
|
||
| expect(logSpy).toHaveBeenCalledWith( | ||
| expect.stringContaining( | ||
| 'No pantries with unconfirmed deliveries, skipping email sending.', | ||
| ), | ||
| ); | ||
| expect(mockEmailsService.sendEmails).not.toHaveBeenCalled(); | ||
|
|
||
| logSpy.mockRestore(); | ||
| }); | ||
|
|
||
| it('sends one personalized reminder per unconfirmed order', async () => { | ||
| const warnSpy = jest.spyOn(service['logger'], 'warn'); | ||
| const orders = await eligibleOrders(); | ||
| expect(orders.length).toBeGreaterThan(0); | ||
|
|
||
| await service.sendConfirmDeliveryReminders(); | ||
|
|
||
| expect(mockEmailsService.sendEmails).toHaveBeenCalledTimes(orders.length); | ||
| for (const order of orders) { | ||
| const message = expectedMessageFor(order); | ||
| expect(mockEmailsService.sendEmails).toHaveBeenCalledWith({ | ||
| toEmail: order.request.pantry.pantryUser.email, | ||
| subject: message.subject, | ||
| bodyHtml: message.bodyHTML, | ||
| }); | ||
| } | ||
| expect(warnSpy).not.toHaveBeenCalled(); | ||
|
|
||
| warnSpy.mockRestore(); | ||
| }); | ||
|
|
||
| it('sends a separate reminder for each unconfirmed order, even within the same pantry', async () => { | ||
| const orderRepo = testDataSource.getRepository(Order); | ||
| const existingShippedOrder = await orderRepo.findOne({ | ||
| where: { status: OrderStatus.SHIPPED }, | ||
| }); | ||
| if (!existingShippedOrder) | ||
| throw new Error('Missing existingShippedOrder test object'); | ||
|
|
||
| // Add a second shipped order to the same request | ||
| const secondOrder = orderRepo.create({ | ||
| requestId: existingShippedOrder.requestId, | ||
| foodManufacturerId: existingShippedOrder.foodManufacturerId, | ||
| assigneeId: existingShippedOrder.assigneeId, | ||
| status: OrderStatus.SHIPPED, | ||
| shippedAt: new Date('2024-02-03T08:00:00Z'), | ||
| }); | ||
| await orderRepo.save(secondOrder); | ||
|
|
||
| await service.sendConfirmDeliveryReminders(); | ||
|
|
||
| const samePantryOrders = (await eligibleOrders()).filter( | ||
| (o) => o.requestId === existingShippedOrder.requestId, | ||
| ); | ||
| expect(samePantryOrders.length).toBe(2); | ||
|
|
||
| const sentForSecondOrder = samePantryOrders.find( | ||
| (o) => o.orderId === secondOrder.orderId, | ||
| )!; | ||
| const message = expectedMessageFor(sentForSecondOrder); | ||
| expect(mockEmailsService.sendEmails).toHaveBeenCalledWith({ | ||
| toEmail: sentForSecondOrder.request.pantry.pantryUser.email, | ||
| subject: message.subject, | ||
| bodyHtml: message.bodyHTML, | ||
| }); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can we also confirm that the mockEmailsService is still called multiple times? |
||
| }); | ||
|
|
||
| it('does not send a reminder for an order shipped less than a week ago', async () => { | ||
| const orderRepo = testDataSource.getRepository(Order); | ||
|
|
||
| await testDataSource.query( | ||
| `UPDATE orders SET status = $1 WHERE status = $2`, | ||
| [OrderStatus.DELIVERED, OrderStatus.SHIPPED], | ||
| ); | ||
|
|
||
| const template = await orderRepo.findOne({ | ||
| where: { status: OrderStatus.DELIVERED }, | ||
| }); | ||
| if (!template) throw new Error('Missing order template'); | ||
|
|
||
| const recentOrder = orderRepo.create({ | ||
| requestId: template.requestId, | ||
| foodManufacturerId: template.foodManufacturerId, | ||
| assigneeId: template.assigneeId, | ||
| status: OrderStatus.SHIPPED, | ||
| shippedAt: new Date(), | ||
| }); | ||
| await orderRepo.save(recentOrder); | ||
|
|
||
| await service.sendConfirmDeliveryReminders(); | ||
|
|
||
| expect(mockEmailsService.sendEmails).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('only sends reminders for orders that are SHIPPED', async () => { | ||
| const orders = await eligibleOrders(); | ||
| expect(orders.length).toBeGreaterThan(0); | ||
|
|
||
| await service.sendConfirmDeliveryReminders(); | ||
|
|
||
| expect(mockEmailsService.sendEmails).toHaveBeenCalledTimes(orders.length); | ||
|
|
||
| const orderRepo = testDataSource.getRepository(Order); | ||
| // Pulling id out of sent email to assert it is shipped. | ||
| for (const [{ bodyHtml }] of mockEmailsService.sendEmails.mock.calls) { | ||
| const match = bodyHtml.match(/orderId=(\d+)/); | ||
| expect(match).not.toBeNull(); | ||
|
|
||
| const orderId = Number(match![1]); | ||
| const order = await orderRepo.findOneBy({ orderId }); | ||
| expect(order).not.toBeNull(); | ||
| expect(order!.status).toEqual(OrderStatus.SHIPPED); | ||
| } | ||
| }); | ||
|
|
||
| it('logs a warning and continues when sending a reminder fails', async () => { | ||
| const warnSpy = jest.spyOn(service['logger'], 'warn'); | ||
| mockEmailsService.sendEmails.mockRejectedValueOnce( | ||
| new Error('SES failure'), | ||
| ); | ||
|
|
||
| await expect( | ||
| service.sendConfirmDeliveryReminders(), | ||
| ).resolves.toBeUndefined(); | ||
|
|
||
| expect(mockEmailsService.sendEmails).toHaveBeenCalled(); | ||
| expect(warnSpy).toHaveBeenCalledWith( | ||
| expect.stringContaining('Failed to send confirm delivery reminder to'), | ||
| ); | ||
|
|
||
| warnSpy.mockRestore(); | ||
| }); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| import { Injectable, Logger } from '@nestjs/common'; | ||
| import { Cron } from '@nestjs/schedule'; | ||
| import { OrdersService } from './order.service'; | ||
|
|
||
| @Injectable() | ||
| export class OrdersSchedulerService { | ||
| private readonly logger = new Logger(OrdersSchedulerService.name); | ||
|
|
||
| constructor(private readonly ordersService: OrdersService) {} | ||
|
|
||
| // 12 PM on every Monday | ||
| @Cron('0 0 12 * * 1', { timeZone: 'America/New_York' }) | ||
| async handleWeeklyConfirmDeliveryReminder() { | ||
| this.logger.log('Running weekly confirm-delivery reminder cron job'); | ||
| await this.ordersService.sendConfirmDeliveryReminders(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.