# added send bulk email for invitation and reminder

- An Invitation email with application link will be sent to all active doctors
   - A reminder email will be sent all active users who have at least one step in pending state.
# imported 5 new doctors and added status column in doctor list (pppaimt_doctors) table.
This commit is contained in:
Amey Bhagwat 2026-11-20 15:05:08 +05:30
parent 86689f019f
commit 351e8a7203
14 changed files with 807 additions and 572 deletions

View File

@ -72,7 +72,16 @@ See [docs/DEPLOY.md](docs/DEPLOY.md) for Ubuntu on EC2, Nginx, PM2, RDS, and S3.
## Import doctors from a CSV file ## Import doctors from a CSV file
# File path: files/import/*.csv
# run below from root if you want to update/import the doctors File path: `files/import/*.csv`. From the repo root:
npm run import:doctors -- import-doctors-04-11-2026.csv
```bash
npm run import:doctors -- import-doctors-18-11-2026.csv
```
## Admin invitation / reminder emails
Admin → Send emails targets **active** doctors only (`pppaimt_doctors.status`). Reminder also requires at least one pending study step.
For local testing without mailing the full list, set `BULK_EMAIL_ALLOWLIST` in `backend/.env` (comma-separated emails), restart the API, then clear it again. Leave it unset on the server so all active doctors are included.

View File

@ -18,6 +18,10 @@ SENDGRID_API_KEY=
SENDGRID_SANDBOX_MODE=false SENDGRID_SANDBOX_MODE=false
SENDGRID_WEBHOOK_VERIFICATION_KEY= SENDGRID_WEBHOOK_VERIFICATION_KEY=
ADMIN_NOTIFY_EMAILS= ADMIN_NOTIFY_EMAILS=
# Optional local-only limit for Admin → Send emails (invitation/reminder).
# Unset or empty = all active doctors (production). Never set this on the server.
# Example for local testing: amey@stratawiz.com,testdoc1@yopmail.com
BULK_EMAIL_ALLOWLIST=
MAIL_FROM= MAIL_FROM=
APP_BASE_URL=http://localhost:5173 APP_BASE_URL=http://localhost:5173

View File

@ -0,0 +1,13 @@
/** Add Status (active/disabled) so listed doctors can be turned off without deleting them. */
export async function up(knex) {
await knex.schema.alterTable('pppaimt_doctors', (table) => {
table.string('status', 32).notNullable().defaultTo('active').after('contact_no');
});
}
/** Remove doctor status column. */
export async function down(knex) {
await knex.schema.alterTable('pppaimt_doctors', (table) => {
table.dropColumn('status');
});
}

View File

@ -53,6 +53,8 @@ const envSchema = z.object({
}, z.boolean()), }, z.boolean()),
SENDGRID_WEBHOOK_VERIFICATION_KEY: optionalText, SENDGRID_WEBHOOK_VERIFICATION_KEY: optionalText,
ADMIN_NOTIFY_EMAILS: optionalText, ADMIN_NOTIFY_EMAILS: optionalText,
/** Optional local allowlist for bulk invitation/reminder; leave unset in production. */
BULK_EMAIL_ALLOWLIST: optionalText,
MAIL_FROM: optionalText, MAIL_FROM: optionalText,
APP_BASE_URL: optionalUrl, APP_BASE_URL: optionalUrl,
JWT_SECRET: optionalText, JWT_SECRET: optionalText,

View File

