diff --git a/.gitignore b/.gitignore
index 4648298..2f3fe02 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,4 +2,6 @@ node_modules/
backend/.env
frontend/.env
backend/.local-storage/
-dist/
\ No newline at end of file
+dist/
+.cursor/
+.env
\ No newline at end of file
diff --git a/backend/migrations/20261119120000_email_campaigns.js b/backend/migrations/20261119120000_email_campaigns.js
new file mode 100644
index 0000000..29463d7
--- /dev/null
+++ b/backend/migrations/20261119120000_email_campaigns.js
@@ -0,0 +1,50 @@
+/** Store bulk invitation and reminder letters before any delivery. */
+export async function up(knex) {
+ await knex.schema.createTable('email_campaigns', (table) => {
+ table.charset('utf8mb4');
+ table.collate('utf8mb4_unicode_ci');
+ table.increments('id').primary();
+ table.enu('type', ['invitation', 'reminder']).notNullable();
+ table
+ .integer('created_by')
+ .unsigned()
+ .nullable()
+ .references('id')
+ .inTable('admin_users')
+ .onDelete('SET NULL');
+ table.integer('recipient_count').unsigned().notNullable().defaultTo(0);
+ table.string('status', 32).notNullable().defaultTo('queued');
+ table.datetime('created_at').notNullable().defaultTo(knex.fn.now());
+ });
+
+ await knex.schema.createTable('email_campaign_recipients', (table) => {
+ table.charset('utf8mb4');
+ table.collate('utf8mb4_unicode_ci');
+ table.increments('id').primary();
+ table
+ .integer('campaign_id')
+ .unsigned()
+ .notNullable()
+ .references('id')
+ .inTable('email_campaigns')
+ .onDelete('CASCADE');
+ table
+ .integer('doctor_id')
+ .unsigned()
+ .nullable()
+ .references('id')
+ .inTable('pppaimt_doctors')
+ .onDelete('SET NULL');
+ table.string('to_email', 255).notNullable();
+ table.string('subject', 255).notNullable();
+ table.text('body_text').notNullable();
+ table.text('body_html').notNullable();
+ table.string('status', 32).notNullable().defaultTo('queued');
+ });
+}
+
+/** Drop the bulk email queue tables. */
+export async function down(knex) {
+ await knex.schema.dropTableIfExists('email_campaign_recipients');
+ await knex.schema.dropTableIfExists('email_campaigns');
+}
diff --git a/backend/src/routes/admin.js b/backend/src/routes/admin.js
index f1dfd3c..5a8a1a7 100644
--- a/backend/src/routes/admin.js
+++ b/backend/src/routes/admin.js
@@ -6,6 +6,7 @@ import { db } from '../db/knex.js';
import { exportApplicationsWorkbook } from '../services/applicationsExport.js';
import { consentPdfFor, pdfDownload } from '../services/consentPdf.js';
import { exportWorkbook } from '../services/surveyExport.js';
+import { getEmailCampaign, previewBulkEmail, queueBulkEmail } from '../services/bulkEmail.js';
import { getReminderSettings, saveReminderSettings } from '../services/settings.js';
import {
adminDashboard,
@@ -56,6 +57,15 @@ const reminderSchema = z.object({
surveyReminderDays: z.number().int().min(1).max(30),
});
+const emailTypeSchema = z.object({
+ type: z.enum(['invitation', 'reminder']),
+});
+
+const emailQueueSchema = emailTypeSchema.extend({
+ subject: z.string().trim().min(1).max(255),
+ body: z.string().trim().min(1).max(20000),
+});
+
/**
* @param {import('@hapi/hapi').Request} request
*/
@@ -298,6 +308,54 @@ export const adminRoutes = {
},
});
+ server.route({
+ method: 'GET',
+ path: '/api/admin/emails/preview',
+ options: { pre },
+ handler(request) {
+ const parsed = emailTypeSchema.safeParse(request.query);
+
+ if (!parsed.success) {
+ throw Boom.badRequest('Choose invitation or reminder');
+ }
+
+ return previewBulkEmail(parsed.data.type);
+ },
+ });
+
+ server.route({
+ method: 'POST',
+ path: '/api/admin/emails/queue',
+ options: { pre },
+ handler(request) {
+ const parsed = emailQueueSchema.safeParse(request.payload);
+
+ if (!parsed.success) {
+ throw Boom.badRequest('Choose invitation or reminder and include the subject and letter');
+ }
+
+ return queueBulkEmail(parsed.data.type, request.pre.admin.id, {
+ subject: parsed.data.subject,
+ body: parsed.data.body,
+ });
+ },
+ });
+
+ server.route({
+ method: 'GET',
+ path: '/api/admin/emails/campaigns/{id}',
+ options: { pre },
+ async handler(request) {
+ const campaign = await getEmailCampaign(numericId(request));
+
+ if (!campaign) {
+ throw Boom.notFound('Email campaign not found');
+ }
+
+ return campaign;
+ },
+ });
+
server.route({
method: 'GET',
path: '/api/admin/audit-log',
diff --git a/backend/src/services/bulkEmail.js b/backend/src/services/bulkEmail.js
new file mode 100644
index 0000000..ab18f17
--- /dev/null
+++ b/backend/src/services/bulkEmail.js
@@ -0,0 +1,351 @@
+import { db } from '../db/knex.js';
+import { env } from '../config/env.js';
+import { recordAudit } from './audit.js';
+import { renderEmail, renderLetterHtml } from './emailTemplates.js';
+import { deliverRenderedEmails } from './mail.js';
+
+const BATCH = 200;
+
+/**
+ * Login page used in both study letters.
+ */
+function loginUrl() {
+ const base = (env.APP_BASE_URL ?? `http://127.0.0.1:${env.PORT}`).replace(/\/$/, '');
+ return `${base}/login`;
+}
+
+/**
+ * Drop a leading Dr title so the greeting does not repeat it.
+ * @param {unknown} value
+ */
+export function doctorGreetingName(value) {
+ return String(value ?? '')
+ .trim()
+ .replace(/^dr\.?\s+/i, '')
+ .trim();
+}
+
+/**
+ * Mark each study step Completed or Pending.
+ * @param {{
+ * lastLoginAt?: Date | string | null,
+ * consentSubmittedAt?: Date | string | null,
+ * applicationStatus?: string | null,
+ * surveyStatus?: string | null,
+ * }} input
+ */
+export function studyProgress(input) {
+ const status = input.applicationStatus ?? '';
+
+ return {
+ login: input.lastLoginAt ? 'Completed' : 'Pending',
+ consent: input.consentSubmittedAt ? 'Completed' : 'Pending',
+ agreement: status === 'SUBMITTED' || status === 'APPROVED' ? 'Completed' : 'Pending',
+ approval: status === 'APPROVED' ? 'Completed' : 'Pending',
+ survey: input.surveyStatus === 'COMPLETED' ? 'Completed' : 'Pending',
+ };
+}
+
+/**
+ * Attach each doctor’s study progress from users, consents, applications, and surveys.
+ * @param {{ id: number, email: string, hcp_name?: string | null }[]} doctors
+ */
+export async function withStudyProgress(doctors) {
+ if (doctors.length === 0) {
+ return [];
+ }
+
+ const emails = doctors.map((doctor) => doctor.email);
+ const users = await db('users').whereIn('email', emails).select('id', 'email', 'last_login_at');
+ const usersByEmail = new Map(users.map((user) => [String(user.email).toLowerCase(), user]));
+ const userIds = users.map((user) => user.id);
+ const consents = userIds.length
+ ? await db('consents').whereIn('user_id', userIds).select('user_id', 'submitted_at')
+ : [];
+ const consentByUser = new Map(consents.map((row) => [row.user_id, row]));
+ const applications = await db('applications')
+ .whereIn('email', emails)
+ .select('id', 'email', 'status')
+ .orderBy('id', 'asc');
+ /** @type {Map} */
+ const applicationByEmail = new Map();
+
+ for (const application of applications) {
+ applicationByEmail.set(String(application.email).toLowerCase(), application);
+ }
+
+ const applicationIds = [...applicationByEmail.values()].map((row) => row.id);
+ const surveys = applicationIds.length
+ ? await db('survey_responses')
+ .whereIn('application_id', applicationIds)
+ .select('id', 'application_id', 'status')
+ .orderBy('id', 'asc')
+ : [];
+ /** @type {Map} */
+ const surveyByApplication = new Map();
+
+ for (const survey of surveys) {
+ const current = surveyByApplication.get(survey.application_id);
+
+ if (!current || current.status !== 'COMPLETED') {
+ surveyByApplication.set(survey.application_id, survey);
+ }
+ }
+
+ return doctors.map((doctor) => {
+ const user = usersByEmail.get(doctor.email.toLowerCase());
+ const application = applicationByEmail.get(doctor.email.toLowerCase());
+ const survey = application ? surveyByApplication.get(application.id) : null;
+
+ return {
+ ...doctor,
+ steps: studyProgress({
+ lastLoginAt: user?.last_login_at ?? null,
+ consentSubmittedAt: user ? (consentByUser.get(user.id)?.submitted_at ?? null) : null,
+ applicationStatus: application?.status ?? null,
+ surveyStatus: survey?.status ?? null,
+ }),
+ };
+ });
+}
+
+/**
+ * Replace only {tokens} that appear in the letter. Text without those tokens is kept as written.
+ * @param {string} text
+ * @param {{ hcp_name?: string | null, steps?: Record }} doctor
+ */
+export function applyEmailTokens(text, doctor) {
+ const steps = doctor.steps ?? {};
+ const name = doctorGreetingName(doctor.hcp_name);
+ /** @type {Record} */
+ const values = {};
+
+ if (name) {
+ values.Name = name;
+ }
+
+ values['Application link'] = loginUrl();
+
+ for (const key of ['Login', 'Consent', 'Agreement', 'Approval', 'Survey']) {
+ const step = steps[key.toLowerCase()];
+
+ if (step === 'Completed' || step === 'Pending') {
+ values[key] = step;
+ }
+ }
+
+ return String(text).replace(/\{([^{}]+)\}/g, (match, key) => values[key] ?? match);
+}
+
+/**
+ * True when Login, Consent, Agreement, Approval, or Survey is still Pending.
+ * @param {Record | undefined} steps
+ */
+export function hasPendingStep(steps) {
+ return ['login', 'consent', 'agreement', 'approval', 'survey'].some((key) => steps?.[key] === 'Pending');
+}
+
+/** Every imported doctor. Does not create a doctor row. */
+async function listDoctors() {
+ return db('pppaimt_doctors').select('id', 'email', 'hcp_name').orderBy('id', 'asc');
+}
+
+/**
+ * Invitation uses every imported doctor. A reminder goes only to those with a pending step.
+ * @param {'invitation' | 'reminder'} type
+ */
+async function listRecipients(type) {
+ const doctors = await withStudyProgress(await listDoctors());
+
+ if (type === 'reminder') {
+ return doctors.filter((doctor) => hasPendingStep(doctor.steps));
+ }
+
+ return doctors;
+}
+
+/**
+ * Sample letter and recipient count. Nothing is stored or sent.
+ * @param {'invitation' | 'reminder'} type
+ */
+export async function previewBulkEmail(type) {
+ const doctors = await listRecipients(type);
+ const rendered = renderEmail(type === 'invitation' ? 'study_invitation' : 'study_reminder', {});
+
+ return {
+ type,
+ subject: rendered.subject,
+ text: rendered.text,
+ recipientCount: doctors.length,
+ recipients:
+ type === 'reminder'
+ ? doctors.map((doctor) => ({
+ email: doctor.email,
+ name: doctorGreetingName(doctor.hcp_name),
+ steps: doctor.steps,
+ }))
+ : [],
+ };
+}
+
+/** Send the saved letters together and record each result as it finishes.
+ * @param {number} campaignId
+ */
+async function sendCampaign(campaignId) {
+ const rows = await db('email_campaign_recipients').where({ campaign_id: campaignId }).orderBy('id', 'asc');
+ let sentCount = 0;
+ let failedCount = 0;
+ let loggedCount = 0;
+ /** @type {string | null} */
+ let error = null;
+
+ await deliverRenderedEmails(
+ rows.map((row) => ({
+ to: row.to_email,
+ subject: row.subject,
+ html: row.body_html,
+ text: row.body_text,
+ })),
+ async (index, result) => {
+ await db('email_campaign_recipients').where({ id: rows[index].id }).update({ status: result.status });
+
+ if (result.status === 'sent') {
+ sentCount += 1;
+ } else if (result.status === 'failed') {
+ failedCount += 1;
+ error = error ?? result.error;
+ } else {
+ loggedCount += 1;
+ }
+ },
+ );
+
+ const status =
+ rows.length === 0 || sentCount === rows.length
+ ? 'sent'
+ : failedCount === rows.length
+ ? 'failed'
+ : loggedCount === rows.length
+ ? 'logged'
+ : 'partial';
+
+ await db('email_campaigns').where({ id: campaignId }).update({ status });
+
+ return { sentCount, failedCount, status, error };
+}
+
+/**
+ * Current send counts for one campaign.
+ * @param {number} id
+ */
+export async function getEmailCampaign(id) {
+ const campaign = await db('email_campaigns').where({ id }).first();
+
+ if (!campaign) {
+ return null;
+ }
+
+ const counts = await db('email_campaign_recipients')
+ .where({ campaign_id: id })
+ .select('status')
+ .count({ total: '*' })
+ .groupBy('status');
+ /** @type {Record} */
+ const byStatus = {};
+
+ for (const row of counts) {
+ byStatus[String(row.status)] = Number(row.total);
+ }
+
+ return {
+ id: campaign.id,
+ type: campaign.type,
+ recipientCount: campaign.recipient_count,
+ sentCount: byStatus.sent ?? 0,
+ failedCount: byStatus.failed ?? 0,
+ loggedCount: byStatus.logged ?? 0,
+ status: campaign.status,
+ error: null,
+ from: env.MAIL_FROM || process.env.MAIL_FROM || '',
+ };
+}
+
+/**
+ * Save one letter per matching doctor, then send each saved letter through SendGrid.
+ * @param {'invitation' | 'reminder'} type
+ * @param {number} adminId
+ * @param {{ subject: string, body: string }} content
+ */
+export async function queueBulkEmail(type, adminId, content) {
+ const doctors = await listRecipients(type);
+ const messages = doctors.map((doctor) => {
+ const subject = applyEmailTokens(content.subject, doctor);
+ const body = applyEmailTokens(content.body, doctor);
+
+ return {
+ doctor_id: doctor.id,
+ to_email: doctor.email,
+ subject,
+ body_text: body,
+ body_html: renderLetterHtml(subject, body),
+ status: 'queued',
+ };
+ });
+
+ const campaignId = await db.transaction(async (trx) => {
+ const [id] = await trx('email_campaigns').insert({
+ type,
+ created_by: adminId,
+ recipient_count: messages.length,
+ status: 'queued',
+ created_at: new Date(),
+ });
+
+ for (let index = 0; index < messages.length; index += BATCH) {
+ const slice = messages.slice(index, index + BATCH).map((row) => ({
+ ...row,
+ campaign_id: id,
+ }));
+
+ if (slice.length > 0) {
+ await trx('email_campaign_recipients').insert(slice);
+ }
+ }
+
+ await recordAudit(
+ {
+ actorType: 'ADMIN',
+ actorId: adminId,
+ action: type === 'invitation' ? 'EMAIL_INVITATION_QUEUED' : 'EMAIL_REMINDER_QUEUED',
+ entityType: 'email_campaigns',
+ entityId: id,
+ metadata: { recipientCount: messages.length },
+ },
+ trx,
+ );
+
+ return id;
+ });
+
+ const sending = sendCampaign(campaignId).catch((sendError) => {
+ console.error(sendError);
+ return db('email_campaigns').where({ id: campaignId }).update({ status: 'failed' });
+ });
+
+ if (env.NODE_ENV === 'test') {
+ await sending;
+ return getEmailCampaign(campaignId);
+ }
+
+ return {
+ id: campaignId,
+ type,
+ recipientCount: messages.length,
+ sentCount: 0,
+ failedCount: 0,
+ loggedCount: 0,
+ status: messages.length === 0 ? 'sent' : 'queued',
+ error: null,
+ from: env.MAIL_FROM || process.env.MAIL_FROM || '',
+ };
+}
diff --git a/backend/src/services/emailTemplates.js b/backend/src/services/emailTemplates.js
index f2ed624..e19eb02 100644
--- a/backend/src/services/emailTemplates.js
+++ b/backend/src/services/emailTemplates.js
@@ -51,9 +51,197 @@ function layout(content) {
return { subject: content.subject, html, text };
}
+const SURVEY_TITLE =
+ '“Physicians’ Perceptions of the Impact of an Extended-Dose Pack versus Regular Pack on Adherence to Inhaled Maintenance Medication in Asthma and COPD.”';
+
+const SIGN_OFF = 'CREST Team\nChest Research and Training Pvt. Ltd.\nPune';
+
+/**
+ * Bold the survey title, honorarium, and CREST marks, and turn an application link line into a link.
+ * @param {string} line
+ */
+function formatLine(line) {
+ const link = String(line).match(/^(Application Link:)\s+(https?:\/\/\S+)$/);
+
+ if (link) {
+ const href = escapeHtml(link[2]);
+ return `Application Link: ${href} `;
+ }
+
+ if (line.trim() === 'CREST Team') {
+ return 'CREST Team ';
+ }
+
+ if (line.trim() === 'Reminder: Extended-Dose-Pack Study') {
+ return 'Reminder: Extended-Dose-Pack Study ';
+ }
+
+ return escapeHtml(line)
+ .replaceAll('(CREST)', '(CREST) ')
+ .replaceAll(SURVEY_TITLE, `${SURVEY_TITLE} `)
+ .replaceAll('two weeks', 'two weeks ')
+ .replaceAll('₹15,000', '₹15,000 ');
+}
+
+/**
+ * Keep line breaks inside one paragraph.
+ * @param {string} paragraph
+ */
+function formatParagraph(paragraph) {
+ return String(paragraph)
+ .split('\n')
+ .map((line) => formatLine(line))
+ .join(' ');
+}
+
+/**
+ * Plain study letter, without the sign-in header or footer.
+ * @param {string} subject
+ * @param {string[]} before
+ * @param {string[]} [bullets]
+ * @param {string[]} [after]
+ */
+function letter(subject, before, bullets = [], after = []) {
+ const bulletHtml = bullets.length
+ ? `${bullets
+ .map((item) => `${escapeHtml(item)} `)
+ .join('')} `
+ : '';
+ const html = `
+
+
+
+
+${escapeHtml(subject)}
+
+
+
+ ${before.map((paragraph) => `
${formatParagraph(paragraph)}
`).join('')}
+ ${bulletHtml}
+ ${after.map((paragraph) => `
${formatParagraph(paragraph)}
`).join('')}
+
+
+`;
+ const lines = [];
+
+ for (const paragraph of before) {
+ lines.push(paragraph, '');
+ }
+
+ for (const item of bullets) {
+ lines.push(`• ${item}`);
+ }
+
+ if (bullets.length > 0) {
+ lines.push('');
+ }
+
+ for (const paragraph of after) {
+ lines.push(paragraph, '');
+ }
+
+ return { subject, html, text: lines.join('\n').trim() };
+}
+
+/**
+ * Invitation letter. {Application link} is filled in for each doctor at send time.
+ */
+function studyInvitation() {
+ return letter(
+ 'Extended-Dose-Pack Study - email-Invitation',
+ [
+ 'Dear Doctor,',
+ 'Greetings from Chest Research And Training (CREST) Pvt. Ltd., Pune!',
+ 'CREST is an academic research and training organization founded by Dr. Sundeep Salvi, focusing on respiratory research, education, and innovation.',
+ `We invite you to participate in a pan-India survey titled ${SURVEY_TITLE} The survey aims to understand physicians’ perspectives on medication adherence and the potential benefits of Extended-Dose Packs in routine clinical practice.`,
+ 'The online survey will take approximately 10–15 minutes. Kindly complete it within two weeks of receiving this invitation. Your participation is voluntary, and all responses will remain confidential. The study has been approved by the Central Independent Ethics Committee (CIEC), Pune, and is supported by Cipla Ltd.',
+ 'A professional honorarium of ₹15,000 will be provided upon completion and submission of the questionnaire and execution of an MOU with CREST.',
+ 'Application Link: {Application link}',
+ 'We sincerely appreciate your time and participation. Your valuable professional inputs will contribute to a better understanding of inhaled medication adherence and prescribing practices in routine clinical settings.',
+ 'Thank you for your support and cooperation.',
+ 'Warm regards,',
+ SIGN_OFF,
+ ],
+ );
+}
+
+/** Reminder letter. Name, progress, and the link are filled in for each doctor at send time. */
+function studyReminder() {
+ return letter(
+ 'Reminder Email for Extended-Dose-Pack Study',
+ [
+ 'Dear Dr {Name},',
+ 'Reminder: Extended-Dose-Pack Study',
+ 'Greetings from Chest Research And Training (CREST) Pvt. Ltd., Pune!',
+ 'Please continue and complete your Extended-Dose Pack Study survey from where you left off.',
+ 'Your current progress:',
+ ],
+ [
+ 'Login — {Login}',
+ 'Consent — {Consent}',
+ 'Agreement — {Agreement}',
+ 'Approval — {Approval}',
+ 'Survey — {Survey}',
+ ],
+ [
+ 'Application Link: {Application link}',
+ 'Thank you for your support and cooperation.',
+ 'Warm regards,',
+ SIGN_OFF,
+ ],
+ );
+}
+
+/**
+ * HTML for a letter whose text was already filled in.
+ * @param {string} subject
+ * @param {string} text
+ */
+export function renderLetterHtml(subject, text) {
+ const blocks = String(text)
+ .split(/\n{2,}/)
+ .map((block) => block.trim())
+ .filter(Boolean);
+ const framed =
+ blocks[0] === 'Chest Research and Training' &&
+ blocks[blocks.length - 1] === 'Extended-Dose Pack Study';
+ const bodyBlocks = framed ? blocks.slice(2, -1) : blocks;
+ const htmlBlocks = bodyBlocks
+ .map((block) => {
+ const lines = block.split('\n').map((line) => line.trim()).filter(Boolean);
+ const items = lines.filter((line) => line.startsWith('• '));
+
+ if (items.length > 0 && items.length === lines.length) {
+ return `${items
+ .map((item) => `${escapeHtml(item.slice(2))} `)
+ .join('')} `;
+ }
+
+ return `${lines.map((line) => formatLine(line)).join(' ')}
`;
+ })
+ .join('');
+ const frameStart = framed
+ ? `Chest Research and Training
${escapeHtml(blocks[1] || '')} `
+ : '';
+ const frameEnd = framed
+ ? `Extended-Dose Pack Study
`
+ : '';
+
+ return `
+
+
+
+${escapeHtml(subject)}
+
+
+ ${frameStart}${htmlBlocks}${frameEnd}
+
+`;
+}
+
/**
* @param {string} name
- * @param {{ url?: string, name?: string, reason?: string, otp?: string }} data
+ * @param {{ url?: string, name?: string, reason?: string, otp?: string, steps?: Record }} data
*/
export function renderEmail(name, data) {
const physician = data.name || 'Doctor';
@@ -150,5 +338,13 @@ export function renderEmail(name, data) {
});
}
+ if (name === 'study_invitation') {
+ return studyInvitation();
+ }
+
+ if (name === 'study_reminder') {
+ return studyReminder();
+ }
+
throw new Error(`Unknown email template: ${name}`);
}
diff --git a/backend/src/services/mail.js b/backend/src/services/mail.js
index 19c56fd..d7bbe89 100644
--- a/backend/src/services/mail.js
+++ b/backend/src/services/mail.js
@@ -98,6 +98,110 @@ async function deliverToSendGrid(message) {
throw lastError;
}
+const SEND_AT_ONCE = 100;
+
+/**
+ * @param {unknown} error
+ */
+function sendGridError(error) {
+ const body = error && typeof error === 'object' && 'response' in error ? error.response?.body : null;
+ const details = Array.isArray(body?.errors)
+ ? body.errors.map((item) => item.message).filter(Boolean).join('; ')
+ : '';
+
+ return details || (error instanceof Error ? error.message : 'Email could not be sent');
+}
+
+/**
+ * @param {{ to: string, subject: string, html: string, text: string, from?: string }} message
+ * @param {string} fromName
+ */
+function renderedPayload(message, fromName) {
+ const fromEmail = message.from || env.MAIL_FROM || process.env.MAIL_FROM;
+ const payload = {
+ to: message.to,
+ from: { email: fromEmail, name: fromName },
+ subject: message.subject,
+ html: message.html,
+ text: message.text,
+ };
+
+ if (sandboxEnabled()) {
+ payload.mailSettings = { sandboxMode: { enable: true } };
+ }
+
+ return payload;
+}
+
+/**
+ * Deliver one already rendered letter through SendGrid.
+ * @param {{ to: string, subject: string, html: string, text: string, from?: string }} message
+ */
+export async function deliverRenderedEmail(message) {
+ const [result] = await deliverRenderedEmails([message]);
+ return result;
+}
+
+/**
+ * Deliver rendered letters together. Each letter is sent as written.
+ * @param {{ to: string, subject: string, html: string, text: string, from?: string }[]} messages
+ * @param {(index: number, result: { status: string, error: string | null }) => Promise | void} [onResult]
+ */
+export async function deliverRenderedEmails(messages, onResult) {
+ if (!useSendGrid()) {
+ const status = env.NODE_ENV === 'production' ? 'failed' : 'logged';
+ const error = env.NODE_ENV === 'production' ? 'SENDGRID_API_KEY is not configured' : null;
+ const results = messages.map(() => ({ status, error }));
+
+ for (let index = 0; index < results.length; index += 1) {
+ if (onResult) {
+ await onResult(index, results[index]);
+ }
+ }
+
+ return results;
+ }
+
+ const fromName = await getMailFromName();
+ /** @type {{ status: string, error: string | null }[]} */
+ const results = new Array(messages.length);
+ /** @type {{ message: { to: string, subject: string, html: string, text: string, from?: string }, index: number }[]} */
+ const ready = [];
+
+ messages.forEach((message, index) => {
+ if (!(message.from || env.MAIL_FROM || process.env.MAIL_FROM)) {
+ results[index] = { status: 'failed', error: 'MAIL_FROM is not configured' };
+ return;
+ }
+
+ ready.push({ message, index });
+ });
+
+ for (let index = 0; index < ready.length; index += SEND_AT_ONCE) {
+ const slice = ready.slice(index, index + SEND_AT_ONCE);
+ await Promise.all(
+ slice.map(async ({ message, index: resultIndex }) => {
+ let result;
+
+ try {
+ await deliverToSendGrid(renderedPayload(message, fromName));
+ result = { status: 'sent', error: null };
+ } catch (error) {
+ result = { status: 'failed', error: sendGridError(error) };
+ }
+
+ results[resultIndex] = result;
+
+ if (onResult) {
+ await onResult(resultIndex, result);
+ }
+ }),
+ );
+ }
+
+ return results;
+}
+
/**
* Send one template. Failures are stored on email_log and are not rethrown.
* @param {string} name
diff --git a/backend/test/bulkEmail.test.js b/backend/test/bulkEmail.test.js
new file mode 100644
index 0000000..9578664
--- /dev/null
+++ b/backend/test/bulkEmail.test.js
@@ -0,0 +1,358 @@
+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();
+ 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',
+ });
+ 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',
+ });
+ const [ameyId] = await db('pppaimt_doctors').insert({
+ email: 'amey@stratawiz.com',
+ hcp_name: 'Dr Amey',
+ });
+ 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.recipients).toEqual([
+ {
+ email: 'new@example.com',
+ name: 'New Doctor',
+ steps: {
+ login: 'Pending',
+ consent: 'Pending',
+ agreement: 'Pending',
+ approval: 'Pending',
+ survey: 'Pending',
+ },
+ },
+ {
+ email: 'testdoc1@yopmail.com',
+ name: 'Asha Rao',
+ steps: {
+ login: 'Completed',
+ consent: 'Completed',
+ agreement: 'Completed',
+ approval: 'Completed',
+ survey: 'Pending',
+ },
+ },
+ {
+ email: 'amey@stratawiz.com',
+ name: 'Amey',
+ steps: {
+ login: 'Pending',
+ consent: 'Pending',
+ agreement: 'Pending',
+ approval: 'Pending',
+ survey: 'Pending',
+ },
+ },
+ ]);
+
+ 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);
+ 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' });
+ });
+
+ 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' },
+ { email: 'new@example.com', hcp_name: 'Dr New Doctor' },
+ ]);
+
+ 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).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;
+ }
+ });
+});
diff --git a/backend/test/truncate.js b/backend/test/truncate.js
index 97045b7..a48c3f7 100644
--- a/backend/test/truncate.js
+++ b/backend/test/truncate.js
@@ -2,6 +2,8 @@ import { db } from '../src/db/knex.js';
const TABLES = [
'audit_log',
+ 'email_campaign_recipients',
+ 'email_campaigns',
'email_log',
'survey_responses',
'survey_tokens',
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 61dacc5..06efe84 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -6,6 +6,7 @@ import AuditPage from './admin/AuditPage.jsx';
import DashboardPage from './admin/DashboardPage.jsx';
import LoginPage from './admin/LoginPage.jsx';
import ReportsPage from './admin/ReportsPage.jsx';
+import SendEmailsPage from './admin/SendEmailsPage.jsx';
import SettingsPage from './admin/SettingsPage.jsx';
import UsersPage from './admin/UsersPage.jsx';
import PrivacyPage from './pages/PrivacyPage.jsx';
@@ -79,6 +80,7 @@ export default function App() {
} />
} />
} />
+ } />
} />
} />
} />
diff --git a/frontend/src/admin.css b/frontend/src/admin.css
index a332e60..33e842a 100644
--- a/frontend/src/admin.css
+++ b/frontend/src/admin.css
@@ -423,3 +423,88 @@ input[type='checkbox'].h-4 {
padding: 0;
flex: 0 0 auto;
}
+
+.email-send-layout {
+ display: grid;
+ gap: 1rem;
+ align-items: start;
+}
+
+@media (min-width: 60rem) {
+ .email-send-layout {
+ grid-template-columns: minmax(16rem, 22rem) minmax(0, 1fr);
+ }
+}
+
+.email-letter-card {
+ display: flex;
+ flex-direction: column;
+ min-height: 28rem;
+}
+
+.email-letter-toolbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.75rem;
+ margin-bottom: 0.75rem;
+}
+
+.email-letter-paper,
+.email-letter-input {
+ flex: 1;
+ width: 100%;
+ min-height: 28rem;
+ overflow: auto;
+ padding: 1.25rem 1.35rem;
+ border-radius: 0.85rem;
+ background: #fffdf8;
+ border: 1px solid #e7e5e4;
+ color: #292524;
+ font-family: Georgia, 'Times New Roman', serif;
+ font-size: 0.98rem;
+ line-height: 1.55;
+ box-sizing: border-box;
+ resize: vertical;
+}
+
+.email-letter-subject {
+ width: 100%;
+ margin-top: 0.35rem;
+}
+
+.email-letter-paper p {
+ margin: 0 0 0.9rem;
+}
+
+.email-letter-paper ul {
+ margin: 0 0 0.9rem;
+ padding-left: 1.2rem;
+}
+
+.email-letter-screen {
+ position: fixed;
+ inset: 0;
+ z-index: 40;
+ display: flex;
+ flex-direction: column;
+ padding: 1.25rem;
+ background: rgb(19 78 74 / 0.45);
+}
+
+.email-letter-screen-sheet {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ min-height: 0;
+ width: min(46rem, 100%);
+ margin: 0 auto;
+ padding: 1.25rem 1.5rem 1.5rem;
+ border-radius: 1rem;
+ background: #fff;
+ box-shadow: 0 24px 60px rgb(28 25 23 / 0.25);
+}
+
+.email-letter-screen .email-letter-paper {
+ max-height: none;
+}
diff --git a/frontend/src/admin/AdminLayout.jsx b/frontend/src/admin/AdminLayout.jsx
index ba429d4..c259487 100644
--- a/frontend/src/admin/AdminLayout.jsx
+++ b/frontend/src/admin/AdminLayout.jsx
@@ -10,6 +10,7 @@ const LINKS = [
['/admin/settings', 'Settings'],
['/admin/users', 'Admin users'],
['/admin/audit', 'Audit log'],
+ ['/admin/emails', 'Send emails'],
];
const NAV_KEY = 'crest-admin-nav';
diff --git a/frontend/src/admin/SendEmailsPage.jsx b/frontend/src/admin/SendEmailsPage.jsx
new file mode 100644
index 0000000..ef59ecd
--- /dev/null
+++ b/frontend/src/admin/SendEmailsPage.jsx
@@ -0,0 +1,309 @@
+import { useEffect, useRef, useState } from 'react';
+import { adminApi } from './adminApi.js';
+
+const PROGRESS = [
+ ['login', 'Login'],
+ ['consent', 'Consent'],
+ ['agreement', 'Agreement'],
+ ['approval', 'Approval'],
+ ['survey', 'Survey'],
+];
+
+const TYPES = [
+ {
+ id: 'invitation',
+ label: 'Invitation email',
+ detail: 'Sent to every imported doctor.',
+ },
+ {
+ id: 'reminder',
+ label: 'Reminder email',
+ detail: 'Sent to imported doctors who still have Login, Consent, Agreement, Approval, or Survey pending.',
+ },
+];
+
+/**
+ * @param {{ status?: string, sentCount?: number, recipientCount?: number, error?: string | null, from?: string }} queued
+ */
+function sendResult(queued) {
+ if ((queued.recipientCount ?? 0) === 0) {
+ return 'No emails were sent.';
+ }
+
+ if (queued.status === 'sent') {
+ const from = queued.from ? ` from ${queued.from}` : '';
+ return `${queued.sentCount} emails were sent${from}.`;
+ }
+
+ if (queued.status === 'logged') {
+ return `Saved ${queued.recipientCount} emails. SendGrid is not configured.`;
+ }
+
+ if (queued.error) {
+ return queued.error;
+ }
+
+ return `Sent ${queued.sentCount ?? 0} of ${queued.recipientCount ?? 0} emails.`;
+}
+
+/**
+ * @param {{ sentCount?: number, recipientCount?: number }} queued
+ */
+function sendingProgress(queued) {
+ return `Sent ${queued.sentCount ?? 0} of ${queued.recipientCount ?? 0} emails.`;
+}
+
+/**
+ * @param {{ onClose: () => void }} props
+ */
+function useEscapeClose(onClose) {
+ useEffect(() => {
+ function onKey(event) {
+ if (event.key === 'Escape') {
+ onClose();
+ }
+ }
+
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [onClose]);
+}
+
+/**
+ * @param {{
+ * subject: string,
+ * body: string,
+ * onSubject: (value: string) => void,
+ * onBody: (value: string) => void,
+ * onClose: () => void,
+ * }} props
+ */
+function LetterScreen({ subject, body, onSubject, onBody, onClose }) {
+ useEscapeClose(onClose);
+
+ return (
+
+
+
+
Edit the letter
+
+ Close
+
+
+
+ Subject
+ onSubject(event.target.value)}
+ />
+
+
+ Letter
+
+
+
+ );
+}
+
+export default function SendEmailsPage() {
+ const [type, setType] = useState('invitation');
+ const [recipientCount, setRecipientCount] = useState(null);
+ const [recipients, setRecipients] = useState([]);
+ const [subject, setSubject] = useState('');
+ const [body, setBody] = useState('');
+ const [ready, setReady] = useState(false);
+ const [error, setError] = useState('');
+ const [result, setResult] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [fullScreen, setFullScreen] = useState(false);
+ const watch = useRef(0);
+
+ useEffect(() => {
+ let cancelled = false;
+ setReady(false);
+ setFullScreen(false);
+ setError('');
+ setRecipients([]);
+
+ adminApi(`/api/admin/emails/preview?type=${type}`)
+ .then((data) => {
+ if (!cancelled) {
+ setSubject(data.subject);
+ setBody(data.text);
+ setRecipientCount(data.recipientCount);
+ setRecipients(Array.isArray(data.recipients) ? data.recipients : []);
+ setReady(true);
+ }
+ })
+ .catch((loadError) => {
+ if (!cancelled) {
+ setError(loadError.message);
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [type]);
+
+ async function send(event) {
+ event.preventDefault();
+ const watchId = watch.current + 1;
+ watch.current = watchId;
+ setBusy(true);
+ setError('');
+ setResult('');
+
+ try {
+ let current = await adminApi('/api/admin/emails/queue', {
+ method: 'POST',
+ body: { type, subject, body },
+ });
+
+ while (current.status === 'queued' && current.id) {
+ if (watch.current !== watchId) {
+ return;
+ }
+
+ setResult(sendingProgress(current));
+ await new Promise((resolve) => {
+ setTimeout(resolve, 1000);
+ });
+
+ if (watch.current !== watchId) {
+ return;
+ }
+
+ current = await adminApi(`/api/admin/emails/campaigns/${current.id}`);
+ }
+
+ if (watch.current !== watchId) {
+ return;
+ }
+
+ setResult(sendResult(current));
+ } catch (sendError) {
+ if (watch.current === watchId) {
+ setError(sendError.message);
+ }
+ } finally {
+ if (watch.current === watchId) {
+ setBusy(false);
+ }
+ }
+ }
+
+ return (
+
+
Send emails
+
+
+
+
+
Letter
+
setFullScreen(true)}
+ >
+ Full screen
+
+
+
+ Subject
+ setSubject(event.target.value)}
+ />
+
+
+ Letter
+
+
+
+ {fullScreen ? (
+
setFullScreen(false)}
+ />
+ ) : null}
+
+ );
+}
diff --git a/frontend/src/admin/SendEmailsPage.test.jsx b/frontend/src/admin/SendEmailsPage.test.jsx
new file mode 100644
index 0000000..ed9ea46
--- /dev/null
+++ b/frontend/src/admin/SendEmailsPage.test.jsx
@@ -0,0 +1,196 @@
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import SendEmailsPage from './SendEmailsPage.jsx';
+
+describe('send emails page', () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ fetchMock.mockReset();
+ fetchMock.mockImplementation(async (path, options) => {
+ const url = String(path);
+
+ if (options?.method === 'POST') {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ id: 1,
+ type: JSON.parse(options.body).type,
+ recipientCount: 4,
+ sentCount: 4,
+ status: 'sent',
+ from: 'crest@crestindia.co.in',
+ }),
+ };
+ }
+
+ if (url.includes('type=reminder')) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ type: 'reminder',
+ subject: 'Reminder Email for Extended-Dose-Pack Study',
+ text: 'Dear Dr {Name},',
+ recipientCount: 1,
+ recipients: [
+ {
+ email: 'testdoc1@yopmail.com',
+ name: 'Asha Rao',
+ steps: {
+ login: 'Completed',
+ consent: 'Pending',
+ agreement: 'Pending',
+ approval: 'Pending',
+ survey: 'Pending',
+ },
+ },
+ ],
+ }),
+ };
+ }
+
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ type: 'invitation',
+ subject: 'Extended-Dose-Pack Study - email-Invitation',
+ text: 'Dear Doctor,',
+ recipientCount: 4,
+ }),
+ };
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ });
+
+ it('switches the letter and sends the edited subject and body', async () => {
+ render( );
+
+ await waitFor(() => {
+ expect(screen.getByLabelText('Subject')).toHaveValue(
+ 'Extended-Dose-Pack Study - email-Invitation',
+ );
+ });
+ expect(screen.getByLabelText('Letter')).toHaveValue('Dear Doctor,');
+
+ fireEvent.click(screen.getByRole('radio', { name: /Reminder email/ }));
+
+ await waitFor(() => {
+ expect(screen.getByLabelText('Subject')).toHaveValue(
+ 'Reminder Email for Extended-Dose-Pack Study',
+ );
+ expect(screen.getByLabelText('Letter')).toHaveValue('Dear Dr {Name},');
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/admin/emails/preview?type=reminder',
+ expect.objectContaining({ method: 'GET' }),
+ );
+ expect(screen.getByText('testdoc1@yopmail.com')).toBeInTheDocument();
+ expect(screen.getByText('Login — Completed')).toBeInTheDocument();
+ expect(screen.getByText('Survey — Pending')).toBeInTheDocument();
+
+ fireEvent.change(screen.getByLabelText('Letter'), {
+ target: { value: 'Hello {Name}' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Full screen' }));
+ expect(screen.getByRole('dialog', { name: 'Email letter' })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }));
+
+ fireEvent.click(screen.getByRole('button', { name: 'Send emails' }));
+
+ await waitFor(() => {
+ expect(screen.getByRole('status')).toHaveTextContent(
+ '4 emails were sent from crest@crestindia.co.in.',
+ );
+ });
+ const queued = fetchMock.mock.calls.find((call) => call[1]?.method === 'POST');
+ expect(queued?.[0]).toBe('/api/admin/emails/queue');
+ expect(JSON.parse(queued[1].body)).toEqual({
+ type: 'reminder',
+ subject: 'Reminder Email for Extended-Dose-Pack Study',
+ body: 'Hello {Name}',
+ });
+ });
+
+ it('updates the sent count until the campaign finishes', async () => {
+ let polls = 0;
+ fetchMock.mockImplementation(async (path, options) => {
+ const url = String(path);
+
+ if (options?.method === 'POST') {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ id: 9,
+ type: 'invitation',
+ recipientCount: 37,
+ sentCount: 0,
+ status: 'queued',
+ from: 'crest@crestindia.co.in',
+ }),
+ };
+ }
+
+ if (url.includes('/api/admin/emails/campaigns/9')) {
+ polls += 1;
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ id: 9,
+ recipientCount: 37,
+ sentCount: polls === 1 ? 12 : 37,
+ status: polls === 1 ? 'queued' : 'sent',
+ from: 'crest@crestindia.co.in',
+ }),
+ };
+ }
+
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ type: 'invitation',
+ subject: 'Extended-Dose-Pack Study - email-Invitation',
+ text: 'Dear Doctor,',
+ recipientCount: 37,
+ recipients: [],
+ }),
+ };
+ });
+
+ render( );
+ await waitFor(() => {
+ expect(screen.getByLabelText('Subject')).toHaveValue(
+ 'Extended-Dose-Pack Study - email-Invitation',
+ );
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Send emails' }));
+
+ await waitFor(() => {
+ expect(screen.getByRole('status')).toHaveTextContent('Sent 0 of 37 emails.');
+ });
+ await waitFor(
+ () => {
+ expect(screen.getByRole('status')).toHaveTextContent('Sent 12 of 37 emails.');
+ },
+ { timeout: 3000 },
+ );
+ await waitFor(
+ () => {
+ expect(screen.getByRole('status')).toHaveTextContent(
+ '37 emails were sent from crest@crestindia.co.in.',
+ );
+ },
+ { timeout: 3000 },
+ );
+ });
+});