From ec231862879d64babf207493ef63de8d379dee5f Mon Sep 17 00:00:00 2001 From: Danny Miller Date: Mon, 3 Feb 2025 17:33:52 -0500 Subject: [PATCH] fix email subject for when streak expires --- pages/api/internal-jobs/email-digest/index.ts | 3 +- .../api/internal-jobs/email-digest.test.ts | 68 +++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/pages/api/internal-jobs/email-digest/index.ts b/pages/api/internal-jobs/email-digest/index.ts index 3c369947e..59a66629a 100644 --- a/pages/api/internal-jobs/email-digest/index.ts +++ b/pages/api/internal-jobs/email-digest/index.ts @@ -8,6 +8,7 @@ import NotificationType from '@root/constants/notificationType'; import Role from '@root/constants/role'; import queueDiscordWebhook from '@root/helpers/discordWebhook'; import { getGameFromId } from '@root/helpers/getGameIdFromReq'; +import { getStreak } from '@root/lib/cleanUser'; import EmailLog from '@root/models/db/emailLog'; import { EnrichedLevel } from '@root/models/db/level'; import { convert } from 'html-to-text'; @@ -331,7 +332,7 @@ export async function sendEmailDigests(batchId: Types.ObjectId, limit: number) { let dailySubject = 'Levels of the Day - ' + todaysDatePretty; // get max config.calcCurrentStreak for all configs - const maxStreak = user.configs?.reduce((max, config) => Math.max(max, config.calcCurrentStreak || 0), 0); + const maxStreak = user.configs?.reduce((max, config) => Math.max(max, getStreak(config)?.streak || 0), 0); if (maxStreak && maxStreak > 0) { const streakRank = STREAK_RANK_GROUPS[getStreakRankIndex(maxStreak)]; diff --git a/tests/pages/api/internal-jobs/email-digest.test.ts b/tests/pages/api/internal-jobs/email-digest.test.ts index f31b3baa7..910dafb2e 100644 --- a/tests/pages/api/internal-jobs/email-digest.test.ts +++ b/tests/pages/api/internal-jobs/email-digest.test.ts @@ -382,6 +382,74 @@ describe('Email digest', () => { expect(response.failed[EmailType.EMAIL_DIGEST]).toHaveLength(0); }, }); + }, 10000); + + test('Run it with a user who had a streak but it expired', async () => { + // setup + await dbConnect(); + sendMailRefMock.ref = acceptMock; + jest.spyOn(logger, 'error').mockImplementation(() => ({} as Logger)); + jest.spyOn(logger, 'info').mockImplementation(() => ({} as Logger)); + jest.spyOn(logger, 'warn').mockImplementation(() => ({} as Logger)); + + const tomorrow = Date.now() + (1000 * 60 * 60 * 24 ); // Note... Date.now() here is being mocked each time too! + + MockDate.set(tomorrow); + + await Promise.all([ + UserModel.findByIdAndUpdate(TestId.USER, { + ts: Math.floor(Date.now() / 1000) - (30 * 24 * 60 * 60) // Set registration date to 30 days ago so get by all the intro emails + }), + EmailLogModel.deleteMany({ type: EmailType.EMAIL_DIGEST, userId: TestId.USER }), + UserConfigModel.findOneAndUpdate( + { userId: TestId.USER }, + { + calcCurrentStreak: 7, + lastPlayedAt: new Date().getTime() - 1000 * 60 * 60 * 24 * 7, // make the streak expired + emailDigest: EmailDigestSettingType.DAILY + }, + { upsert: true } + ) + ]); + + // Update user config to have a streak + + await testApiHandler({ + pagesHandler: async (_, res) => { + const req: NextApiRequestWrapper = { + gameId: DEFAULT_GAME_ID, + method: 'GET', + query: { + secret: process.env.INTERNAL_JOB_TOKEN_SECRET_EMAILDIGEST + }, + body: {}, + headers: { + 'content-type': 'application/json', + }, + } as unknown as NextApiRequestWrapper; + + await handler(req, res); + }, + test: async ({ fetch }) => { + const res = await fetch(); + const response = await res.json(); + + expect(response.error).toBeUndefined(); + expect(res.status).toBe(200); + + // Check the email logs to verify the subject line includes the streak + const emailLogs = await EmailLogModel.find({ userId: TestId.USER }, {}, { sort: { createdAt: -1 } }); + const latestEmail = emailLogs[0]; + + expect(latestEmail).toBeDefined(); + expect(latestEmail.subject).not.toContain('Keep your streak of 7 days going!'); + expect(latestEmail.state).toBe(EmailState.SENT); + + expect(response.sent[EmailType.EMAIL_DIGEST]).toHaveLength(4); + + expect(response.failed[EmailType.EMAIL_DIGEST]).toHaveLength(0); + }, + }); // Clean up - reset the streak await UserConfigModel.findOneAndUpdate(