Enhance audience management features with new components and API integrations

- Added `AssignCoursesModal`, `AudienceMemberRow`, `AudienceTable`, and related components for improved audience management UI.
- Implemented audience invite actions including resend and revoke functionality.
- Updated audience API to support importing members and assigning courses.
- Refactored audience data handling to include status and invite management.
- Improved overall user experience with pagination and selection features in the audience table.
This commit is contained in:
Rotimi Best
2026-03-22 18:42:23 +01:00
parent e9c4082f89
commit 3919ff6c2f
157 changed files with 13183 additions and 872 deletions
@@ -0,0 +1,531 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import type {
TAssignAudienceCourses,
TAudienceInviteByEmail,
TImportAudienceMembers
} from '@cio/utils/validation/organization';
import { addGroupMembers, enrollUsersInCourseGroups, getExistingGroupMembers } from '@cio/db/queries/group';
import { buildEmailFromName, sendEmail } from '@cio/email';
import {
checkEmailsExistInOrg,
createOrganizationInvite,
createOrganizationInviteAudits,
createOrganizationInvites,
createOrganizationMembers,
getLatestOrganizationInviteRowByOrgAndEmail,
getOrgMembersByProfileIds,
getOrganizationById,
getStudentOrganizationMemberByOrgAndEmail,
hasActiveOrganizationInviteForEmail,
revokeActiveOrganizationInvitesByEmails
} from '@cio/db/queries/organization';
import { getCourseGroupIds, getOrgCourseGroups, getOrgCourses } from '@cio/db/queries/course';
import { ROLE } from '@cio/utils/constants';
import crypto from 'node:crypto';
import { getDashboardBaseUrl } from '@api/config/dashboard-url';
import { getProfilesByEmails } from '@cio/db/queries/auth';
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const ORG_INVITE_EXPIRY_MS = 7 * 24 * 60 * 60 * 1000;
/** Parallel outbound invite emails; avoids sequential SMTP/API latency per recipient. */
const EMAIL_SEND_CONCURRENCY = 5;
async function mapWithConcurrency<T, R>(items: T[], concurrency: number, fn: (item: T) => Promise<R>): Promise<R[]> {
if (items.length === 0) {
return [];
}
const results: R[] = new Array(items.length);
let next = 0;
const workerCount = Math.min(concurrency, items.length);
const workers = Array.from({ length: workerCount }, async () => {
while (true) {
const i = next++;
if (i >= items.length) break;
results[i] = await fn(items[i]);
}
});
await Promise.all(workers);
return results;
}
function hashToken(token: string): string {
return crypto.createHash('sha256').update(token).digest('hex');
}
function generateToken(): string {
return crypto.randomBytes(32).toString('base64url');
}
function buildInviteLink(token: string): string {
return `${getDashboardBaseUrl()}/invite/${encodeURIComponent(token)}`;
}
function getExpiryLabel(expiresAtIso: string): string {
return new Date(expiresAtIso).toLocaleString('en-US', {
dateStyle: 'medium',
timeStyle: 'short',
timeZone: 'UTC'
});
}
function parseRecipientCsv(recipientCsv: string): string[] {
return recipientCsv
.split(/[\n,;\t ]+/g)
.map((value) => value.trim())
.filter(Boolean);
}
function getNormalizedRecipients(recipientCsv: string): {
valid: string[];
invalid: string[];
duplicates: string[];
} {
const raw = parseRecipientCsv(recipientCsv);
const seen = new Set<string>();
const valid: string[] = [];
const invalid: string[] = [];
const duplicates: string[] = [];
for (const recipient of raw) {
const normalized = recipient.toLowerCase().trim();
if (!normalized) continue;
if (!EMAIL_REGEX.test(normalized)) {
invalid.push(normalized);
continue;
}
if (seen.has(normalized)) {
duplicates.push(normalized);
continue;
}
seen.add(normalized);
valid.push(normalized);
}
return { valid, invalid, duplicates };
}
export async function importAudienceMembers(orgId: string, data: TImportAudienceMembers, invitedByProfileId: string) {
const organization = await getOrganizationById(orgId);
if (!organization || !organization.siteName) {
throw new AppError('Organization not found', ErrorCodes.ORGANIZATION_NOT_FOUND, 404);
}
const recipients = getNormalizedRecipients(data.recipientCsv);
if (recipients.invalid.length > 0) {
throw new AppError(
`Invalid emails found: ${recipients.invalid.slice(0, 5).join(', ')}`,
ErrorCodes.VALIDATION_ERROR,
400,
'recipientCsv'
);
}
if (recipients.valid.length === 0) {
throw new AppError('No valid emails provided', ErrorCodes.VALIDATION_ERROR, 400, 'recipientCsv');
}
const existingEmails = await checkEmailsExistInOrg(orgId, recipients.valid);
const emailsToImport = recipients.valid.filter((email) => !existingEmails.includes(email));
if (emailsToImport.length === 0) {
return {
imported: 0,
skipped: existingEmails.length,
duplicates: recipients.duplicates.length,
emailsSent: 0,
emailsFailed: 0
};
}
await createOrganizationMembers(
emailsToImport.map((email) => ({
organizationId: orgId,
email,
roleId: ROLE.STUDENT,
verified: false
}))
);
let courseIds: string[] = [];
let courseNames: string[] = [];
if (data.allCourses) {
const courses = await getOrgCourses({ orgId });
courseIds = courses.map((c) => c.id);
courseNames = courses.map((c) => c.title).filter(Boolean);
} else if (data.courseIds && data.courseIds.length > 0) {
const courses = await getOrgCourses({ orgId, courseIds: data.courseIds });
courseIds = courses.map((c) => c.id);
courseNames = courses.map((c) => c.title).filter(Boolean);
}
if (courseIds.length > 0) {
const courseGroupMappings = await getCourseGroupIds(courseIds);
const validGroupIds = courseGroupMappings.map((m) => m.groupId).filter(Boolean) as string[];
if (validGroupIds.length > 0) {
const profiles = await getProfilesByEmails(emailsToImport);
if (profiles.length > 0) {
const users = profiles.map((p) => ({ profileId: p.id, email: p.email ?? undefined }));
await enrollUsersInCourseGroups(validGroupIds, users, ROLE.STUDENT);
}
}
}
await revokeActiveOrganizationInvitesByEmails(orgId, emailsToImport, invitedByProfileId);
const expiresAt = new Date(Date.now() + ORG_INVITE_EXPIRY_MS).toISOString();
const courseNamesLabel = courseNames.length > 0 ? courseNames.join(', ') : undefined;
const inviteInputs = emailsToImport.map((email) => {
const token = generateToken();
return {
email,
token,
row: {
organizationId: orgId,
roleId: ROLE.STUDENT,
email,
tokenHash: hashToken(token),
createdByProfileId: invitedByProfileId,
expiresAt,
isRevoked: false,
metadata: {
source: 'AUDIENCE_IMPORT',
courseIds: courseIds.length > 0 ? courseIds : undefined
}
}
};
});
const invites = await createOrganizationInvites(inviteInputs.map((i) => i.row));
const inviteByEmail = new Map(invites.map((inv) => [inv.email.toLowerCase(), inv]));
const tokenByEmail = new Map(inviteInputs.map((i) => [i.email.toLowerCase(), i.token]));
await createOrganizationInviteAudits(
emailsToImport.map((email) => {
const invite = inviteByEmail.get(email)!;
return {
inviteId: invite.id,
organizationId: orgId,
eventType: 'CREATED' as const,
actorProfileId: invitedByProfileId,
targetEmail: email,
ipAddress: null,
userAgent: null,
metadata: {
roleId: ROLE.STUDENT,
roleName: 'Student',
expiresAt,
courseIds
}
};
})
);
let emailsSent = 0;
let emailsFailed = 0;
if (data.sendEmail) {
const emailOutcomes = await mapWithConcurrency(emailsToImport, EMAIL_SEND_CONCURRENCY, async (email) => {
const invite = inviteByEmail.get(email)!;
const token = tokenByEmail.get(email)!;
try {
const inviteLink = buildInviteLink(token);
const responses = await sendEmail('studentOrgInvite', {
to: email,
fields: {
email,
orgName: organization.name,
inviteLink,
expiresAt: getExpiryLabel(expiresAt),
courseNames: courseNamesLabel
},
from: buildEmailFromName(`${organization.name} (via ClassroomIO.com)`)
});
const allSuccessful = responses.every((r) => r.success);
if (allSuccessful) {
return {
inviteId: invite.id,
email,
success: true as const,
error: undefined as string | undefined
};
}
return {
inviteId: invite.id,
email,
success: false as const,
error: responses
.filter((r) => !r.success)
.map((r) => r.error || 'Unknown')
.join('; ')
};
} catch (emailError) {
const message = emailError instanceof Error ? emailError.message : 'Unknown email error';
return { inviteId: invite.id, email, success: false as const, error: message };
}
});
emailsSent = emailOutcomes.filter((o) => o.success).length;
emailsFailed = emailOutcomes.length - emailsSent;
await createOrganizationInviteAudits(
emailOutcomes.map((o) => ({
inviteId: o.inviteId,
organizationId: orgId,
eventType: o.success ? ('EMAIL_SENT' as const) : ('EMAIL_FAILED' as const),
actorProfileId: invitedByProfileId,
targetEmail: o.email,
ipAddress: null,
userAgent: null,
metadata: o.success ? {} : { error: o.error ?? 'Unknown' }
}))
);
}
return {
imported: emailsToImport.length,
skipped: existingEmails.length,
duplicates: recipients.duplicates.length,
emailsSent,
emailsFailed
};
}
export async function resendAudienceInvite(orgId: string, data: TAudienceInviteByEmail, invitedByProfileId: string) {
const organization = await getOrganizationById(orgId);
if (!organization || !organization.siteName) {
throw new AppError('Organization not found', ErrorCodes.ORGANIZATION_NOT_FOUND, 404);
}
const member = await getStudentOrganizationMemberByOrgAndEmail(orgId, data.email);
if (!member) {
throw new AppError('Audience member not found', ErrorCodes.VALIDATION_ERROR, 404, 'email');
}
if (member.profileId) {
throw new AppError('Member has already joined', ErrorCodes.VALIDATION_ERROR, 400, 'email');
}
const emailToUse = member.email.toLowerCase().trim();
const latestInvite = await getLatestOrganizationInviteRowByOrgAndEmail(orgId, emailToUse);
const meta = latestInvite?.metadata as { courseIds?: string[] } | undefined;
const courseIdsFromMetadata = meta?.courseIds?.filter(Boolean) ?? [];
let courseIds: string[] = [];
let courseNames: string[] = [];
if (courseIdsFromMetadata.length > 0) {
const courses = await getOrgCourses({ orgId, courseIds: courseIdsFromMetadata });
courseIds = courses.map((c) => c.id);
courseNames = courses.map((c) => c.title).filter(Boolean);
}
await revokeActiveOrganizationInvitesByEmails(orgId, [emailToUse], invitedByProfileId);
const expiresAt = new Date(Date.now() + ORG_INVITE_EXPIRY_MS).toISOString();
const token = generateToken();
const courseNamesLabel = courseNames.length > 0 ? courseNames.join(', ') : undefined;
const invite = await createOrganizationInvite({
organizationId: orgId,
roleId: ROLE.STUDENT,
email: emailToUse,
tokenHash: hashToken(token),
createdByProfileId: invitedByProfileId,
expiresAt,
isRevoked: false,
metadata: {
source: 'AUDIENCE_RESEND',
courseIds: courseIds.length > 0 ? courseIds : undefined
}
});
await createOrganizationInviteAudits([
{
inviteId: invite.id,
organizationId: orgId,
eventType: 'CREATED',
actorProfileId: invitedByProfileId,
targetEmail: emailToUse,
ipAddress: null,
userAgent: null,
metadata: {
roleId: ROLE.STUDENT,
roleName: 'Student',
expiresAt,
courseIds
}
}
]);
let emailSent = false;
try {
const inviteLink = buildInviteLink(token);
const responses = await sendEmail('studentOrgInvite', {
to: emailToUse,
fields: {
email: emailToUse,
orgName: organization.name,
inviteLink,
expiresAt: getExpiryLabel(expiresAt),
courseNames: courseNamesLabel
},
from: buildEmailFromName(`${organization.name} (via ClassroomIO.com)`)
});
const allSuccessful = responses.every((r) => r.success);
emailSent = allSuccessful;
await createOrganizationInviteAudits([
{
inviteId: invite.id,
organizationId: orgId,
eventType: allSuccessful ? 'EMAIL_SENT' : 'EMAIL_FAILED',
actorProfileId: invitedByProfileId,
targetEmail: emailToUse,
ipAddress: null,
userAgent: null,
metadata: allSuccessful
? {}
: {
error: responses
.filter((r) => !r.success)
.map((r) => r.error || 'Unknown')
.join('; ')
}
}
]);
} catch (emailError) {
const message = emailError instanceof Error ? emailError.message : 'Unknown email error';
await createOrganizationInviteAudits([
{
inviteId: invite.id,
organizationId: orgId,
eventType: 'EMAIL_FAILED',
actorProfileId: invitedByProfileId,
targetEmail: emailToUse,
ipAddress: null,
userAgent: null,
metadata: { error: message }
}
]);
}
return { emailSent };
}
export async function revokeAudiencePendingInvite(
orgId: string,
data: TAudienceInviteByEmail,
revokedByProfileId: string
) {
const member = await getStudentOrganizationMemberByOrgAndEmail(orgId, data.email);
if (!member) {
throw new AppError('Audience member not found', ErrorCodes.VALIDATION_ERROR, 404, 'email');
}
if (member.profileId) {
throw new AppError('Member has already joined', ErrorCodes.VALIDATION_ERROR, 400, 'email');
}
const emailToUse = member.email.toLowerCase().trim();
const hasActive = await hasActiveOrganizationInviteForEmail(orgId, emailToUse);
if (!hasActive) {
throw new AppError('No active pending invite to revoke', ErrorCodes.VALIDATION_ERROR, 400);
}
const revoked = await revokeActiveOrganizationInvitesByEmails(orgId, [emailToUse], revokedByProfileId);
if (revoked.length === 0) {
throw new AppError('No invite was revoked', ErrorCodes.VALIDATION_ERROR, 400);
}
await createOrganizationInviteAudits(
revoked.map((inv) => ({
inviteId: inv.id,
organizationId: orgId,
eventType: 'REVOKED' as const,
actorProfileId: revokedByProfileId,
targetEmail: emailToUse,
ipAddress: null,
userAgent: null,
metadata: { reason: 'audience_revoked_by_admin' }
}))
);
return { revoked: true };
}
export async function assignAudienceToCourses(orgId: string, data: TAssignAudienceCourses) {
const organization = await getOrganizationById(orgId);
if (!organization) {
throw new AppError('Organization not found', ErrorCodes.ORGANIZATION_NOT_FOUND, 404);
}
const orgMembers = await getOrgMembersByProfileIds(orgId, data.profileIds);
const validProfileIds = new Set(orgMembers.map((m) => m.profileId).filter(Boolean));
const profileEmailMap = new Map(orgMembers.filter((m) => m.profileId).map((m) => [m.profileId!, m.email ?? '']));
const courseGroups = await getOrgCourseGroups(orgId, data.courseIds);
if (courseGroups.length === 0) {
throw new AppError('No valid courses found', ErrorCodes.VALIDATION_ERROR, 400, 'courseIds');
}
const validGroupIds = courseGroups.map((cg) => cg.groupId).filter(Boolean) as string[];
const courseTitleByGroupId = new Map(courseGroups.map((cg) => [cg.groupId, cg.courseTitle]));
const validProfiles = data.profileIds.filter((id) => validProfileIds.has(id));
const pairs = validProfiles.flatMap((profileId) => validGroupIds.map((groupId) => ({ groupId, profileId })));
const existingSet = await getExistingGroupMembers(pairs);
const toInsert = pairs.filter((p) => !existingSet.has(`${p.groupId}:${p.profileId}`));
const alreadyEnrolled = pairs.length - toInsert.length;
if (toInsert.length > 0) {
await addGroupMembers(
toInsert.map((p) => ({
groupId: p.groupId,
roleId: ROLE.STUDENT,
profileId: p.profileId,
email: profileEmailMap.get(p.profileId) || undefined
}))
);
}
let emailsSent = 0;
if (data.sendEmail && toInsert.length > 0) {
const emailPromises = toInsert
.filter((p) => profileEmailMap.get(p.profileId))
.map(async (p) => {
const email = profileEmailMap.get(p.profileId)!;
try {
await sendEmail('studentCourseWelcome', {
to: email,
fields: {
orgName: organization.name,
courseName: courseTitleByGroupId.get(p.groupId) || 'Course'
},
from: buildEmailFromName(`${organization.name} (via ClassroomIO.com)`)
});
emailsSent++;
} catch (emailError) {
console.error(`assignAudienceToCourses email error for ${email}:`, emailError);
}
});
await Promise.all(emailPromises);
}
return {
assigned: toInsert.length,
alreadyEnrolled,
emailsSent
};
}