import { randomUUID } from 'node:crypto'; import argon2 from 'argon2'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { createServer } from '../src/app.js'; import { db } from '../src/db/knex.js'; import { applyEmailTokens, doctorGreetingName, hasPendingStep, studyProgress } from '../src/services/bulkEmail.js'; import { renderEmail } from '../src/services/emailTemplates.js'; import { seedSurveyDefinition } from '../src/survey/seed.js'; import { truncateTables } from './truncate.js'; const mailState = vi.hoisted(() => ({ send: vi.fn(async () => [{ headers: { 'x-message-id': 'msg-1' } }]), })); vi.mock('@sendgrid/mail', () => ({ default: { setApiKey: vi.fn(), send: (...args) => mailState.send(...args), }, })); const adminEmail = 'bulk-admin@example.com'; const password = 'correct-password'; /** * @param {import('@hapi/hapi').ServerInjectResponse} response */ function sessionCookie(response) { const raw = response.headers['set-cookie']; const header = Array.isArray(raw) ? raw[0] : raw; return header.split(';')[0]; } describe('bulk study email', () => { /** @type {import('@hapi/hapi').Server | undefined} */ let server; afterEach(async () => { await server?.stop(); mailState.send.mockClear(); delete process.env.BULK_EMAIL_ALLOWLIST; delete process.env.MAIL_FORCE_SEND; await truncateTables(); }); it('keeps replaceable tokens in both letters', () => { const invitation = renderEmail('study_invitation', {}); const reminder = renderEmail('study_reminder', {}); expect(invitation.subject).toBe('Extended-Dose-Pack Study - email-Invitation'); expect(invitation.text).toContain('Dear Doctor,'); expect(invitation.text).toContain( 'A professional honorarium of ₹15,000 will be provided upon completion and submission of the questionnaire and execution of an MOU with CREST.', ); expect(invitation.text).toContain('Application Link: {Application link}'); expect(invitation.text).not.toContain('Sandeep'); expect(invitation.text.startsWith('Dear Doctor,')).toBe(true); expect(invitation.text).not.toContain('Study invitation'); expect(invitation.text.endsWith('Pune')).toBe(true); expect(invitation.text).toContain('CREST Team\nChest Research and Training Pvt. Ltd.\nPune'); expect(invitation.html).toContain(`${invitation.text.match(/“Physicians’[^”]+”/)[0]}`); expect(invitation.html).toContain('₹15,000'); expect(invitation.html).toContain('two weeks'); expect(invitation.html).not.toContain('Extended-Dose Pack Study

'); expect(reminder.text.startsWith('Dear Dr {Name},')).toBe(true); expect(reminder.subject).toBe('Reminder Email for Extended-Dose-Pack Study'); expect(reminder.text.indexOf('Dear Dr {Name},')).toBeLessThan( reminder.text.indexOf('Reminder: Extended-Dose-Pack Study'), ); expect(reminder.html).toContain('Reminder: Extended-Dose-Pack Study'); expect(reminder.text.endsWith('Pune')).toBe(true); expect(reminder.text).toContain('CREST Team\nChest Research and Training Pvt. Ltd.\nPune'); expect(reminder.text).toContain('• Login — {Login}'); expect(reminder.text).toContain('• Consent — {Consent}'); expect(reminder.text).toContain('• Agreement — {Agreement}'); expect(reminder.text).toContain('• Approval — {Approval}'); expect(reminder.text).toContain('• Survey — {Survey}'); expect(reminder.text).toContain('Application Link: {Application link}'); expect(reminder.text).toContain( 'Please continue and complete your Extended-Dose Pack Study survey from where you left off.', ); expect(reminder.text).not.toContain('If you have already completed this step, you can ignore this email.'); expect(reminder.text).toContain('Warm regards,'); expect(reminder.text).toContain('CREST Team'); expect(doctorGreetingName('Dr. Sundeep Salvi')).toBe('Sundeep Salvi'); expect( applyEmailTokens('Dear Dr {Name}, Login — {Login}', { hcp_name: 'Dr Asha Rao', steps: { login: 'Completed', consent: 'Pending', agreement: 'Pending', approval: 'Pending', survey: 'Pending', }, }), ).toBe('Dear Dr Asha Rao, Login — Completed'); expect(applyEmailTokens('Please continue as written.', { hcp_name: 'Dr Asha Rao' })).toBe( 'Please continue as written.', ); expect(applyEmailTokens('Dear Dr {Name}, {Note}', { hcp_name: '' })).toBe( 'Dear Dr {Name}, {Note}', ); }); it('maps login, consent, agreement, approval, and survey', () => { expect( studyProgress({ lastLoginAt: null, consentSubmittedAt: null, applicationStatus: null, surveyStatus: null, }), ).toEqual({ login: 'Pending', consent: 'Pending', agreement: 'Pending', approval: 'Pending', survey: 'Pending', }); expect( studyProgress({ lastLoginAt: new Date(), consentSubmittedAt: new Date(), applicationStatus: 'APPROVED', surveyStatus: 'IN_PROGRESS', }), ).toEqual({ login: 'Completed', consent: 'Completed', agreement: 'Completed', approval: 'Completed', survey: 'Pending', }); const finished = studyProgress({ lastLoginAt: new Date(), consentSubmittedAt: new Date(), applicationStatus: 'APPROVED', surveyStatus: 'COMPLETED', }); expect(finished.survey).toBe('Completed'); expect(hasPendingStep(finished)).toBe(false); expect(hasPendingStep({ login: 'Completed', consent: 'Completed', agreement: 'Completed', approval: 'Completed', survey: 'Pending' })).toBe(true); }); it('saves reminders for imported doctors who still have a pending step', async () => { server = await createServer(); await db('admin_users').insert({ name: 'Administrator', email: adminEmail, password_hash: await argon2.hash(password, { type: argon2.argon2id }), is_active: true, }); const login = await server.inject({ method: 'POST', url: '/api/admin/auth/login', payload: { email: adminEmail, password }, }); const surveyId = await seedSurveyDefinition(); await db('pppaimt_doctors').insert({ email: 'new@example.com', hcp_name: 'Dr New Doctor', status: 'active', }); const [activeId] = await db('users').insert({ email: 'testdoc1@yopmail.com', name: 'Asha Rao', is_active: true, last_login_at: new Date(), }); const [applicationId] = await db('applications').insert({ public_id: randomUUID(), email: 'testdoc1@yopmail.com', user_id: activeId, status: 'APPROVED', full_name: 'Asha Rao', version: 1, }); await db('consents').insert({ user_id: activeId, application_id: applicationId, participant_name: 'Asha Rao', consent_date: '2026-11-01', answers: JSON.stringify({ understood: true }), submitted_at: new Date(), }); const [doctorId] = await db('pppaimt_doctors').insert({ email: 'testdoc1@yopmail.com', hcp_name: 'Dr Asha Rao', status: 'active', }); const [ameyId] = await db('pppaimt_doctors').insert({ email: 'amey@stratawiz.com', hcp_name: 'Dr Amey', status: 'active', }); // Disabled doctors must never get invitation or reminder mail. await db('pppaimt_doctors').insert({ email: 'disabled@example.com', hcp_name: 'Dr Disabled', status: 'disabled', }); await db('survey_responses').insert({ application_id: applicationId, survey_definition_id: surveyId, answers: JSON.stringify({}), status: 'IN_PROGRESS', started_at: new Date(), }); const preview = await server.inject({ method: 'GET', url: '/api/admin/emails/preview?type=reminder', headers: { cookie: sessionCookie(login) }, }); expect(preview.result.recipientCount).toBe(3); expect(preview.result.recipients).toBeUndefined(); const response = await server.inject({ method: 'POST', url: '/api/admin/emails/queue', headers: { cookie: sessionCookie(login) }, payload: { type: 'reminder', subject: 'Reminder Email for Extended-Dose-Pack Study', body: 'Dear Dr {Name},\n\nLogin — {Login}\n\nApproval — {Approval}\n\nSurvey — {Survey}\n\nCustom line', }, }); expect(response.statusCode).toBe(200); expect(response.result).toMatchObject({ type: 'reminder', recipientCount: 3, sentCount: 0, status: 'logged', }); const rows = await db('email_campaign_recipients').orderBy('id', 'asc'); expect(rows).toHaveLength(3); expect(rows.map((row) => row.to_email)).not.toContain('disabled@example.com'); const asha = rows.find((row) => row.to_email === 'testdoc1@yopmail.com'); const amey = rows.find((row) => row.to_email === 'amey@stratawiz.com'); const extra = rows.find((row) => row.to_email === 'new@example.com'); expect(asha).toMatchObject({ doctor_id: doctorId, status: 'logged' }); expect(asha.body_text).toContain('Dear Dr Asha Rao,'); expect(asha.body_text).toContain('Login — Completed'); expect(asha.body_text).toContain('Approval — Completed'); expect(asha.body_text).toContain('Survey — Pending'); expect(amey).toMatchObject({ doctor_id: ameyId, status: 'logged' }); expect(amey.body_text).toContain('Dear Dr Amey,'); expect(amey.body_text).toContain('Login — Pending'); expect(amey.body_text).not.toContain('{Name}'); expect(extra.body_text).toContain('Dear Dr New Doctor,'); expect(extra.body_text).toContain('Login — Pending'); expect(mailState.send).not.toHaveBeenCalled(); const audit = await db('audit_log').where({ action: 'EMAIL_REMINDER_QUEUED' }).first(); expect(audit.entity_id).toBe(response.result.id); await db('survey_responses').where({ application_id: applicationId }).update({ status: 'COMPLETED' }); const finished = await server.inject({ method: 'POST', url: '/api/admin/emails/queue', headers: { cookie: sessionCookie(login) }, payload: { type: 'reminder', subject: 'Reminder Email for Extended-Dose-Pack Study', body: 'Login — {Login}', }, }); expect(finished.result).toMatchObject({ recipientCount: 2, status: 'logged' }); const pendingOnly = await db('email_campaign_recipients').where({ campaign_id: finished.result.id }).orderBy('id', 'asc'); expect(pendingOnly.map((row) => row.to_email)).toEqual(['new@example.com', 'amey@stratawiz.com']); const invitation = await server.inject({ method: 'POST', url: '/api/admin/emails/queue', headers: { cookie: sessionCookie(login) }, payload: { type: 'invitation', subject: 'Extended-Dose-Pack Study - email-Invitation', body: 'Dear Doctor,', }, }); expect(invitation.result).toMatchObject({ recipientCount: 3, status: 'logged' }); const invitationRows = await db('email_campaign_recipients') .where({ campaign_id: invitation.result.id }) .select('to_email'); expect(invitationRows.map((row) => row.to_email)).not.toContain('disabled@example.com'); }); it('sends each personalized letter in one wave', async () => { process.env.MAIL_FORCE_SEND = 'true'; mailState.send.mockImplementation(async () => [{ headers: { 'x-message-id': 'msg-1' } }]); server = await createServer(); await db('admin_users').insert({ name: 'Administrator', email: adminEmail, password_hash: await argon2.hash(password, { type: argon2.argon2id }), is_active: true, }); const login = await server.inject({ method: 'POST', url: '/api/admin/auth/login', payload: { email: adminEmail, password }, }); await db('pppaimt_doctors').insert([ { email: 'asha@example.com', hcp_name: 'Dr Asha Rao', status: 'active' }, { email: 'new@example.com', hcp_name: 'Dr New Doctor', status: 'active' }, { email: 'disabled@example.com', hcp_name: 'Dr Disabled', status: 'disabled' }, ]); try { const response = await server.inject({ method: 'POST', url: '/api/admin/emails/queue', headers: { cookie: sessionCookie(login) }, payload: { type: 'reminder', subject: 'Reminder Email for Extended-Dose-Pack Study', body: 'Dear Dr {Name},', }, }); expect(response.result).toMatchObject({ recipientCount: 2, sentCount: 2, status: 'sent' }); const progress = await server.inject({ method: 'GET', url: `/api/admin/emails/campaigns/${response.result.id}`, headers: { cookie: sessionCookie(login) }, }); expect(progress.result).toMatchObject({ recipientCount: 2, sentCount: 2, status: 'sent' }); expect(mailState.send).toHaveBeenCalledTimes(2); const sent = mailState.send.mock.calls.map((call) => ({ to: call[0].to, text: call[0].text })); expect(sent.map((row) => row.to)).not.toContain('disabled@example.com'); expect(sent).toEqual( expect.arrayContaining([ expect.objectContaining({ to: 'asha@example.com', text: expect.stringContaining('Dear Dr Asha Rao,') }), expect.objectContaining({ to: 'new@example.com', text: expect.stringContaining('Dear Dr New Doctor,') }), ]), ); } finally { delete process.env.MAIL_FORCE_SEND; } }); it('limits invitation and reminder to BULK_EMAIL_ALLOWLIST when set', async () => { process.env.BULK_EMAIL_ALLOWLIST = 'asha@example.com,skipped@example.com'; server = await createServer(); await db('admin_users').insert({ name: 'Administrator', email: adminEmail, password_hash: await argon2.hash(password, { type: argon2.argon2id }), is_active: true, }); const login = await server.inject({ method: 'POST', url: '/api/admin/auth/login', payload: { email: adminEmail, password }, }); await db('pppaimt_doctors').insert([ { email: 'asha@example.com', hcp_name: 'Dr Asha Rao', status: 'active' }, { email: 'other@example.com', hcp_name: 'Dr Other', status: 'active' }, { email: 'skipped@example.com', hcp_name: 'Dr Skipped', status: 'disabled' }, ]); try { const invitation = await server.inject({ method: 'GET', url: '/api/admin/emails/preview?type=invitation', headers: { cookie: sessionCookie(login) }, }); expect(invitation.result.recipientCount).toBe(1); const reminder = await server.inject({ method: 'GET', url: '/api/admin/emails/preview?type=reminder', headers: { cookie: sessionCookie(login) }, }); expect(reminder.result.recipientCount).toBe(1); } finally { delete process.env.BULK_EMAIL_ALLOWLIST; } }); });