From 4d273d8be7d6a231be4eaa02702b801ddf511fe7 Mon Sep 17 00:00:00 2001 From: Michael H Date: Mon, 16 Nov 2026 18:23:38 -0500 Subject: [PATCH 1/5] Add bulk application updates with email tracking --- .../src/clients/AgendaClient/Jobs/index.ts | 199 +++++ .../server/src/clients/AgendaClient/index.ts | 8 + .../server/src/controllers/ATSController.ts | 747 +++++++++++++++++- peopleportal/server/src/models/Application.ts | 2 + .../src/models/BulkApplicationUpdate.ts | 156 ++++ .../models/application-stage-transitions.ts | 31 + peopleportal/server/src/routes.ts | 170 ++++ .../bulk-application-updates.test.js | 318 ++++++++ .../fabric/DashboardTeamRecuitment.test.tsx | 111 ++- .../fabric/DashboardTeamRecuitment.tsx | 713 ++++++++++++++++- .../components/fabric/recruitment-queries.ts | 30 + 11 files changed, 2449 insertions(+), 36 deletions(-) create mode 100644 peopleportal/server/src/models/BulkApplicationUpdate.ts create mode 100644 peopleportal/server/src/models/application-stage-transitions.ts create mode 100644 peopleportal/server/test/integration/bulk-application-updates.test.js diff --git a/peopleportal/server/src/clients/AgendaClient/Jobs/index.ts b/peopleportal/server/src/clients/AgendaClient/Jobs/index.ts index 0a5a0c8f..bef36a08 100644 --- a/peopleportal/server/src/clients/AgendaClient/Jobs/index.ts +++ b/peopleportal/server/src/clients/AgendaClient/Jobs/index.ts @@ -10,6 +10,17 @@ import { HydratedDocument } from "mongoose"; import { ENABLED_SHARED_RESOURCES } from "../../../config"; import { SlackClient } from "../../SlackClient"; import { DiscordClient } from "../../DiscordClient"; +import { + Application, + ApplicationStage, +} from "../../../models/Application"; +import { + BulkApplicationRecipientStatus, + BulkApplicationUpdateJob, + BulkApplicationUpdateRecipient, + BulkApplicationUpdateStatus, +} from "../../../models/BulkApplicationUpdate"; +import { isValidApplicationStageTransition } from "../../../models/application-stage-transitions"; interface _JobData { jobName: string; @@ -147,6 +158,10 @@ export interface SendEventRemindersPayload extends JobPayload { eventId: string; } +export interface SendBulkApplicationUpdatesPayload extends JobPayload { + jobId: string; +} + // Define Agenda jobs here export const DefinedJobs: Record< string, @@ -311,6 +326,190 @@ export const DefinedJobs: Record< removeOnComplete: true, // Frees space by removing job from MongoDB on completion }, }, + + sendBulkApplicationUpdates: { + workerFunction: async ( + job: Job, + ) => { + const bulkJob = await BulkApplicationUpdateJob.findById( + job.attrs.data.jobId, + ).exec(); + if (!bulkJob) { + throw new Error( + `Bulk application update job ${job.attrs.data.jobId} was not found`, + ); + } + + bulkJob.status = BulkApplicationUpdateStatus.PROCESSING; + await bulkJob.save(); + + const recipients = await BulkApplicationUpdateRecipient.find({ + jobId: bulkJob._id, + status: { + $in: [ + BulkApplicationRecipientStatus.PENDING, + BulkApplicationRecipientStatus.PROCESSING, + ], + }, + }) + .sort({ createdAt: 1 }) + .exec(); + const emailClient = new EmailClient(); + + for (const recipient of recipients) { + recipient.status = BulkApplicationRecipientStatus.PROCESSING; + recipient.attempts += 1; + recipient.error = undefined; + recipient.failurePhase = undefined; + await recipient.save(); + + try { + if (!recipient.stageChangedAt) { + const application = await Application.findOne({ + _id: recipient.applicationId, + teamPk: bulkJob.teamPk, + }).exec(); + + if (!application) { + throw new Error( + "Application no longer exists in this team", + ); + } + + const existingBulkTransition = + application.stageHistory.find( + (entry) => + entry.bulkJobId === + bulkJob._id.toString(), + ); + if ( + application.stage === recipient.targetStage && + existingBulkTransition + ) { + recipient.stageChangedAt = + existingBulkTransition.changedAt; + } else { + if ( + !recipient.previousStage || + application.stage !== + recipient.previousStage || + !isValidApplicationStageTransition( + application.stage, + recipient.targetStage, + ) + ) { + throw new Error( + "Application stage changed after this batch was submitted", + ); + } + + const changedAt = new Date(); + application.stage = recipient.targetStage; + application.stageHistory.push({ + stage: recipient.targetStage, + changedAt, + changedBy: `${bulkJob.requestedByName} (${bulkJob.requestedByUsername})`, + bulkJobId: bulkJob._id.toString(), + }); + await application.save(); + recipient.stageChangedAt = changedAt; + } + await recipient.save(); + } + + if (!recipient.email || !recipient.applicantName) { + throw new Error( + "Applicant contact information is unavailable", + ); + } + + if (recipient.targetStage === ApplicationStage.INTERVIEW) { + await emailClient.send({ + to: recipient.email, + cc: [bulkJob.requestedByEmail], + replyTo: [bulkJob.requestedByEmail], + subject: `Next Steps: ${bulkJob.teamName} Interview`, + templateName: "RecruitInterviewRequest", + templateVars: { + applicantName: recipient.applicantName, + interviewerName: bulkJob.requestedByName, + teamName: bulkJob.teamName, + interviewLink: bulkJob.interviewLink, + interviewGuidelines: + bulkJob.interviewGuidelines, + }, + }); + } else if ( + recipient.targetStage === ApplicationStage.REJECTED + ) { + await emailClient.send({ + to: recipient.email, + cc: [bulkJob.requestedByEmail], + replyTo: [bulkJob.requestedByEmail], + subject: `Update on ${bulkJob.teamName}`, + templateName: "RecruitApplicationDeclined", + templateVars: { + applicantName: recipient.applicantName, + teamName: bulkJob.teamName, + }, + }); + } else { + throw new Error( + `No bulk email template is available for ${recipient.targetStage}`, + ); + } + + recipient.status = BulkApplicationRecipientStatus.SENT; + recipient.failurePhase = undefined; + recipient.error = undefined; + recipient.sentAt = new Date(); + await recipient.save(); + } catch (error: unknown) { + recipient.status = BulkApplicationRecipientStatus.FAILED; + recipient.failurePhase = recipient.stageChangedAt + ? "email" + : "stage"; + recipient.error = + error instanceof Error + ? error.message + : "Unknown recipient processing error"; + await recipient.save(); + } + } + + const remainingRecipients = + await BulkApplicationUpdateRecipient.countDocuments({ + jobId: bulkJob._id, + status: { + $in: [ + BulkApplicationRecipientStatus.PENDING, + BulkApplicationRecipientStatus.PROCESSING, + ], + }, + }).exec(); + const unsuccessfulRecipients = + await BulkApplicationUpdateRecipient.countDocuments({ + jobId: bulkJob._id, + status: { + $in: [ + BulkApplicationRecipientStatus.FAILED, + BulkApplicationRecipientStatus.VALIDATION_FAILED, + ], + }, + }).exec(); + + bulkJob.status = remainingRecipients + ? BulkApplicationUpdateStatus.QUEUED + : unsuccessfulRecipients + ? BulkApplicationUpdateStatus.COMPLETED_WITH_ERRORS + : BulkApplicationUpdateStatus.COMPLETED; + await bulkJob.save(); + }, + options: { + concurrency: 1, + removeOnComplete: true, + }, + }, }; // Define any static, repeating jobs here diff --git a/peopleportal/server/src/clients/AgendaClient/index.ts b/peopleportal/server/src/clients/AgendaClient/index.ts index 80e2d185..d6ebaa36 100644 --- a/peopleportal/server/src/clients/AgendaClient/index.ts +++ b/peopleportal/server/src/clients/AgendaClient/index.ts @@ -21,6 +21,13 @@ import { Agenda } from "agenda"; import { MongoBackend } from "@agendajs/mongo-backend"; import { DefinedJobs, JobSchedulingData, RecurringJobs } from "./Jobs"; +// Agenda exports this channel at runtime but omits it from its root type declarations. +const { InMemoryNotificationChannel } = require("agenda") as { + InMemoryNotificationChannel: new () => Parameters< + Agenda["notifyVia"] + >[0]; +}; + export class AgendaClient { private static readonly TAG = "AgendaClient"; private agenda: Agenda | undefined; @@ -41,6 +48,7 @@ export class AgendaClient { mongo: mongoose.connection.db!, }), processEvery: dbQueryInterval, + notificationChannel: new InMemoryNotificationChannel(), }); // Define all jobs diff --git a/peopleportal/server/src/controllers/ATSController.ts b/peopleportal/server/src/controllers/ATSController.ts index 1d3a0902..09bb43c8 100644 --- a/peopleportal/server/src/controllers/ATSController.ts +++ b/peopleportal/server/src/controllers/ATSController.ts @@ -47,8 +47,16 @@ import { IApplication, ApplicationStage, } from "../models/Application"; +import { + BulkApplicationRecipientStatus, + BulkApplicationUpdateJob, + BulkApplicationUpdateRecipient, + BulkApplicationUpdateStatus, +} from "../models/BulkApplicationUpdate"; +import { isValidApplicationStageTransition } from "../models/application-stage-transitions"; import { Security } from "tsoa"; import * as express from "express"; +import { Types } from "mongoose"; import path from "path"; import { PutObjectCommand, @@ -61,6 +69,7 @@ import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; import { s3Client, BUCKET_NAME } from "../clients/AWSClient/S3Client"; import { Query } from "tsoa"; import { EmailClient } from "../clients/EmailClient"; +import { agendaClient } from "../clients/AgendaClient"; import { OrgController } from "./OrgController"; import { BindleController } from "./BindleController"; import { AuthorizedUser } from "../clients/OpenIdClient"; @@ -108,6 +117,13 @@ interface ATSUpdateApplicationStageRequest { hiredSubteamPk?: string; } +interface ATSBulkApplicationUpdateRequest { + applicationIds: string[]; + stage: ApplicationStage; + interviewLink?: string; + interviewGuidelines?: string; +} + interface ATSKanbanApplicationCard { id: string; applicantId: string; @@ -122,6 +138,11 @@ interface ATSKanbanApplicationCard { * @maximum 5 Maximum Stars is 5 */ stars: number; + latestEmailUpdate?: { + stage: ApplicationStage; + status: BulkApplicationRecipientStatus; + updatedAt: Date; + }; } interface ATSApplicationDetails extends ATSKanbanApplicationCard { @@ -136,6 +157,15 @@ interface ATSApplicationDetails extends ATSKanbanApplicationCard { hiredRole?: string; appDevInternalPk?: number; notes?: string; + emailUpdates: { + jobId: string; + stage: ApplicationStage; + status: BulkApplicationRecipientStatus; + attempts: number; + createdAt: Date; + sentAt?: Date; + error?: string; + }[]; } // Constants @@ -774,17 +804,55 @@ export class ATSController extends Controller { .lean() .exec(); + const applicationIds = applications.map((app) => + app._id.toString(), + ); + const recentUpdates = await BulkApplicationUpdateRecipient.find({ + teamPk: teamId, + applicationId: { $in: applicationIds }, + }) + .sort({ createdAt: -1, _id: -1 }) + .select("applicationId targetStage status updatedAt") + .lean() + .exec(); + const latestUpdateByApplication = new Map< + string, + (typeof recentUpdates)[number] + >(); + for (const update of recentUpdates) { + if (!latestUpdateByApplication.has(update.applicationId)) { + latestUpdateByApplication.set( + update.applicationId, + update, + ); + } + } + // Map to Kanban-friendly format const kanbanData: ATSKanbanApplicationCard[] = applications.map( - (app) => ({ - id: app._id.toString(), - applicantId: app.applicantId._id.toString(), - name: app.applicantId.fullName || "Unknown Applicant", - stage: app.stage, - rolePreferences: app.rolePreferences, - appliedAt: app.appliedAt, - stars: app.stars || 0, - }), + (app) => { + const latestUpdate = latestUpdateByApplication.get( + app._id.toString(), + ); + return { + id: app._id.toString(), + applicantId: app.applicantId._id.toString(), + name: app.applicantId.fullName || "Unknown Applicant", + stage: app.stage, + rolePreferences: app.rolePreferences, + appliedAt: app.appliedAt, + stars: app.stars || 0, + ...(latestUpdate + ? { + latestEmailUpdate: { + stage: latestUpdate.targetStage, + status: latestUpdate.status, + updatedAt: latestUpdate.updatedAt, + }, + } + : {}), + }; + }, ); return kanbanData; @@ -827,6 +895,18 @@ export class ATSController extends Controller { return { error: "NotFound", message: "Application not found" }; } + const emailUpdates = + await BulkApplicationUpdateRecipient.find({ + teamPk: teamId, + applicationId: app._id.toString(), + }) + .sort({ createdAt: -1, _id: -1 }) + .select( + "jobId targetStage status attempts createdAt sentAt error", + ) + .lean() + .exec(); + return { id: app._id.toString(), applicantId: app.applicantId._id.toString(), @@ -841,6 +921,15 @@ export class ATSController extends Controller { profile: app.applicantId.profile as any, responses: app.responses as any, stageHistory: app.stageHistory, + emailUpdates: emailUpdates.map((update) => ({ + jobId: update.jobId.toString(), + stage: update.targetStage, + status: update.status, + attempts: update.attempts, + createdAt: update.createdAt, + ...(update.sentAt ? { sentAt: update.sentAt } : {}), + ...(update.error ? { error: update.error } : {}), + })), ...(app.notes ? { notes: app.notes } : {}), ...(app.hiredRole ? { hiredRole: app.hiredRole } : {}), ...(app.appDevInternalPk @@ -1158,26 +1247,7 @@ export class ATSController extends Controller { } // Transition Validation - const VALID_TRANSITIONS: Record = { - [ApplicationStage.APPLIED]: [ - ApplicationStage.INTERVIEW, - ApplicationStage.REJECTED, - ], - [ApplicationStage.INTERVIEW]: [ - ApplicationStage.POTENTIAL_HIRE, - ApplicationStage.HIRED, - ApplicationStage.REJECTED, - ], - [ApplicationStage.POTENTIAL_HIRE]: [ - ApplicationStage.HIRED, - ApplicationStage.REJECTED, - ], - [ApplicationStage.HIRED]: [], - [ApplicationStage.REJECTED]: [], - }; - - const allowed = VALID_TRANSITIONS[currentStage] || []; - if (!allowed.includes(stage)) { + if (!isValidApplicationStageTransition(currentStage, stage)) { this.setStatus(400); return { error: "BadRequest", @@ -1312,6 +1382,625 @@ export class ATSController extends Controller { } } + /** + * Creates a persistent batch stage-change job. Interview and Rejected are + * the only bulk stages with applicant-facing status templates. + */ + @Post("applications/{teamId}/bulk-updates") + @Tags("Recruitment Actions") + @SuccessResponse(201, "Bulk application update created") + @Security("bindles", ["corp:hiringaccess"]) + async createBulkApplicationUpdate( + @Request() req: express.Request, + @Path() teamId: string, + @Body() body: ATSBulkApplicationUpdateRequest, + ) { + if (!req.session?.authorizedUser) { + this.setStatus(401); + return { + error: "Unauthorized", + message: "Authenticated user not found", + }; + } + + if ( + !Array.isArray(body.applicationIds) || + body.applicationIds.length === 0 || + body.applicationIds.length > 100 || + body.applicationIds.some( + (applicationId) => + typeof applicationId !== "string" || + applicationId.trim() === "", + ) + ) { + this.setStatus(400); + return { + error: "BadRequest", + message: + "Provide between 1 and 100 non-empty application IDs", + }; + } + + if ( + body.stage !== ApplicationStage.INTERVIEW && + body.stage !== ApplicationStage.REJECTED + ) { + this.setStatus(400); + return { + error: "BadRequest", + message: + "Bulk email stage updates are available only for Interview and Rejected", + }; + } + + const interviewLink = body.interviewLink?.trim(); + const interviewGuidelines = body.interviewGuidelines?.trim(); + if ( + body.stage === ApplicationStage.INTERVIEW && + (!interviewLink || + !interviewGuidelines || + interviewGuidelines.length < 50 || + interviewGuidelines.length > 500) + ) { + this.setStatus(400); + return { + error: "BadRequest", + message: + "Interview link and 50-500 character interview guidelines are required", + }; + } + if (body.stage === ApplicationStage.INTERVIEW) { + let parsedInterviewLink: URL; + try { + parsedInterviewLink = new URL(interviewLink!); + } catch { + this.setStatus(400); + return { + error: "BadRequest", + message: "Interview link must be a valid HTTP(S) URL", + }; + } + if ( + parsedInterviewLink.protocol !== "http:" && + parsedInterviewLink.protocol !== "https:" + ) { + this.setStatus(400); + return { + error: "BadRequest", + message: "Interview link must be a valid HTTP(S) URL", + }; + } + } + + const uniqueApplicationIds = Array.from( + new Set(body.applicationIds.map((id) => id.trim())), + ); + const authorizedUser = req.session.authorizedUser; + try { + const teamInfo = await this.getAuthorizedHiringTeam( + authorizedUser, + teamId, + ); + if (!teamInfo) { + this.setStatus(403); + return { + error: "Forbidden", + message: "You do not have hiring access to this team", + }; + } + + const validIds = uniqueApplicationIds.filter((id) => + Types.ObjectId.isValid(id), + ); + const applications = validIds.length + ? await Application.find({ + _id: { $in: validIds }, + teamPk: teamId, + }) + .populate<{ applicantId: IApplicant | null }>( + "applicantId", + "fullName email", + ) + .exec() + : []; + const applicationsById = new Map( + applications.map((application) => [ + application._id.toString(), + application, + ]), + ); + + const job = await BulkApplicationUpdateJob.create({ + teamPk: teamId, + teamName: teamInfo.attributes.friendlyName || teamInfo.name, + targetStage: body.stage, + ...(body.stage === ApplicationStage.INTERVIEW + ? { + interviewLink, + interviewGuidelines, + } + : {}), + requestedByName: authorizedUser.name, + requestedByEmail: authorizedUser.email, + requestedByUsername: authorizedUser.username, + status: BulkApplicationUpdateStatus.QUEUED, + }); + + const recipients = uniqueApplicationIds.map((applicationId) => { + const application = applicationsById.get(applicationId); + if (!application) { + return { + jobId: job._id, + teamPk: teamId, + applicationId, + targetStage: body.stage, + status: + BulkApplicationRecipientStatus.VALIDATION_FAILED, + error: "Application not found for this team", + attempts: 0, + }; + } + + const applicant = application.applicantId; + let validationError: string | undefined; + if (!applicant || !applicant.email || !applicant.fullName) { + validationError = + "Applicant name or email is unavailable"; + } else if (application.stage === body.stage) { + validationError = `Application is already in ${body.stage}`; + } else if ( + !isValidApplicationStageTransition( + application.stage, + body.stage, + ) + ) { + validationError = `Invalid transition from ${application.stage} to ${body.stage}`; + } + + return { + jobId: job._id, + teamPk: teamId, + applicationId, + ...(applicant + ? { + applicantId: applicant._id.toString(), + applicantName: applicant.fullName, + email: applicant.email, + } + : {}), + previousStage: application.stage, + targetStage: body.stage, + status: validationError + ? BulkApplicationRecipientStatus.VALIDATION_FAILED + : BulkApplicationRecipientStatus.PENDING, + ...(validationError ? { error: validationError } : {}), + attempts: 0, + }; + }); + + await BulkApplicationUpdateRecipient.insertMany(recipients); + const queuedRecipients = recipients.filter( + (recipient) => + recipient.status === + BulkApplicationRecipientStatus.PENDING, + ).length; + const validationFailedRecipients = + recipients.length - queuedRecipients; + + if (queuedRecipients === 0) { + job.status = BulkApplicationUpdateStatus.COMPLETED_WITH_ERRORS; + await job.save(); + this.setStatus(201); + return { + jobId: job._id.toString(), + status: job.status, + queued: false, + queuedRecipients, + validationFailedRecipients, + }; + } + + try { + await agendaClient.scheduleJobOnce({ + runAt: new Date(), + jobName: "sendBulkApplicationUpdates", + jobPayload: { jobId: job._id.toString() }, + }); + } catch (error: unknown) { + const message = + error instanceof Error + ? error.message + : "Unknown background queue error"; + await BulkApplicationUpdateRecipient.updateMany( + { + jobId: job._id, + status: BulkApplicationRecipientStatus.PENDING, + }, + { + $set: { + status: BulkApplicationRecipientStatus.FAILED, + failurePhase: "queue", + error: `Could not schedule email job: ${message}`, + }, + }, + ).exec(); + job.status = BulkApplicationUpdateStatus.COMPLETED_WITH_ERRORS; + await job.save(); + console.error("Failed to schedule bulk application update", error); + this.setStatus(503); + return { + error: "QueueUnavailable", + message: + "The batch was saved but could not be queued. Retry it from batch history.", + jobId: job._id.toString(), + status: job.status, + queued: false, + queuedRecipients: 0, + validationFailedRecipients, + }; + } + + this.setStatus(201); + return { + jobId: job._id.toString(), + status: job.status, + queued: true, + queuedRecipients, + validationFailedRecipients, + }; + } catch (error: unknown) { + console.error("Error creating bulk application update:", error); + this.setStatus(500); + return { + error: "ServerError", + message: "Failed to create bulk application update", + }; + } + } + + /** + * Lists recent persisted batch jobs so a recruiter can resume monitoring + * after leaving the page or signing in on another device. + */ + @Get("applications/{teamId}/bulk-updates") + @Tags("Recruitment Actions") + @SuccessResponse(200) + @Security("bindles", ["corp:hiringaccess"]) + async getBulkApplicationUpdates( + @Request() req: express.Request, + @Path() teamId: string, + ) { + try { + if (!req.session?.authorizedUser) { + this.setStatus(401); + return { + error: "Unauthorized", + message: "Authenticated user not found", + }; + } + const teamInfo = await this.getAuthorizedHiringTeam( + req.session.authorizedUser, + teamId, + ); + if (!teamInfo) { + this.setStatus(403); + return { + error: "Forbidden", + message: "You do not have hiring access to this team", + }; + } + + const jobs = await BulkApplicationUpdateJob.find({ + teamPk: teamId, + }) + .sort({ createdAt: -1 }) + .limit(20) + .exec(); + if (!jobs.length) return []; + + const groupedCounts = + await BulkApplicationUpdateRecipient.aggregate<{ + _id: { + jobId: Types.ObjectId; + status: BulkApplicationRecipientStatus; + }; + count: number; + }>([ + { + $match: { + jobId: { $in: jobs.map((job) => job._id) }, + }, + }, + { + $group: { + _id: { jobId: "$jobId", status: "$status" }, + count: { $sum: 1 }, + }, + }, + ]).exec(); + const countsByJob = new Map< + string, + Record + >(); + for (const row of groupedCounts) { + const jobId = row._id.jobId.toString(); + const counts = countsByJob.get(jobId) ?? {}; + counts[row._id.status] = row.count; + countsByJob.set(jobId, counts); + } + + return jobs.map((job) => { + const counts = countsByJob.get(job._id.toString()) ?? {}; + const total = Object.values(counts).reduce( + (sum, count) => sum + count, + 0, + ); + return { + jobId: job._id.toString(), + targetStage: job.targetStage, + status: job.status, + createdAt: job.createdAt, + counts: { + total, + pending: + counts[BulkApplicationRecipientStatus.PENDING] ?? + 0, + processing: + counts[ + BulkApplicationRecipientStatus.PROCESSING + ] ?? 0, + sent: counts[BulkApplicationRecipientStatus.SENT] ?? 0, + failed: + counts[BulkApplicationRecipientStatus.FAILED] ?? 0, + validationFailed: + counts[ + BulkApplicationRecipientStatus + .VALIDATION_FAILED + ] ?? 0, + }, + }; + }); + } catch (error: unknown) { + console.error("Error fetching bulk application updates:", error); + this.setStatus(500); + return { + error: "ServerError", + message: "Failed to fetch bulk application updates", + }; + } + } + + /** + * Returns a batch and its individual recipient outcomes. + */ + @Get("applications/{teamId}/bulk-updates/{jobId}") + @Tags("Recruitment Actions") + @SuccessResponse(200) + @Security("bindles", ["corp:hiringaccess"]) + async getBulkApplicationUpdate( + @Request() req: express.Request, + @Path() teamId: string, + @Path() jobId: string, + ) { + if (!req.session?.authorizedUser) { + this.setStatus(401); + return { + error: "Unauthorized", + message: "Authenticated user not found", + }; + } + if (!Types.ObjectId.isValid(jobId)) { + this.setStatus(404); + return { error: "NotFound", message: "Batch job not found" }; + } + + try { + const teamInfo = await this.getAuthorizedHiringTeam( + req.session.authorizedUser, + teamId, + ); + if (!teamInfo) { + this.setStatus(403); + return { + error: "Forbidden", + message: "You do not have hiring access to this team", + }; + } + + const job = await BulkApplicationUpdateJob.findOne({ + _id: jobId, + teamPk: teamId, + }).exec(); + if (!job) { + this.setStatus(404); + return { error: "NotFound", message: "Batch job not found" }; + } + + const recipients = await BulkApplicationUpdateRecipient.find({ + jobId: job._id, + }) + .sort({ createdAt: 1 }) + .select( + "applicationId applicantName email previousStage targetStage status failurePhase error attempts stageChangedAt sentAt createdAt", + ) + .lean() + .exec(); + + return { + jobId: job._id.toString(), + targetStage: job.targetStage, + status: job.status, + createdAt: job.createdAt, + recipients: recipients.map((recipient) => ({ + applicationId: recipient.applicationId, + applicantName: recipient.applicantName ?? "Unknown applicant", + email: recipient.email, + previousStage: recipient.previousStage, + targetStage: recipient.targetStage, + status: recipient.status, + failurePhase: recipient.failurePhase, + error: recipient.error, + attempts: recipient.attempts, + stageChangedAt: recipient.stageChangedAt, + sentAt: recipient.sentAt, + createdAt: recipient.createdAt, + })), + }; + } catch (error: unknown) { + console.error("Error fetching bulk application update:", error); + this.setStatus(500); + return { + error: "ServerError", + message: "Failed to fetch bulk application update", + }; + } + } + + /** + * Requeues failed email sends and batches that could not be scheduled. + * Validation and stage-transition failures are not retryable. + */ + @Post("applications/{teamId}/bulk-updates/{jobId}/retry") + @Tags("Recruitment Actions") + @SuccessResponse(202, "Eligible recipients queued for retry") + @Security("bindles", ["corp:hiringaccess"]) + async retryBulkApplicationUpdate( + @Request() req: express.Request, + @Path() teamId: string, + @Path() jobId: string, + ) { + if (!req.session?.authorizedUser) { + this.setStatus(401); + return { + error: "Unauthorized", + message: "Authenticated user not found", + }; + } + if (!Types.ObjectId.isValid(jobId)) { + this.setStatus(404); + return { error: "NotFound", message: "Batch job not found" }; + } + + try { + const teamInfo = await this.getAuthorizedHiringTeam( + req.session.authorizedUser, + teamId, + ); + if (!teamInfo) { + this.setStatus(403); + return { + error: "Forbidden", + message: "You do not have hiring access to this team", + }; + } + + const job = await BulkApplicationUpdateJob.findOne({ + _id: jobId, + teamPk: teamId, + }).exec(); + if (!job) { + this.setStatus(404); + return { error: "NotFound", message: "Batch job not found" }; + } + + const retryableRecipients = + await BulkApplicationUpdateRecipient.find({ + jobId: job._id, + status: BulkApplicationRecipientStatus.FAILED, + $or: [ + { + failurePhase: "email", + stageChangedAt: { $ne: null }, + }, + { failurePhase: "queue" }, + ], + }).exec(); + if (!retryableRecipients.length) { + this.setStatus(409); + return { + error: "NoRetryableRecipients", + message: "This batch has no eligible failed recipients to retry", + }; + } + + const retryableRecipientIds = retryableRecipients.map( + (recipient) => recipient._id.toString(), + ); + const requeued = + await BulkApplicationUpdateRecipient.updateMany( + { + _id: { $in: retryableRecipientIds }, + status: BulkApplicationRecipientStatus.FAILED, + }, + { + $set: { + status: BulkApplicationRecipientStatus.PENDING, + }, + $unset: { error: 1, failurePhase: 1 }, + }, + ).exec(); + if (requeued.modifiedCount === 0) { + this.setStatus(409); + return { + error: "NoRetryableRecipients", + message: + "The failed recipients have already been retried", + }; + } + job.status = BulkApplicationUpdateStatus.QUEUED; + await job.save(); + + try { + await agendaClient.scheduleJobOnce({ + runAt: new Date(), + jobName: "sendBulkApplicationUpdates", + jobPayload: { jobId: job._id.toString() }, + }); + } catch (error: unknown) { + const message = + error instanceof Error + ? error.message + : "Unknown background queue error"; + await BulkApplicationUpdateRecipient.updateMany( + { + _id: { $in: retryableRecipientIds }, + status: BulkApplicationRecipientStatus.PENDING, + }, + { + $set: { + status: BulkApplicationRecipientStatus.FAILED, + failurePhase: "queue", + error: `Could not schedule email retry: ${message}`, + }, + }, + ).exec(); + job.status = BulkApplicationUpdateStatus.COMPLETED_WITH_ERRORS; + await job.save(); + console.error("Failed to schedule bulk application retry", error); + this.setStatus(503); + return { + error: "QueueUnavailable", + message: "The retry could not be queued", + jobId: job._id.toString(), + }; + } + + this.setStatus(202); + return { + jobId: job._id.toString(), + queuedRecipients: requeued.modifiedCount, + status: job.status, + }; + } catch (error: unknown) { + console.error("Error retrying bulk application update:", error); + this.setStatus(500); + return { + error: "ServerError", + message: "Failed to retry bulk application update", + }; + } + } + /** * Fetches all the other teams the applicant has applied to and the * stage they're currently in for those teams. To access this, the diff --git a/peopleportal/server/src/models/Application.ts b/peopleportal/server/src/models/Application.ts index 168fe1f6..64762834 100644 --- a/peopleportal/server/src/models/Application.ts +++ b/peopleportal/server/src/models/Application.ts @@ -37,6 +37,7 @@ export interface IApplication extends Document { stage: ApplicationStage; changedAt: Date; changedBy?: string; + bulkJobId?: string; }>; hiredRole?: string; hiredSubteamPk?: string; @@ -90,6 +91,7 @@ const ApplicationSchema = new Schema( }, changedAt: { type: Date, default: Date.now }, changedBy: { type: String }, + bulkJobId: { type: String }, }, ], hiredRole: { type: String, required: false }, diff --git a/peopleportal/server/src/models/BulkApplicationUpdate.ts b/peopleportal/server/src/models/BulkApplicationUpdate.ts new file mode 100644 index 00000000..18ee9a1e --- /dev/null +++ b/peopleportal/server/src/models/BulkApplicationUpdate.ts @@ -0,0 +1,156 @@ +/** + People Portal Server + Copyright (C) 2026 Atheesh Thirumalairajan + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +import { Document, model, Schema, Types } from "mongoose"; +import { ApplicationStage } from "./Application"; + +export enum BulkApplicationUpdateStatus { + QUEUED = "queued", + PROCESSING = "processing", + COMPLETED = "completed", + COMPLETED_WITH_ERRORS = "completed_with_errors", +} + +export enum BulkApplicationRecipientStatus { + PENDING = "pending", + PROCESSING = "processing", + SENT = "sent", + FAILED = "failed", + VALIDATION_FAILED = "validation_failed", +} + +export type BulkApplicationFailurePhase = "stage" | "email" | "queue"; + +export interface IBulkApplicationUpdateJob extends Document { + teamPk: string; + teamName: string; + targetStage: ApplicationStage; + interviewLink?: string; + interviewGuidelines?: string; + requestedByName: string; + requestedByEmail: string; + requestedByUsername: string; + status: BulkApplicationUpdateStatus; + createdAt: Date; + updatedAt: Date; +} + +export interface IBulkApplicationUpdateRecipient extends Document { + jobId: Types.ObjectId; + teamPk: string; + applicationId: string; + applicantId?: string; + applicantName?: string; + email?: string; + previousStage?: ApplicationStage; + targetStage: ApplicationStage; + status: BulkApplicationRecipientStatus; + failurePhase?: BulkApplicationFailurePhase | undefined; + error?: string | undefined; + attempts: number; + stageChangedAt?: Date; + sentAt?: Date; + createdAt: Date; + updatedAt: Date; +} + +const BulkApplicationUpdateJobSchema = + new Schema( + { + teamPk: { type: String, required: true, index: true }, + teamName: { type: String, required: true }, + targetStage: { + type: String, + enum: Object.values(ApplicationStage), + required: true, + }, + interviewLink: { type: String }, + interviewGuidelines: { type: String }, + requestedByName: { type: String, required: true }, + requestedByEmail: { type: String, required: true }, + requestedByUsername: { type: String, required: true }, + status: { + type: String, + enum: Object.values(BulkApplicationUpdateStatus), + required: true, + default: BulkApplicationUpdateStatus.QUEUED, + }, + }, + { timestamps: true }, + ); + +const BulkApplicationUpdateRecipientSchema = + new Schema( + { + jobId: { + type: Schema.Types.ObjectId, + ref: "BulkApplicationUpdateJob", + required: true, + }, + teamPk: { type: String, required: true }, + applicationId: { type: String, required: true }, + applicantId: { type: String }, + applicantName: { type: String }, + email: { type: String }, + previousStage: { + type: String, + enum: Object.values(ApplicationStage), + }, + targetStage: { + type: String, + enum: Object.values(ApplicationStage), + required: true, + }, + status: { + type: String, + enum: Object.values(BulkApplicationRecipientStatus), + required: true, + }, + failurePhase: { + type: String, + enum: ["stage", "email", "queue"], + }, + error: { type: String }, + attempts: { type: Number, required: true, default: 0 }, + stageChangedAt: { type: Date }, + sentAt: { type: Date }, + }, + { timestamps: true }, + ); + +BulkApplicationUpdateRecipientSchema.index( + { jobId: 1, applicationId: 1 }, + { unique: true }, +); +BulkApplicationUpdateRecipientSchema.index({ + teamPk: 1, + applicationId: 1, + createdAt: -1, +}); + +export const BulkApplicationUpdateJob = + model( + "BulkApplicationUpdateJob", + BulkApplicationUpdateJobSchema, + ); + +export const BulkApplicationUpdateRecipient = + model( + "BulkApplicationUpdateRecipient", + BulkApplicationUpdateRecipientSchema, + ); diff --git a/peopleportal/server/src/models/application-stage-transitions.ts b/peopleportal/server/src/models/application-stage-transitions.ts new file mode 100644 index 00000000..8af3de18 --- /dev/null +++ b/peopleportal/server/src/models/application-stage-transitions.ts @@ -0,0 +1,31 @@ +import { ApplicationStage } from "./Application"; + +export const VALID_APPLICATION_STAGE_TRANSITIONS: Record< + ApplicationStage, + readonly ApplicationStage[] +> = { + [ApplicationStage.APPLIED]: [ + ApplicationStage.INTERVIEW, + ApplicationStage.REJECTED, + ], + [ApplicationStage.INTERVIEW]: [ + ApplicationStage.POTENTIAL_HIRE, + ApplicationStage.HIRED, + ApplicationStage.REJECTED, + ], + [ApplicationStage.POTENTIAL_HIRE]: [ + ApplicationStage.HIRED, + ApplicationStage.REJECTED, + ], + [ApplicationStage.HIRED]: [], + [ApplicationStage.REJECTED]: [], +}; + +export function isValidApplicationStageTransition( + currentStage: ApplicationStage, + newStage: ApplicationStage, +): boolean { + return VALID_APPLICATION_STAGE_TRANSITIONS[currentStage]?.includes( + newStage, + ); +} diff --git a/peopleportal/server/src/routes.ts b/peopleportal/server/src/routes.ts index 4a19fa81..c67c82be 100644 --- a/peopleportal/server/src/routes.ts +++ b/peopleportal/server/src/routes.ts @@ -1079,6 +1079,11 @@ const models: TsoaRoute.Models = { "type": {"dataType":"nestedObjectLiteral","nestedProperties":{},"validators":{}}, }, // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "BulkApplicationRecipientStatus": { + "dataType": "refEnum", + "enums": ["pending","processing","sent","failed","validation_failed"], + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa "ATSKanbanApplicationCard": { "dataType": "refObject", "properties": { @@ -1089,6 +1094,7 @@ const models: TsoaRoute.Models = { "appliedAt": {"dataType":"datetime","required":true}, "stage": {"ref":"ApplicationStage","required":true}, "stars": {"dataType":"double","required":true,"validators":{"minimum":{"errorMsg":"Minimum Stars is 0","value":0},"maximum":{"errorMsg":"Maximum Stars is 5","value":5}}}, + "latestEmailUpdate": {"dataType":"nestedObjectLiteral","nestedProperties":{"updatedAt":{"dataType":"datetime","required":true},"status":{"ref":"BulkApplicationRecipientStatus","required":true},"stage":{"ref":"ApplicationStage","required":true}}}, }, "additionalProperties": false, }, @@ -1103,6 +1109,7 @@ const models: TsoaRoute.Models = { "appliedAt": {"dataType":"datetime","required":true}, "stage": {"ref":"ApplicationStage","required":true}, "stars": {"dataType":"double","required":true,"validators":{"minimum":{"errorMsg":"Minimum Stars is 0","value":0},"maximum":{"errorMsg":"Maximum Stars is 5","value":5}}}, + "latestEmailUpdate": {"dataType":"nestedObjectLiteral","nestedProperties":{"updatedAt":{"dataType":"datetime","required":true},"status":{"ref":"BulkApplicationRecipientStatus","required":true},"stage":{"ref":"ApplicationStage","required":true}}}, "email": {"dataType":"string","required":true}, "profile": {"ref":"Record_string.string_","required":true}, "responses": {"ref":"Record_string.string_","required":true}, @@ -1110,6 +1117,7 @@ const models: TsoaRoute.Models = { "hiredRole": {"dataType":"string"}, "appDevInternalPk": {"dataType":"double"}, "notes": {"dataType":"string"}, + "emailUpdates": {"dataType":"array","array":{"dataType":"nestedObjectLiteral","nestedProperties":{"error":{"dataType":"string"},"sentAt":{"dataType":"datetime"},"createdAt":{"dataType":"datetime","required":true},"attempts":{"dataType":"double","required":true},"status":{"ref":"BulkApplicationRecipientStatus","required":true},"stage":{"ref":"ApplicationStage","required":true},"jobId":{"dataType":"string","required":true}}},"required":true}, }, "additionalProperties": false, }, @@ -1126,6 +1134,37 @@ const models: TsoaRoute.Models = { "additionalProperties": false, }, // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "BulkApplicationUpdateStatus.COMPLETED_WITH_ERRORS": { + "dataType": "refEnum", + "enums": ["completed_with_errors"], + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "BulkApplicationUpdateStatus": { + "dataType": "refEnum", + "enums": ["queued","processing","completed","completed_with_errors"], + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "ATSBulkApplicationUpdateRequest": { + "dataType": "refObject", + "properties": { + "applicationIds": {"dataType":"array","array":{"dataType":"string"},"required":true}, + "stage": {"ref":"ApplicationStage","required":true}, + "interviewLink": {"dataType":"string"}, + "interviewGuidelines": {"dataType":"string"}, + }, + "additionalProperties": false, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "BulkApplicationFailurePhase": { + "dataType": "refAlias", + "type": {"dataType":"union","subSchemas":[{"dataType":"enum","enums":["stage"]},{"dataType":"enum","enums":["email"]},{"dataType":"enum","enums":["queue"]}],"validators":{}}, + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + "BulkApplicationUpdateStatus.QUEUED": { + "dataType": "refEnum", + "enums": ["queued"], + }, + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa "ApplicantProfile": { "dataType": "refObject", "properties": { @@ -3881,6 +3920,137 @@ export function RegisterRoutes(app: Router) { } }); // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsATSController_createBulkApplicationUpdate: Record = { + req: {"in":"request","name":"req","required":true,"dataType":"object"}, + teamId: {"in":"path","name":"teamId","required":true,"dataType":"string"}, + body: {"in":"body","name":"body","required":true,"ref":"ATSBulkApplicationUpdateRequest"}, + }; + app.post('/api/ats/applications/:teamId/bulk-updates', + authenticateMiddleware([{"bindles":["corp:hiringaccess"]}]), + ...(fetchMiddlewares(ATSController)), + ...(fetchMiddlewares(ATSController.prototype.createBulkApplicationUpdate)), + + async function ATSController_createBulkApplicationUpdate(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsATSController_createBulkApplicationUpdate, request, response }); + + const controller = new ATSController(); + + await templateService.apiHandler({ + methodName: 'createBulkApplicationUpdate', + controller, + response, + next, + validatedArgs, + successStatus: 201, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsATSController_getBulkApplicationUpdates: Record = { + req: {"in":"request","name":"req","required":true,"dataType":"object"}, + teamId: {"in":"path","name":"teamId","required":true,"dataType":"string"}, + }; + app.get('/api/ats/applications/:teamId/bulk-updates', + authenticateMiddleware([{"bindles":["corp:hiringaccess"]}]), + ...(fetchMiddlewares(ATSController)), + ...(fetchMiddlewares(ATSController.prototype.getBulkApplicationUpdates)), + + async function ATSController_getBulkApplicationUpdates(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsATSController_getBulkApplicationUpdates, request, response }); + + const controller = new ATSController(); + + await templateService.apiHandler({ + methodName: 'getBulkApplicationUpdates', + controller, + response, + next, + validatedArgs, + successStatus: 200, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsATSController_getBulkApplicationUpdate: Record = { + req: {"in":"request","name":"req","required":true,"dataType":"object"}, + teamId: {"in":"path","name":"teamId","required":true,"dataType":"string"}, + jobId: {"in":"path","name":"jobId","required":true,"dataType":"string"}, + }; + app.get('/api/ats/applications/:teamId/bulk-updates/:jobId', + authenticateMiddleware([{"bindles":["corp:hiringaccess"]}]), + ...(fetchMiddlewares(ATSController)), + ...(fetchMiddlewares(ATSController.prototype.getBulkApplicationUpdate)), + + async function ATSController_getBulkApplicationUpdate(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsATSController_getBulkApplicationUpdate, request, response }); + + const controller = new ATSController(); + + await templateService.apiHandler({ + methodName: 'getBulkApplicationUpdate', + controller, + response, + next, + validatedArgs, + successStatus: 200, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + const argsATSController_retryBulkApplicationUpdate: Record = { + req: {"in":"request","name":"req","required":true,"dataType":"object"}, + teamId: {"in":"path","name":"teamId","required":true,"dataType":"string"}, + jobId: {"in":"path","name":"jobId","required":true,"dataType":"string"}, + }; + app.post('/api/ats/applications/:teamId/bulk-updates/:jobId/retry', + authenticateMiddleware([{"bindles":["corp:hiringaccess"]}]), + ...(fetchMiddlewares(ATSController)), + ...(fetchMiddlewares(ATSController.prototype.retryBulkApplicationUpdate)), + + async function ATSController_retryBulkApplicationUpdate(request: ExRequest, response: ExResponse, next: any) { + + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa + + let validatedArgs: any[] = []; + try { + validatedArgs = templateService.getValidatedArgs({ args: argsATSController_retryBulkApplicationUpdate, request, response }); + + const controller = new ATSController(); + + await templateService.apiHandler({ + methodName: 'retryBulkApplicationUpdate', + controller, + response, + next, + validatedArgs, + successStatus: 202, + }); + } catch (err) { + return next(err); + } + }); + // WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa const argsATSController_getApplicantApplications: Record = { teamId: {"in":"path","name":"teamId","required":true,"dataType":"string"}, applicantId: {"in":"path","name":"applicantId","required":true,"dataType":"string"}, diff --git a/peopleportal/server/test/integration/bulk-application-updates.test.js b/peopleportal/server/test/integration/bulk-application-updates.test.js new file mode 100644 index 00000000..3bd422a4 --- /dev/null +++ b/peopleportal/server/test/integration/bulk-application-updates.test.js @@ -0,0 +1,318 @@ +const assert = require("node:assert/strict"); +const test = require("node:test"); +const mongoose = require("mongoose"); +const { MongoMemoryServer } = require("mongodb-memory-server"); + +const { Applicant } = require("../../dist/models/Applicant.js"); +const { + Application, + ApplicationStage, +} = require("../../dist/models/Application.js"); +const { + BulkApplicationRecipientStatus, + BulkApplicationUpdateJob, + BulkApplicationUpdateRecipient, +} = require("../../dist/models/BulkApplicationUpdate.js"); +const { ATSController } = require("../../dist/controllers/ATSController.js"); +const { agendaClient } = require("../../dist/clients/AgendaClient/index.js"); +const { EmailClient } = require("../../dist/clients/EmailClient/index.js"); +const { DefinedJobs } = require("../../dist/clients/AgendaClient/Jobs/index.js"); + +const TEAM_PK = "team-webdev-fa26"; +let mongo; +let applicantCounter = 0; +let originalScheduleJobOnce; +let originalEmailSend; +let scheduledJobs; + +test.before(async () => { + mongo = await MongoMemoryServer.create(); + await mongoose.connect(mongo.getUri("people-portal-test")); +}); + +test.after(async () => { + await mongoose.disconnect(); + if (mongo) await mongo.stop(); +}); + +test.beforeEach(async () => { + await Promise.all([ + Applicant.deleteMany({}), + Application.deleteMany({}), + BulkApplicationUpdateJob.deleteMany({}), + BulkApplicationUpdateRecipient.deleteMany({}), + ]); + scheduledJobs = []; + originalScheduleJobOnce = agendaClient.scheduleJobOnce; + agendaClient.scheduleJobOnce = async (data) => scheduledJobs.push(data); + originalEmailSend = EmailClient.prototype.send; +}); + +test.afterEach(() => { + agendaClient.scheduleJobOnce = originalScheduleJobOnce; + EmailClient.prototype.send = originalEmailSend; +}); + +const recruiterRequest = () => ({ + session: { + authorizedUser: { + pk: 7001, + sub: "sub-7001", + username: "recruiter", + email: "recruiter@example.invalid", + name: "Recruiter", + is_superuser: true, + groups: [], + attributes: {}, + }, + }, +}); + +function controllerWithTeam() { + const controller = new ATSController(); + controller.authentikClient = { + getGroupInfo: async () => ({ + pk: TEAM_PK, + name: "webdev-fa26", + attributes: { + friendlyName: "Web Dev", + peoplePortalCreation: true, + flaggedForDeletion: false, + }, + users: [], + subteams: [], + }), + }; + return controller; +} + +async function seedApplication(stage = ApplicationStage.APPLIED) { + applicantCounter += 1; + const applicant = await Applicant.create({ + email: `applicant-${applicantCounter}@example.invalid`, + fullName: `Applicant ${applicantCounter}`, + profile: new Map(), + }); + const application = await Application.create({ + applicantId: applicant._id, + teamPk: TEAM_PK, + rolePreferences: [ + { role: "Software Engineer", subteamPk: "subteam-webdev-frontend" }, + ], + stage, + responses: {}, + stars: 0, + }); + return { applicant, application }; +} + +function interviewPayload(applicationIds) { + return { + applicationIds, + stage: ApplicationStage.INTERVIEW, + interviewLink: "https://example.invalid/interview", + interviewGuidelines: "Please prepare to discuss your recent work and interests.", + }; +} + +test("queues eligible applicants and persists per-recipient validation failures", async () => { + const { application: eligible } = await seedApplication(); + const { application: terminal } = await seedApplication( + ApplicationStage.REJECTED, + ); + const controller = controllerWithTeam(); + + const result = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + interviewPayload([ + String(eligible._id), + String(terminal._id), + "not-an-object-id", + ]), + ); + + assert.equal(result.queued, true); + assert.equal(result.queuedRecipients, 1); + assert.equal(result.validationFailedRecipients, 2); + assert.equal(scheduledJobs.length, 1); + + const recipients = await BulkApplicationUpdateRecipient.find({ + jobId: result.jobId, + }).sort({ applicationId: 1 }); + assert.equal( + recipients.filter( + (recipient) => + recipient.status === BulkApplicationRecipientStatus.PENDING, + ).length, + 1, + ); + assert.equal( + recipients.filter( + (recipient) => + recipient.status === + BulkApplicationRecipientStatus.VALIDATION_FAILED, + ).length, + 2, + ); + + const [details, summaries] = await Promise.all([ + controller.getBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + result.jobId, + ), + controller.getBulkApplicationUpdates(recruiterRequest(), TEAM_PK), + ]); + assert.equal(details.recipients.length, 3); + assert.equal( + summaries.find((summary) => summary.jobId === result.jobId).counts.total, + 3, + ); +}); + +test("worker changes stage, sends the configured template, and persists success", async () => { + const { applicant, application } = await seedApplication(); + const controller = controllerWithTeam(); + const created = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + interviewPayload([String(application._id)]), + ); + const sent = []; + EmailClient.prototype.send = async (request) => { + sent.push(request); + }; + + await DefinedJobs.sendBulkApplicationUpdates.workerFunction({ + attrs: { data: { jobId: created.jobId } }, + }); + + const updatedApplication = await Application.findById(application._id); + const recipient = await BulkApplicationUpdateRecipient.findOne({ + jobId: created.jobId, + applicationId: String(application._id), + }); + const job = await BulkApplicationUpdateJob.findById(created.jobId); + + assert.equal(updatedApplication.stage, ApplicationStage.INTERVIEW); + assert.equal( + updatedApplication.stageHistory.at(-1).bulkJobId, + created.jobId, + ); + assert.equal(sent.length, 1); + assert.equal(sent[0].to, applicant.email); + assert.equal(sent[0].templateName, "RecruitInterviewRequest"); + assert.equal(recipient.status, BulkApplicationRecipientStatus.SENT); + assert.ok(recipient.sentAt); + assert.equal(job.status, "completed"); +}); + +test("email failures remain retryable without repeating the stage change", async () => { + const { application } = await seedApplication(); + const controller = controllerWithTeam(); + const created = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + { + applicationIds: [String(application._id)], + stage: ApplicationStage.REJECTED, + }, + ); + EmailClient.prototype.send = async () => { + throw new Error("SMTP unavailable"); + }; + + await DefinedJobs.sendBulkApplicationUpdates.workerFunction({ + attrs: { data: { jobId: created.jobId } }, + }); + + const failedRecipient = await BulkApplicationUpdateRecipient.findOne({ + jobId: created.jobId, + }); + assert.equal(failedRecipient.status, BulkApplicationRecipientStatus.FAILED); + assert.equal(failedRecipient.failurePhase, "email"); + assert.ok(failedRecipient.stageChangedAt); + + const originalHistoryLength = ( + await Application.findById(application._id) + ).stageHistory.length; + let retriedEmail; + EmailClient.prototype.send = async (request) => { + retriedEmail = request; + }; + const retryResult = await controller.retryBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + created.jobId, + ); + assert.equal(retryResult.queuedRecipients, 1); + assert.equal(scheduledJobs.length, 2); + + await DefinedJobs.sendBulkApplicationUpdates.workerFunction({ + attrs: { data: { jobId: created.jobId } }, + }); + const completedRecipient = await BulkApplicationUpdateRecipient.findOne({ + jobId: created.jobId, + }); + const finalApplication = await Application.findById(application._id); + + assert.equal(completedRecipient.status, BulkApplicationRecipientStatus.SENT); + assert.equal(retriedEmail.templateName, "RecruitApplicationDeclined"); + assert.equal(finalApplication.stageHistory.length, originalHistoryLength); +}); + +test("a queue outage is recorded and can be retried", async () => { + const { application } = await seedApplication(); + const controller = controllerWithTeam(); + agendaClient.scheduleJobOnce = async () => { + throw new Error("Agenda unavailable"); + }; + + const created = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + { + applicationIds: [String(application._id)], + stage: ApplicationStage.REJECTED, + }, + ); + assert.equal(created.error, "QueueUnavailable"); + + const failedRecipient = await BulkApplicationUpdateRecipient.findOne({ + jobId: created.jobId, + }); + assert.equal(failedRecipient.failurePhase, "queue"); + assert.equal(failedRecipient.status, BulkApplicationRecipientStatus.FAILED); + + agendaClient.scheduleJobOnce = async (data) => scheduledJobs.push(data); + const retryResult = await controller.retryBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + created.jobId, + ); + const queuedRecipient = await BulkApplicationUpdateRecipient.findById( + failedRecipient._id, + ); + assert.equal(retryResult.queuedRecipients, 1); + assert.equal(queuedRecipient.status, BulkApplicationRecipientStatus.PENDING); + assert.equal(queuedRecipient.stageChangedAt, undefined); + assert.equal(scheduledJobs.length, 1); +}); + +test("bulk updates reject stages without a matching status email", async () => { + const { application } = await seedApplication(); + const controller = controllerWithTeam(); + + const result = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + { + applicationIds: [String(application._id)], + stage: ApplicationStage.POTENTIAL_HIRE, + }, + ); + + assert.equal(result.error, "BadRequest"); + assert.equal(scheduledJobs.length, 0); +}); diff --git a/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.test.tsx b/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.test.tsx index d9375394..3e901b7e 100644 --- a/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.test.tsx +++ b/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.test.tsx @@ -41,10 +41,16 @@ function deferred() { let applications: RecruitmentApplication[]; let details: Map; -let requests: { path: string; signal: AbortSignal | null | undefined }[]; +let requests: { + path: string; + signal: AbortSignal | null | undefined; + method?: string; + body?: BodyInit | null; +}[]; let responses: Map>; beforeEach(() => { + Element.prototype.scrollIntoView = vi.fn(); applications = [makeApplication("a"), makeApplication("b")]; details = new Map( applications.map((application) => [ @@ -55,6 +61,7 @@ beforeEach(() => { profile: { whyAppDev: `Background ${application.id}` }, responses: {}, notes: `Notes ${application.id}`, + emailUpdates: [], }, ]), ); @@ -65,7 +72,12 @@ beforeEach(() => { "fetch", async (input: RequestInfo | URL, init?: RequestInit) => { const path = String(input); - requests.push({ path, signal: init?.signal }); + requests.push({ + path, + signal: init?.signal, + method: init?.method, + body: init?.body, + }); const response = responses.get(path); if (response) return response; if (path === "/api/org/teams/team-a") { @@ -90,6 +102,38 @@ beforeEach(() => { "Hired", ].map((id) => ({ id, name: id })), ); + if (path === `${apiPath}/bulk-updates`) { + if (init?.method === "POST") { + return Response.json( + { + jobId: "job-1", + queued: true, + queuedRecipients: 1, + validationFailedRecipients: 0, + }, + { status: 201 }, + ); + } + return Response.json([]); + } + if (path === `${apiPath}/bulk-updates/job-1`) { + return Response.json({ + jobId: "job-1", + targetStage: "Rejected", + status: "queued", + createdAt: "2026-09-01T12:00:00.000Z", + recipients: [ + { + applicationId: "a", + applicantName: "Applicant A", + targetStage: "Rejected", + status: "pending", + attempts: 0, + createdAt: "2026-09-01T12:00:00.000Z", + }, + ], + }); + } if (path === apiPath) return Response.json(applications); for (const application of applications) { if (path === `${apiPath}/${application.id}/info`) @@ -261,4 +305,67 @@ describe("recruitment review", () => { ); expect(result.current.selected?.stars).toBe(5); }); + + it("queues selected applicants and shows the persisted batch progress", async () => { + openBoard(); + await userEvent.click( + await screen.findByRole("checkbox", { + name: "Select Applicant A", + }), + ); + await userEvent.click( + screen.getByRole("button", { name: "Update selected (1)" }), + ); + screen + .getByRole("combobox", { name: "New application stage" }) + .focus(); + await userEvent.keyboard("{ENTER}{ARROWDOWN}{ARROWDOWN}{ENTER}"); + await userEvent.click( + screen.getByRole("button", { + name: "Queue update for 1 applicants", + }), + ); + + const progressDialog = await screen.findByRole("dialog", { + name: "Bulk update progress", + }); + expect(progressDialog).toHaveTextContent("Pending: 1"); + expect(progressDialog).toHaveTextContent("Applicant A"); + + const submittedRequest = requests.find( + (request) => + request.path === `${apiPath}/bulk-updates` && + request.method === "POST", + ); + expect(submittedRequest).toBeDefined(); + expect(JSON.parse(String(submittedRequest?.body))).toEqual({ + applicationIds: ["a"], + stage: "Rejected", + }); + }); + + it("shows each applicant's latest email status and update history", async () => { + applications[0].latestEmailUpdate = { + stage: "Rejected", + status: "sent", + updatedAt: "2026-09-01T12:00:00.000Z", + }; + details.get("a")!.emailUpdates = [ + { + jobId: "job-1", + stage: "Rejected", + status: "sent", + attempts: 1, + createdAt: "2026-09-01T12:00:00.000Z", + sentAt: "2026-09-01T12:01:00.000Z", + }, + ]; + + openBoard(); + await screen.findByText("sent Rejected"); + await openA(); + + expect(screen.getByText("Applicant email updates")).toBeInTheDocument(); + expect(screen.getByText(/Attempts: 1 · Sent/)).toBeInTheDocument(); + }); }); diff --git a/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.tsx b/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.tsx index d3252721..5f58f530 100644 --- a/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.tsx +++ b/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.tsx @@ -101,6 +101,59 @@ interface StageDefinition { [key: string]: unknown; // Index signature for Kanban compatibility } +interface BulkApplicationUpdateJobSummary { + jobId: string; + targetStage: string; + status: string; + createdAt: string; + counts: { + total: number; + pending: number; + processing: number; + sent: number; + failed: number; + validationFailed: number; + }; +} + +interface BulkApplicationUpdateDetails { + jobId: string; + targetStage: string; + status: string; + createdAt: string; + recipients: { + applicationId: string; + applicantName: string; + email?: string; + previousStage?: string; + targetStage: string; + status: string; + failurePhase?: string; + error?: string; + attempts: number; + sentAt?: string; + createdAt: string; + }[]; +} + +async function fetchBulkUpdate( + teamId: string, + path = "", + init?: RequestInit, +): Promise { + const response = await fetch( + `${PEOPLEPORTAL_SERVER_ENDPOINT}/api/ats/applications/${encodeURIComponent(teamId)}/bulk-updates${path}`, + { ...init, credentials: "include" }, + ); + const data = (await response.json()) as T & { message?: string }; + if (!response.ok) { + throw new Error( + data.message || `Bulk update request failed (${response.status})`, + ); + } + return data; +} + /** Recruitment cache is private to this mounted team/reviewer, never persisted. */ export const DashboardTeamRecruitment = ({ reviewerId, @@ -142,6 +195,7 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { const [searchParams, setSearchParams] = useSearchParams(); const selectedId = searchParams.get("application"); const review = useRecruitmentQueries(teamId, selectedId); + const refreshApplicationData = review.refreshApplicationData; const applications = review.applications.data ?? []; const selectedApplication = review.selected; const selectedApplicationDetails = review.details.data; @@ -175,6 +229,29 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { [key: string]: { [key: string]: string[] }; }>({}); + const [selectedApplicationIds, setSelectedApplicationIds] = React.useState< + string[] + >([]); + const [bulkUpdateDialogOpen, setBulkUpdateDialogOpen] = + React.useState(false); + const [bulkTargetStage, setBulkTargetStage] = React.useState(""); + const [bulkInterviewLink, setBulkInterviewLink] = React.useState(""); + const [bulkInterviewGuidelines, setBulkInterviewGuidelines] = + React.useState(""); + const [isSubmittingBulkUpdate, setIsSubmittingBulkUpdate] = + React.useState(false); + const [bulkUpdateJobs, setBulkUpdateJobs] = React.useState< + BulkApplicationUpdateJobSummary[] + >([]); + const [activeBulkUpdateId, setActiveBulkUpdateId] = React.useState< + string | null + >(null); + const [activeBulkUpdate, setActiveBulkUpdate] = + React.useState(null); + const [bulkUpdateLoadError, setBulkUpdateLoadError] = React.useState< + string | null + >(null); + // --- Stage Transition Logic --- const VALID_TRANSITIONS: { [key: string]: string[] } = { Applied: ["Interview", "Rejected"], @@ -382,6 +459,190 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { } } + const refreshBulkUpdateJobs = React.useCallback( + async (notifyOnError = false) => { + try { + const data = await fetchBulkUpdate< + BulkApplicationUpdateJobSummary[] + >(teamId); + setBulkUpdateJobs(data); + } catch (error) { + console.error("Failed to fetch batch update history:", error); + if (notifyOnError) { + toast.error( + `Failed to fetch batch update history: ${error instanceof Error ? error.message : "Unknown error"}`, + ); + } + } + }, + [teamId], + ); + + const refreshBulkUpdateDetails = React.useCallback( + async (jobId: string) => { + setBulkUpdateLoadError(null); + try { + const details = + await fetchBulkUpdate( + teamId, + `/${encodeURIComponent(jobId)}`, + ); + setActiveBulkUpdate(details); + } catch (error) { + console.error("Failed to fetch batch update status:", error); + setBulkUpdateLoadError( + error instanceof Error ? error.message : "Unknown error", + ); + } + }, + [teamId], + ); + + async function submitBulkApplicationUpdate() { + if ( + !bulkTargetStage || + selectedApplicationIds.length === 0 || + selectedApplicationIds.length > 100 + ) { + return; + } + setIsSubmittingBulkUpdate(true); + try { + const response = await fetch( + `${PEOPLEPORTAL_SERVER_ENDPOINT}/api/ats/applications/${encodeURIComponent(teamId)}/bulk-updates`, + { + method: "POST", + credentials: "include", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + applicationIds: selectedApplicationIds, + stage: bulkTargetStage, + ...(bulkTargetStage === "Interview" + ? { + interviewLink: bulkInterviewLink, + interviewGuidelines: + bulkInterviewGuidelines, + } + : {}), + }), + }, + ); + const data = (await response.json()) as { + message?: string; + jobId?: string; + queued?: boolean; + queuedRecipients?: number; + validationFailedRecipients?: number; + }; + if (data.jobId) { + setActiveBulkUpdateId(data.jobId); + setActiveBulkUpdate(null); + setBulkUpdateDialogOpen(false); + setSelectedApplicationIds([]); + await Promise.all([ + refreshBulkUpdateJobs(), + refreshBulkUpdateDetails(data.jobId), + review.refreshApplicationData(), + ]); + } + if (!response.ok) { + throw new Error( + data.message || + `Could not create batch update (${response.status})`, + ); + } + if (!data.jobId) { + throw new Error("The server did not return a batch job ID."); + } + + if (data.queued) { + toast.success( + `Batch update queued for ${data.queuedRecipients ?? 0} applicants`, + { + description: data.validationFailedRecipients + ? `${data.validationFailedRecipients} selected application(s) were not eligible.` + : undefined, + }, + ); + } else { + toast.error("No applicants were eligible for this batch", { + description: `${data.validationFailedRecipients ?? 0} selected application(s) failed validation.`, + }); + } + } catch (error) { + toast.error( + `Failed to create batch update: ${error instanceof Error ? error.message : "Unknown error"}`, + ); + } finally { + setIsSubmittingBulkUpdate(false); + } + } + + const retryBulkApplicationUpdate = React.useCallback( + async (jobId: string) => { + try { + const data = await fetchBulkUpdate<{ + queuedRecipients: number; + }>(teamId, `/${encodeURIComponent(jobId)}/retry`, { + method: "POST", + }); + toast.success( + `Queued ${data.queuedRecipients} failed recipient(s) for retry`, + ); + await Promise.all([ + refreshBulkUpdateJobs(), + refreshBulkUpdateDetails(jobId), + refreshApplicationData(), + ]); + } catch (error) { + toast.error( + `Failed to retry batch: ${error instanceof Error ? error.message : "Unknown error"}`, + ); + } + }, + [ + refreshBulkUpdateDetails, + refreshBulkUpdateJobs, + refreshApplicationData, + teamId, + ], + ); + + React.useEffect(() => { + void refreshBulkUpdateJobs(true); + }, [refreshBulkUpdateJobs]); + + React.useEffect(() => { + if (!activeBulkUpdateId) { + setActiveBulkUpdate(null); + setBulkUpdateLoadError(null); + return; + } + void refreshBulkUpdateDetails(activeBulkUpdateId); + }, [activeBulkUpdateId, refreshBulkUpdateDetails]); + + React.useEffect(() => { + const hasActiveJobs = bulkUpdateJobs.some((job) => + ["queued", "processing"].includes(job.status), + ); + if (!hasActiveJobs) return; + + const interval = window.setInterval(() => { + void refreshBulkUpdateJobs(); + void refreshApplicationData(); + if (activeBulkUpdateId) { + void refreshBulkUpdateDetails(activeBulkUpdateId); + } + }, 3000); + return () => window.clearInterval(interval); + }, [ + activeBulkUpdateId, + bulkUpdateJobs, + refreshBulkUpdateDetails, + refreshBulkUpdateJobs, + refreshApplicationData, + ]); + // Fetch application stages React.useEffect(() => { fetch(`${PEOPLEPORTAL_SERVER_ENDPOINT}/api/ats/stages`) @@ -597,6 +858,57 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { )} +
+ + {selectedApplicationIds.length > 0 && ( + + )} + {bulkUpdateJobs.length > 0 && ( +
+ + Recent batches: + + {bulkUpdateJobs.slice(0, 5).map((job) => ( + + ))} +
+ )} +
- - { - item.name - } - +
+ { + event.stopPropagation(); + }} + onPointerDown={( + event, + ) => { + event.stopPropagation(); + }} + onCheckedChange={( + checked, + ) => { + setSelectedApplicationIds( + (current) => + checked === + true + ? [ + ...new Set( + [ + ...current, + item.id, + ], + ), + ] + : current.filter( + ( + id, + ) => + id !== + item.id, + ), + ); + }} + /> + + { + item.name + } + +
{new Date( item.appliedAt, @@ -689,6 +1043,31 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { 12 } /> + {item.latestEmailUpdate && ( + + { + item.latestEmailUpdate + .status + }{" "} + { + item.latestEmailUpdate + .stage + } + + )}
@@ -1453,6 +1832,67 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { ))} +
+

+ Applicant email updates +

+ {selectedApplicationDetails?.emailUpdates + ?.length ? ( +
+ {selectedApplicationDetails.emailUpdates.map( + (update) => ( +
+
+ + {update.stage} ·{" "} + {new Date( + update.createdAt, + ).toLocaleString()} + + + {update.status.replace( + /_/g, + " ", + )} + +
+

+ Attempts:{" "} + {update.attempts} + {update.sentAt + ? ` · Sent ${new Date(update.sentAt).toLocaleString()}` + : ""} +

+ {update.error && ( +

+ {update.error} +

+ )} +
+ ), + )} +
+ ) : ( +

+ No batch email updates recorded. +

+ )} +
+ {/* Other applications load independently of the resume. */}

Other Applications @@ -1563,6 +2003,269 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { +

+ + + Bulk stage update + + Move up to 100 selected applications and send each + applicant the existing email for the selected + stage. Applications that fail validation will be + recorded and skipped. + + +
+
+ + +
+ {bulkTargetStage === "Interview" && ( + <> +
+ + + setBulkInterviewLink( + event.target.value, + ) + } + placeholder="https://..." + /> +
+
+ +