Skip to content

Commit

Permalink
fix email subject for when streak expires
Browse files Browse the repository at this point in the history
  • Loading branch information
k2xl committed Feb 3, 2025
1 parent 2c718fc commit ec23186
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 1 deletion.
3 changes: 2 additions & 1 deletion pages/api/internal-jobs/email-digest/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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)];
Expand Down
68 changes: 68 additions & 0 deletions tests/pages/api/internal-jobs/email-digest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit ec23186

Please sign in to comment.