refactor(billing): system email + single-query backfill for the student cap (#735)
* refactor(billing): make student-limit email a system email; tighten backfill query
- Fetch free-plan orgs over the student limit in a single query
(getFreePlanOrganizationsOverStudentLimit) instead of loading all orgs and
counting each in memory; the backfill script now just fans out admin emails.
- Report a dry-run summary: how many free orgs are over the limit, how many
with admins, total admin emails, and how many were skipped for having none.
- Reclassify the student-limit email as a system (ClassroomIO-branded) email
rather than org-branded — it's the platform telling an admin about their
plan. Drop the `branding` field and org masthead/theme; both callers updated.
- Reword the email to explain why it's sent (new students are being turned
away) and that it's throttled to once a day, so it doesn't read as spam.
- Document the system-vs-org-branded email distinction in AGENTS.md.
* feat(billing): send student-limit emails on milestone crossings, once each
Stop emailing admins on every blocked attempt. Instead notify once when the
org crosses a student-count milestone:
- 50% of the limit → new studentLimitApproaching email (heads-up).
- 100% (limit reached) → studentLimitReached email.
Crossings are detected in assertStudentCapacityOrThrow on the allowed path
(blocked attempts no longer email). "Already notified" is persisted on
organization.settings.studentLimitNotified so each milestone fires at most
once, ever — surviving restarts, no per-day approximation. The backfill script
uses the same flag, making reruns idempotent (skips already-notified orgs and
marks them after sending). Email copy updated to explain the trigger and that
it's a one-time-per-milestone message.
* fix(email): use z.url() and drop the frequency footnotes on student-limit emails
Address PR review: `upgradeUrl` uses `z.url()`; remove the "once a day / once
per milestone" footnote lines from both the reached and approaching emails.
* set track={false}
This commit is contained in:
@@ -8,8 +8,9 @@ import type {
|
||||
TOrganization,
|
||||
TOrganizationPlan
|
||||
} from '@db/types';
|
||||
import { and, asc, count, desc, eq, ilike, inArray, isNotNull, or, sql } from 'drizzle-orm';
|
||||
import { and, asc, count, desc, eq, gt, ilike, inArray, isNotNull, notInArray, or, sql } from 'drizzle-orm';
|
||||
|
||||
import { PLAN } from '@cio/utils/plans';
|
||||
import { ROLE } from '@cio/utils/constants';
|
||||
import { db, type DbOrTxClient } from '@db/drizzle';
|
||||
import type { TAudienceSortBy, TAudienceSortOrder } from '@cio/utils/validation/organization';
|
||||
@@ -850,6 +851,43 @@ export const getOrganizations = async (filters?: {
|
||||
}));
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets free (BASIC) plan organizations whose active student count exceeds
|
||||
* `limit`, in a single query. Free = no active paid plan. Used by maintenance
|
||||
* jobs so they don't load every org (or every org's count) and filter in memory.
|
||||
*/
|
||||
export const getFreePlanOrganizationsOverStudentLimit = async (
|
||||
limit: number
|
||||
): Promise<Array<TOrganization & { studentCount: number }>> => {
|
||||
try {
|
||||
const paidPlans = [PLAN.EARLY_ADOPTER, PLAN.ENTERPRISE] as ('EARLY_ADOPTER' | 'ENTERPRISE')[];
|
||||
const paidOrgIds = db
|
||||
.select({ orgId: schema.organizationPlan.orgId })
|
||||
.from(schema.organizationPlan)
|
||||
.where(and(eq(schema.organizationPlan.isActive, true), inArray(schema.organizationPlan.planName, paidPlans)));
|
||||
|
||||
const studentCount = count(schema.organizationmember.id);
|
||||
const rows = await db
|
||||
.select({ organization: schema.organization, studentCount })
|
||||
.from(schema.organization)
|
||||
.innerJoin(
|
||||
schema.organizationmember,
|
||||
and(
|
||||
eq(schema.organizationmember.organizationId, schema.organization.id),
|
||||
eq(schema.organizationmember.roleId, ROLE.STUDENT)
|
||||
)
|
||||
)
|
||||
.where(notInArray(schema.organization.id, paidOrgIds))
|
||||
.groupBy(schema.organization.id)
|
||||
.having(gt(studentCount, limit));
|
||||
|
||||
return rows.map((row) => ({ ...(row.organization as TOrganization), studentCount: Number(row.studentCount) }));
|
||||
} catch (error) {
|
||||
console.error('getFreePlanOrganizationsOverStudentLimit error:', error);
|
||||
throw new Error('Failed to load free-plan organizations over the student limit');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the first (and typically only) organization - used for self-hosted single-org mode
|
||||
* @returns First organization by createdAt, or null if none exist
|
||||
|
||||
@@ -2009,6 +2009,10 @@ export const organization = pgTable(
|
||||
inviteOnly?: boolean;
|
||||
};
|
||||
internalEnrollmentOnly?: boolean;
|
||||
studentLimitNotified?: {
|
||||
half?: boolean;
|
||||
reached?: boolean;
|
||||
};
|
||||
}>(),
|
||||
landingpage: jsonb().default({}).$type<{
|
||||
header?: {
|
||||
|
||||
@@ -9,57 +9,76 @@
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
|
||||
import { buildEmailBranding, sendEmail } from '@cio/email';
|
||||
import { PLAN, getStudentLimit, isOrgOnFreePlan } from '@cio/utils/plans';
|
||||
import { sendEmail } from '@cio/email';
|
||||
import { PLAN, getStudentLimit } from '@cio/utils/plans';
|
||||
|
||||
import {
|
||||
countActiveStudents,
|
||||
getFreePlanOrganizationsOverStudentLimit,
|
||||
getOrganizationAdminEmails,
|
||||
getOrganizations
|
||||
updateOrganization
|
||||
} from '../queries/organization/organization';
|
||||
|
||||
async function main() {
|
||||
const execute = process.argv.includes('--execute');
|
||||
const orgs = await getOrganizations();
|
||||
const limit = getStudentLimit(PLAN.BASIC);
|
||||
const orgs = await getFreePlanOrganizationsOverStudentLimit(limit);
|
||||
|
||||
let notified = 0;
|
||||
let orgsToNotify = 0;
|
||||
let adminsToNotify = 0;
|
||||
let orgsOverWithoutAdmins = 0;
|
||||
let alreadyNotified = 0;
|
||||
|
||||
for (const org of orgs) {
|
||||
const isFree = isOrgOnFreePlan({ plans: org.plans, isSelfHosted: false, orgId: org.id });
|
||||
if (!isFree) continue;
|
||||
|
||||
const studentCount = await countActiveStudents(org.id);
|
||||
if (studentCount <= limit) continue;
|
||||
|
||||
const admins = await getOrganizationAdminEmails(org.id);
|
||||
if (!admins.length) {
|
||||
console.log(`Skipping ${org.name} (${org.id}): ${studentCount}/${limit} but no admin emails`);
|
||||
// Skip orgs already emailed the "reached" milestone (runtime or a prior run).
|
||||
if (org.settings?.studentLimitNotified?.reached) {
|
||||
alreadyNotified++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const admins = await getOrganizationAdminEmails(org.id);
|
||||
if (!admins.length) {
|
||||
orgsOverWithoutAdmins++;
|
||||
console.log(`Skipping ${org.name} (${org.id}): ${org.studentCount}/${limit} but no admin emails`);
|
||||
continue;
|
||||
}
|
||||
|
||||
orgsToNotify++;
|
||||
adminsToNotify += admins.length;
|
||||
|
||||
console.log(
|
||||
`${execute ? 'Notifying' : '[dry-run] Would notify'} ${org.name} (${org.id}): ${studentCount}/${limit} students → ${admins.length} admin(s)`
|
||||
`${execute ? 'Notifying' : '[dry-run] Would notify'} ${org.name} (${org.id}): ${org.studentCount}/${limit} students → ${admins.length} admin(s)`
|
||||
);
|
||||
|
||||
if (execute) {
|
||||
const branding = buildEmailBranding({ name: org.name, avatarUrl: org.avatarUrl, theme: org.theme });
|
||||
const upgradeUrl = `https://app.classroomio.com/org/${org.siteName ?? ''}?upgrade=true`;
|
||||
|
||||
await Promise.all(
|
||||
admins.map((admin) =>
|
||||
sendEmail('studentLimitReached', {
|
||||
to: admin.email,
|
||||
fields: { orgName: org.name, studentCount, studentLimit: limit, upgradeUrl, branding }
|
||||
fields: { orgName: org.name, studentCount: org.studentCount, studentLimit: limit, upgradeUrl }
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
notified++;
|
||||
await updateOrganization(org.id, {
|
||||
settings: { ...org.settings, studentLimitNotified: { half: true, reached: true } }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.log(execute ? `Done. Notified ${notified} org(s).` : 'Dry run complete — re-run with --execute to send.');
|
||||
console.log(
|
||||
`\nFound ${orgs.length} free-plan org(s) over the ${limit}-student limit: ` +
|
||||
`${orgsToNotify} to notify (${adminsToNotify} admin email(s) total)` +
|
||||
(alreadyNotified ? `, ${alreadyNotified} already notified` : '') +
|
||||
(orgsOverWithoutAdmins ? `, ${orgsOverWithoutAdmins} skipped for having no admins` : '') +
|
||||
'.'
|
||||
);
|
||||
console.log(
|
||||
execute
|
||||
? `Done. Sent ${adminsToNotify} email(s) across ${orgsToNotify} org(s).`
|
||||
: 'Dry run — no emails sent. Re-run with --execute to send.'
|
||||
);
|
||||
}
|
||||
|
||||
main()
|
||||
|
||||
@@ -27,6 +27,7 @@ export * from './session';
|
||||
export * from './submission-received';
|
||||
export * from './submission-graded';
|
||||
export * from './student-limit-reached';
|
||||
export * from './student-limit-approaching';
|
||||
|
||||
import type { newsfeedCommentEmail, newsfeedPostEmail } from './newsfeed';
|
||||
|
||||
@@ -46,6 +47,7 @@ import type { sessionReminderEmail, sessionUpdatedEmail } from './session';
|
||||
import type { submissionReceivedEmail } from './submission-received';
|
||||
import type { submissionGradedEmail } from './submission-graded';
|
||||
import type { studentLimitReachedEmail } from './student-limit-reached';
|
||||
import type { studentLimitApproachingEmail } from './student-limit-approaching';
|
||||
import type { teacherCourseWelcomeEmail } from './teacher-course-welcome';
|
||||
import type { teacherStudentBuyRequestEmail } from './teacher-student-buy-request';
|
||||
import type { teacherStudentJoinedEmail } from './teacher-student-joined';
|
||||
@@ -82,4 +84,5 @@ export type EmailSchemas = {
|
||||
submissionReceived: typeof submissionReceivedEmail.template.schema;
|
||||
submissionGraded: typeof submissionGradedEmail.template.schema;
|
||||
studentLimitReached: typeof studentLimitReachedEmail.template.schema;
|
||||
studentLimitApproaching: typeof studentLimitApproachingEmail.template.schema;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import * as z from 'zod';
|
||||
|
||||
import { defineEmail } from '../send';
|
||||
import { getDefaultTemplate } from '../templates';
|
||||
|
||||
export const studentLimitApproachingEmail = defineEmail({
|
||||
id: 'studentLimitApproaching',
|
||||
subject: "You're approaching your Free plan student limit",
|
||||
schema: z.object({
|
||||
orgName: z.string().min(1),
|
||||
studentCount: z.number(),
|
||||
studentLimit: z.number(),
|
||||
upgradeUrl: z.url()
|
||||
}),
|
||||
render: (fields) => {
|
||||
const content = `
|
||||
<p>Hi there,</p>
|
||||
<p><strong>${fields.orgName}</strong> now has ${fields.studentCount} of the ${fields.studentLimit} students included on the Free plan — about halfway to the limit. Once you reach it, new students can't enrol, accept invites, or be added until you upgrade.</p>
|
||||
<div>
|
||||
<a class="button" href="${fields.upgradeUrl}">Upgrade your plan</a>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return getDefaultTemplate(content);
|
||||
}
|
||||
});
|
||||
@@ -2,7 +2,6 @@ import * as z from 'zod';
|
||||
|
||||
import { defineEmail } from '../send';
|
||||
import { getDefaultTemplate } from '../templates';
|
||||
import { ZEmailBranding } from '../core/branding';
|
||||
|
||||
export const studentLimitReachedEmail = defineEmail({
|
||||
id: 'studentLimitReached',
|
||||
@@ -11,18 +10,17 @@ export const studentLimitReachedEmail = defineEmail({
|
||||
orgName: z.string().min(1),
|
||||
studentCount: z.number(),
|
||||
studentLimit: z.number(),
|
||||
upgradeUrl: z.string().url(),
|
||||
branding: ZEmailBranding
|
||||
upgradeUrl: z.url()
|
||||
}),
|
||||
render: (fields) => {
|
||||
const content = `
|
||||
<p>Hi there,</p>
|
||||
<p><strong>${fields.orgName}</strong> has reached the ${fields.studentLimit}-student limit on the Free plan (currently ${fields.studentCount} students). New students can't enrol or be invited until you upgrade.</p>
|
||||
<p><strong>${fields.orgName}</strong> has reached its Free plan limit of ${fields.studentLimit} students. From now on, new students can't enrol, accept invites, or be added until you upgrade.</p>
|
||||
<div>
|
||||
<a class="button" href="${fields.upgradeUrl}">Upgrade your plan</a>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return getDefaultTemplate(content, fields.branding);
|
||||
return getDefaultTemplate(content);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ export const EMAIL_IDS = [
|
||||
'submissionGraded',
|
||||
'submissionReceived',
|
||||
'studentLimitReached',
|
||||
'studentLimitApproaching',
|
||||
'studentCourseInvite',
|
||||
'studentCourseCompletion',
|
||||
'studentCourseWelcome',
|
||||
|
||||
Reference in New Issue
Block a user