@ -145,13 +145,43 @@ export function hasPendingStep(steps) {
return ['login', 'consent', 'agreement', 'approval', 'survey'].some((key) => steps?.[key] === 'Pending'); return ['login', 'consent', 'agreement', 'approval', 'survey'].some((key) => steps?.[key] === 'Pending');
} }
/** Every imported doctor. Does not create a doctor row. */ /**
async function listDoctors() { * Optional local test allowlist from BULK_EMAIL_ALLOWLIST.
return db('pppaimt_doctors').select('id', 'email', 'hcp_name').orderBy('id', 'asc'); * Production / server: leave unset → empty set → every active doctor.
* Local testing: set a comma-separated list, restart the API, then clear it again.
*/
function bulkEmailAllowlist() {
const raw = process.env.BULK_EMAIL_ALLOWLIST || '';
return new Set(
String(raw)
.split(',')
.map((email) => email.trim().toLowerCase())
.filter(Boolean),
);
} }
/** /**
* Invitation uses every imported doctor. A reminder goes only to those with a pending step. * Production recipient base: active doctors only.
* If BULK_EMAIL_ALLOWLIST is set (local), further restrict to those emails.
*/
async function listDoctors() {
let query = db('pppaimt_doctors')
.where({ status: 'active' })
.select('id', 'email', 'hcp_name')
.orderBy('id', 'asc');
const allow = bulkEmailAllowlist();
if (allow.size > 0) {
query = query.whereIn('email', [...allow]);
}
return query;
}
/**
* Invitation → all active doctors (or local allowlist).
* Reminder → those with any pending Login/Consent/Agreement/Approval/Survey step.
* Disabled doctors are never emailed.
* @param {'invitation' | 'reminder'} type * @param {'invitation' | 'reminder'} type
*/ */
async function listRecipients(type) { async function listRecipients(type) {

View File

@ -27,10 +27,12 @@ export const DOCTOR_COLUMNS = {
VENDORNAME: 'vendor_name', VENDORNAME: 'vendor_name',
'Email ID': 'email', 'Email ID': 'email',
'Contact No': 'contact_no', 'Contact No': 'contact_no',
Status: 'status',
}; };
const IGNORED_HEADERS = ['Sr NO']; const IGNORED_HEADERS = ['Sr NO'];
const BATCH = 200; const BATCH = 200;
const DOCTOR_STATUSES = new Set(['active', 'disabled']);
const emailSchema = z.string().max(255).email(); const emailSchema = z.string().max(255).email();
/** Read a CSV stream into its headers and numbered rows; rows with the wrong column count have `data: null`. */ /** Read a CSV stream into its headers and numbered rows; rows with the wrong column count have `data: null`. */
@ -79,12 +81,21 @@ export function validateDoctors({ headers, rows }) {
]), ]),
); );
record.email = record.email ? record.email.toLowerCase() : null; record.email = record.email ? record.email.toLowerCase() : null;
record.status = record.status ? record.status.toLowerCase() : null;
const label = { row, name: record.hcp_name ?? '' }; const label = { row, name: record.hcp_name ?? '' };
if (!record.email) { if (!record.email) {
invalid.push({ ...label, email: '', reason: 'email is missing' }); invalid.push({ ...label, email: '', reason: 'email is missing' });
} else if (!emailSchema.safeParse(record.email).success) { } else if (!emailSchema.safeParse(record.email).success) {
invalid.push({ ...label, email: record.email, reason: `"${record.email}" is not a valid email` }); invalid.push({ ...label, email: record.email, reason: `"${record.email}" is not a valid email` });
} else if (!record.status) {
invalid.push({ ...label, email: record.email, reason: 'status is missing' });
} else if (!DOCTOR_STATUSES.has(record.status)) {
invalid.push({
...label,
email: record.email,
reason: `status must be active or disabled (got "${record.status}")`,
});
} else { } else {
byEmail.set(record.email, [...(byEmail.get(record.email) ?? []), label]); byEmail.set(record.email, [...(byEmail.get(record.email) ?? []), label]);
records.push(record); records.push(record);

View File

@ -51,14 +51,21 @@ function normalizeEmail(email) {
return email.trim().toLowerCase(); return email.trim().toLowerCase();
} }
/** Return the listed doctor's HCP NAME without a leading "Dr"/"Dr."; unlisted emails get "Invalid User!". */ /**
* Return the listed doctor's HCP NAME without a leading "Dr"/"Dr.".
* Unlisted emails get "Invalid User!"; disabled list rows get "Account is disabled".
*/
async function doctorNameFor(email) { async function doctorNameFor(email) {
const doctor = await db('pppaimt_doctors').where({ email }).first('hcp_name'); const doctor = await db('pppaimt_doctors').where({ email }).first('hcp_name', 'status');
if (!doctor) { if (!doctor) {
throw Boom.forbidden('Invalid User!'); throw Boom.forbidden('Invalid User!');
} }
if (String(doctor.status ?? 'active').toLowerCase() === 'disabled') {
throw Boom.forbidden('Account is disabled');
}
return String(doctor.hcp_name ?? '').trim().replace(/^dr(\.\s*|\s+)/i, '') || null; return String(doctor.hcp_name ?? '').trim().replace(/^dr(\.\s*|\s+)/i, '') || null;
} }
@ -120,7 +127,7 @@ async function ensureUserAndApplication(email, doctorName) {
return { user, application }; return { user, application };
} }
/** Email a login code to a doctor listed in pppaimt_doctors; others get "Invalid User!". */ /** Email a login code to an active doctor in pppaimt_doctors; others get Invalid User! / Account is disabled. */
export async function requestLoginOtp(input) { export async function requestLoginOtp(input) {
const email = normalizeEmail(input.email); const email = normalizeEmail(input.email);
const doctorName = await doctorNameFor(email); const doctorName = await doctorNameFor(email);

View File

@ -38,6 +38,8 @@ describe('bulk study email', () => {
afterEach(async () => { afterEach(async () => {
await server?.stop(); await server?.stop();
mailState.send.mockClear(); mailState.send.mockClear();
delete process.env.BULK_EMAIL_ALLOWLIST;
delete process.env.MAIL_FORCE_SEND;
await truncateTables(); await truncateTables();
}); });
@ -158,6 +160,7 @@ describe('bulk study email', () => {
await db('pppaimt_doctors').insert({ await db('pppaimt_doctors').insert({
email: 'new@example.com', email: 'new@example.com',
hcp_name: 'Dr New Doctor', hcp_name: 'Dr New Doctor',
status: 'active',
}); });
const [activeId] = await db('users').insert({ const [activeId] = await db('users').insert({
email: 'testdoc1@yopmail.com', email: 'testdoc1@yopmail.com',
@ -184,10 +187,18 @@ describe('bulk study email', () => {
const [doctorId] = await db('pppaimt_doctors').insert({ const [doctorId] = await db('pppaimt_doctors').insert({
email: 'testdoc1@yopmail.com', email: 'testdoc1@yopmail.com',
hcp_name: 'Dr Asha Rao', hcp_name: 'Dr Asha Rao',
status: 'active',
}); });
const [ameyId] = await db('pppaimt_doctors').insert({ const [ameyId] = await db('pppaimt_doctors').insert({
email: 'amey@stratawiz.com', email: 'amey@stratawiz.com',
hcp_name: 'Dr Amey', 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({ await db('survey_responses').insert({
application_id: applicationId, application_id: applicationId,
@ -225,6 +236,7 @@ describe('bulk study email', () => {
}); });
const rows = await db('email_campaign_recipients').orderBy('id', 'asc'); const rows = await db('email_campaign_recipients').orderBy('id', 'asc');
expect(rows).toHaveLength(3); 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 asha = rows.find((row) => row.to_email === 'testdoc1@yopmail.com');
const amey = rows.find((row) => row.to_email === 'amey@stratawiz.com'); const amey = rows.find((row) => row.to_email === 'amey@stratawiz.com');
const extra = rows.find((row) => row.to_email === 'new@example.com'); const extra = rows.find((row) => row.to_email === 'new@example.com');
@ -269,6 +281,10 @@ describe('bulk study email', () => {
}, },
}); });
expect(invitation.result).toMatchObject({ recipientCount: 3, status: 'logged' }); 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 () => { it('sends each personalized letter in one wave', async () => {
@ -287,8 +303,9 @@ describe('bulk study email', () => {
payload: { email: adminEmail, password }, payload: { email: adminEmail, password },
}); });
await db('pppaimt_doctors').insert([ await db('pppaimt_doctors').insert([
{ email: 'asha@example.com', hcp_name: 'Dr Asha Rao' }, { email: 'asha@example.com', hcp_name: 'Dr Asha Rao', status: 'active' },
{ email: 'new@example.com', hcp_name: 'Dr New Doctor' }, { email: 'new@example.com', hcp_name: 'Dr New Doctor', status: 'active' },
{ email: 'disabled@example.com', hcp_name: 'Dr Disabled', status: 'disabled' },
]); ]);
try { try {
@ -312,6 +329,7 @@ describe('bulk study email', () => {
expect(progress.result).toMatchObject({ recipientCount: 2, sentCount: 2, status: 'sent' }); expect(progress.result).toMatchObject({ recipientCount: 2, sentCount: 2, status: 'sent' });
expect(mailState.send).toHaveBeenCalledTimes(2); expect(mailState.send).toHaveBeenCalledTimes(2);
const sent = mailState.send.mock.calls.map((call) => ({ to: call[0].to, text: call[0].text })); 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(sent).toEqual(
expect.arrayContaining([ expect.arrayContaining([
expect.objectContaining({ to: 'asha@example.com', text: expect.stringContaining('Dear Dr Asha Rao,') }), expect.objectContaining({ to: 'asha@example.com', text: expect.stringContaining('Dear Dr Asha Rao,') }),
@ -322,4 +340,43 @@ describe('bulk study email', () => {
delete process.env.MAIL_FORCE_SEND; 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;
}
});
}); });

View File

@ -13,11 +13,11 @@ import {
import { truncateTables } from './truncate.js'; import { truncateTables } from './truncate.js';
const HEADER = const HEADER =
'Sr NO,TASKFORCE,ZBM Name,RBM Name,ABM Name,HQ,TM ID,TM Name,TM Mail ID,TM Mobile,HCP NAME,LEGACY_CODE,PCODE,SPECIALITY,CLASS,VENDORCODE,VENDORNAME,Email ID,Contact No'; 'Sr NO,TASKFORCE,ZBM Name,RBM Name,ABM Name,HQ,TM ID,TM Name,TM Mail ID,TM Mobile,HCP NAME,LEGACY_CODE,PCODE,SPECIALITY,CLASS,VENDORCODE,VENDORNAME,Email ID,Contact No,Status';
/** One CSV data row in the field team's format. */ /** One CSV data row in the field team's format. */
function line(srNo, name, email, contact = '9769283034') { function line(srNo, name, email, contact = '9769283034', status = 'active') {
return `${srNo},Respiratory 2,Shaikh Mohseen Ahmed,Satish Dhonde,Adityakumar Tiwari,mumbai western,014262,Salim Khan,salim.khan1@Cipla.com,9987944435,${name},CIP833167,011667437,Chest Physician,A+,100064617,${name},${email},${contact}`; return `${srNo},Respiratory 2,Shaikh Mohseen Ahmed,Satish Dhonde,Adityakumar Tiwari,mumbai western,014262,Salim Khan,salim.khan1@Cipla.com,9987944435,${name},CIP833167,011667437,Chest Physician,A+,100064617,${name},${email},${contact},${status}`;
} }
/** Parse and validate CSV text with the header row added. */ /** Parse and validate CSV text with the header row added. */
@ -49,6 +49,7 @@ describe('doctor CSV validation', () => {
vendor_name: 'Sandeep S Tilve', vendor_name: 'Sandeep S Tilve',
email: 'tilve@gmail.com', email: 'tilve@gmail.com',
contact_no: '9769283034', contact_no: '9769283034',
status: 'active',
}); });
}); });
@ -75,6 +76,26 @@ describe('doctor CSV validation', () => {
]); ]);
}); });
it('rejects missing or unknown Status values', async () => {
const result = await check([
line(1, 'Dr A', 'a@x.com', '9769283034', 'ACTIVE'),
line(2, 'Dr B', 'b@x.com', '9769283034', ''),
line(3, 'Dr C', 'c@x.com', '9769283034', 'paused'),
]);
expect(result.records.map((record) => record.email)).toEqual(['a@x.com']);
expect(result.records[0].status).toBe('active');
expect(result.invalid).toEqual([
{ row: 2, name: 'Dr B', email: 'b@x.com', reason: 'status is missing' },
{
row: 3,
name: 'Dr C',
email: 'c@x.com',
reason: 'status must be active or disabled (got "paused")',
},
]);
});
it('groups duplicate emails regardless of case', async () => { it('groups duplicate emails regardless of case', async () => {
const result = await check([ const result = await check([
line(1, 'Dr A', 'a@x.com'), line(1, 'Dr A', 'a@x.com'),
@ -146,6 +167,7 @@ describe('doctor CSV import', () => {
contact_no: '9000000000', contact_no: '9000000000',
tm_mail_id: 'salim.khan1@Cipla.com', tm_mail_id: 'salim.khan1@Cipla.com',
tm_mobile: '9987944435', tm_mobile: '9987944435',
status: 'active',
source_file: 'second.csv', source_file: 'second.csv',
}); });
expect(await doctorCount()).toBe(3); expect(await doctorCount()).toBe(3);

View File

@ -158,6 +158,37 @@ describe('user OTP auth', () => {
expect(verified.statusCode).toBe(403); expect(verified.statusCode).toBe(403);
}); });
it('refuses a disabled doctor with Account is disabled', async () => {
const api = await start();
const disabledEmail = 'disabled-doctor@example.com';
await db('pppaimt_doctors').insert({
email: disabledEmail,
hcp_name: 'Disabled Doctor',
status: 'disabled',
});
const requested = await api.inject({
method: 'POST',
url: '/api/auth/otp/request',
payload: { email: disabledEmail },
});
expect(requested.statusCode).toBe(403);
expect(requested.result.error.message).toBe('Account is disabled');
expect(await db('users').where({ email: disabledEmail }).first()).toBeUndefined();
expect(await db('login_otps').where({ email: disabledEmail }).first()).toBeUndefined();
expect(outbox).toHaveLength(0);
const verified = await api.inject({
method: 'POST',
url: '/api/auth/otp/verify',
payload: { email: disabledEmail, otp: '123456' },
});
expect(verified.statusCode).toBe(403);
expect(verified.result.error.message).toBe('Account is disabled');
});
it('fills the user and draft application name from HCP NAME without a leading Dr', async () => { it('fills the user and draft application name from HCP NAME without a leading Dr', async () => {
const api = await start(); const api = await start();
const doctorEmail = 'tilve@example.com'; const doctorEmail = 'tilve@example.com';

View File

@ -23,9 +23,16 @@ The webhook endpoint is `POST /api/webhooks/sendgrid`. In SendGrid, enable the s
| `SENDGRID_WEBHOOK_VERIFICATION_KEY` | Public key for the event webhook signature. | | `SENDGRID_WEBHOOK_VERIFICATION_KEY` | Public key for the event webhook signature. |
| `ADMIN_NOTIFY_EMAILS` | Comma-separated admin addresses notified when a physician submits. | | `ADMIN_NOTIFY_EMAILS` | Comma-separated admin addresses notified when a physician submits. |
| `APP_BASE_URL` | Public site origin used in resume, survey, and admin links. | | `APP_BASE_URL` | Public site origin used in resume, survey, and admin links. |
| `BULK_EMAIL_ALLOWLIST` | Optional. Comma-separated doctor emails for Admin → Send emails (invitation/reminder) local testing only. Unset or empty on the server so all active doctors are included. |
## Invitation and reminder (Admin → Send emails)
Invitation goes to every **active** doctor. Reminder goes to active doctors who still have a pending Login, Consent, Agreement, Approval, or Survey step. Disabled doctors are never included.
## Testing without delivery ## Testing without delivery
Set `SENDGRID_SANDBOX_MODE=true` with a real API key and `MAIL_FROM`. SendGrid validates the request and returns a message id, and the recipient does not receive the email. Set `SENDGRID_SANDBOX_MODE=true` with a real API key and `MAIL_FROM`. SendGrid validates the request and returns a message id, and the recipient does not receive the email.
With no `SENDGRID_API_KEY`, a development server logs the resume or survey URL and writes `email_log.status` as `logged`. With no `SENDGRID_API_KEY`, a development server logs the resume or survey URL and writes `email_log.status` as `logged`.
To preview or send invitation/reminder to a few addresses only (local), set `BULK_EMAIL_ALLOWLIST`, restart the API, then clear it again before any production-like send.

File diff suppressed because it is too large Load Diff

View File

@ -5,12 +5,13 @@ const TYPES = [
{ {
id: 'invitation', id: 'invitation',
label: 'Invitation email', label: 'Invitation email',
detail: 'Sent to every imported doctor.', detail: 'Sent to every active imported doctor.',
}, },
{ {
id: 'reminder', id: 'reminder',
label: 'Reminder email', label: 'Reminder email',
detail: 'Sent to imported doctors who still have Login, Consent, Agreement, Approval, or Survey pending.', detail:
'Sent to active imported doctors who still have Login, Consent, Agreement, Approval, or Survey pending.',
}, },
]; ];

View File

@ -119,4 +119,40 @@ describe('UserLoginPage', () => {
expect(screen.getByLabelText('Email')).toBeInTheDocument(); expect(screen.getByLabelText('Email')).toBeInTheDocument();
expect(screen.queryByLabelText('One-time code')).not.toBeInTheDocument(); expect(screen.queryByLabelText('One-time code')).not.toBeInTheDocument();
}); });
it('shows Account is disabled and stays on the email step for a disabled doctor', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async (path) => {
if (path === '/api/auth/otp/request') {
return {
ok: false,
status: 403,
json: async () => ({ error: { code: 'FORBIDDEN', message: 'Account is disabled' } }),
};
}
return {
ok: false,
status: 401,
json: async () => ({ error: { message: 'Authentication required' } }),
};
}),
);
render(
<MemoryRouter>
<UserLoginPage />
</MemoryRouter>,
);
fireEvent.change(await screen.findByLabelText('Email'), {
target: { value: 'disabled@example.com' },
});
fireEvent.click(screen.getByRole('button', { name: 'Send code' }));
expect(await screen.findByRole('alert')).toHaveTextContent('Account is disabled');
expect(screen.getByLabelText('Email')).toBeInTheDocument();
expect(screen.queryByLabelText('One-time code')).not.toBeInTheDocument();
});
}); });