diff --git a/.gitignore b/.gitignore index 7682a770..6ba30989 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,19 @@ .claude/worktrees .claude/settings.local.json *.DS_Store + +# Local environment files may contain credentials. Commit explicit templates only. +.env +.env.* +!.env*.example + +# Generated Gitea development data, including database and private keys. +/peopleportal/gitea/ + +# Local compose files contain development-only credentials; use dev-stack instead. +/docker-compose.yml +/peopleportal/docker-compose.yml + peopleportal/server/.env.development # Bootstrap script outputs (contain credentials) diff --git a/peopleportal/server/src/clients/AgendaClient/Jobs/index.ts b/peopleportal/server/src/clients/AgendaClient/Jobs/index.ts index 0a5a0c8f..e29d4935 100644 --- a/peopleportal/server/src/clients/AgendaClient/Jobs/index.ts +++ b/peopleportal/server/src/clients/AgendaClient/Jobs/index.ts @@ -1,4 +1,5 @@ import { Job, JobDefinition } from "agenda"; +import { Types } from "mongoose"; import { DateTime } from "luxon"; import { EmailClient } from "../../EmailClient"; import { EmailSendRequest } from "../../EmailClient/models"; @@ -10,6 +11,23 @@ import { HydratedDocument } from "mongoose"; import { ENABLED_SHARED_RESOURCES } from "../../../config"; import { SlackClient } from "../../SlackClient"; import { DiscordClient } from "../../DiscordClient"; +import { + Application, + IApplication, + ApplicationStage, +} from "../../../models/Application"; +import { + BulkApplicationRecipientStatus, + BulkApplicationUpdateJob, + BulkApplicationUpdateRecipient, + BulkApplicationUpdateStatus, +} from "../../../models/BulkApplicationUpdate"; +import { isValidApplicationStageTransition } from "../../../models/application-stage-transitions"; +import { + acquireApplicationStageUpdateLock, + releaseApplicationStageUpdateLock, +} from "../../../models/application-stage-update-lock"; +import { logger } from "../../../utils/logger"; interface _JobData { jobName: string; @@ -147,6 +165,87 @@ export interface SendEventRemindersPayload extends JobPayload { eventId: string; } +export interface SendBulkApplicationUpdatesPayload extends JobPayload { + jobId: string; +} + +export async function recoverQueuedBulkApplicationUpdates( + scheduleJob: (jobId: string) => Promise, +): Promise { + const queuedJobs = await BulkApplicationUpdateJob.find({ + status: BulkApplicationUpdateStatus.QUEUED, + }) + .select("_id") + .exec(); + + for (const queuedJob of queuedJobs) { + const pendingRecipients = + await BulkApplicationUpdateRecipient.countDocuments({ + jobId: queuedJob._id, + status: BulkApplicationRecipientStatus.PENDING, + }).exec(); + if (pendingRecipients === 0) continue; + + await scheduleJob(queuedJob._id.toString()); + } +} + +export async function reconcileApplicationStageUpdateLocks(): Promise { + const applications = await Application.find({ + "stageUpdateLock.operationId": { $exists: true }, + }) + .select("_id stage stageUpdateLock") + .exec(); + + for (const application of applications) { + const lock = application.stageUpdateLock; + if (!lock) continue; + + if ( + (application.stage === ApplicationStage.HIRED || + application.stage === ApplicationStage.REJECTED) && + lock.targetStage === application.stage + ) { + await releaseApplicationStageUpdateLock( + lock.operationId, + application._id.toString(), + ); + continue; + } + + if (!Types.ObjectId.isValid(lock.operationId)) continue; + + const completedRecipient = + await BulkApplicationUpdateRecipient.findOne({ + jobId: lock.operationId, + applicationId: application._id.toString(), + $or: [ + { + status: { + $in: [ + BulkApplicationRecipientStatus.SENT, + BulkApplicationRecipientStatus.UPDATED, + ], + }, + }, + { + status: BulkApplicationRecipientStatus.FAILED, + stageChangedAt: { $exists: false }, + }, + ], + }) + .select("_id") + .exec(); + + if (completedRecipient) { + await releaseApplicationStageUpdateLock( + lock.operationId, + application._id.toString(), + ); + } + } +} + // Define Agenda jobs here export const DefinedJobs: Record< string, @@ -311,6 +410,274 @@ 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) { + const interruptedEmailAttempt = + recipient.status === + BulkApplicationRecipientStatus.PROCESSING && + Boolean(recipient.emailAttemptStartedAt); + let application: IApplication | null = null; + recipient.status = BulkApplicationRecipientStatus.PROCESSING; + recipient.attempts += 1; + recipient.error = undefined; + recipient.failurePhase = undefined; + await recipient.save(); + + try { + if (interruptedEmailAttempt) { + recipient.status = + BulkApplicationRecipientStatus.FAILED; + recipient.failurePhase = "email"; + recipient.error = + "Email delivery is uncertain because processing stopped during the send attempt. An explicit retry may send a duplicate."; + await recipient.save(); + if (!recipient.stageChangedAt) { + await releaseApplicationStageUpdateLockSafely( + bulkJob._id.toString(), + recipient.applicationId, + ); + } + continue; + } + + 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(), + ); + const expectedLockStage = + recipient.stageChangedAt || existingBulkTransition + ? recipient.targetStage + : recipient.previousStage; + if (!expectedLockStage) { + throw new Error( + "Application stage cannot be reserved for this batch", + ); + } + + if ( + application.stageUpdateLock?.operationId !== + bulkJob._id.toString() + ) { + if (application.stageUpdateLock?.operationId) { + throw new Error( + "Application is reserved by another stage update", + ); + } + const lockAcquired = + await acquireApplicationStageUpdateLock( + recipient.applicationId, + bulkJob.teamPk, + expectedLockStage, + bulkJob._id.toString(), + recipient.targetStage, + ); + if (!lockAcquired) { + throw new Error( + "Application stage changed or another stage update is in progress", + ); + } + } + + if (!recipient.stageChangedAt) { + 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.targetStage === + ApplicationStage.POTENTIAL_HIRE + ) { + recipient.status = BulkApplicationRecipientStatus.UPDATED; + recipient.failurePhase = undefined; + recipient.error = undefined; + await recipient.save(); + await releaseApplicationStageUpdateLockSafely( + bulkJob._id.toString(), + recipient.applicationId, + ); + continue; + } + + if (!recipient.email || !recipient.applicantName) { + throw new Error( + "Applicant contact information is unavailable", + ); + } + + recipient.emailAttemptStartedAt = new Date(); + await recipient.save(); + + 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(); + await releaseApplicationStageUpdateLockSafely( + bulkJob._id.toString(), + recipient.applicationId, + ); + } catch (error: unknown) { + recipient.status = BulkApplicationRecipientStatus.FAILED; + recipient.failurePhase = + recipient.stageChangedAt && + recipient.targetStage !== + ApplicationStage.POTENTIAL_HIRE + ? "email" + : "stage"; + recipient.error = + error instanceof Error + ? error.message + : "Unknown recipient processing error"; + await recipient.save(); + if (!recipient.stageChangedAt) { + await releaseApplicationStageUpdateLockSafely( + bulkJob._id.toString(), + recipient.applicationId, + ); + } + } + } + + 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 @@ -323,3 +690,17 @@ export const RecurringJobs: RecurringJobSchedulingData[] = [ }, }, ]; + +async function releaseApplicationStageUpdateLockSafely( + operationId: string, + applicationId: string, +): Promise { + try { + await releaseApplicationStageUpdateLock(operationId, applicationId); + } catch (error: unknown) { + logger.error( + { err: error, applicationId, operationId }, + "Failed to release completed application stage update lock; reconciliation will retry", + ); + } +} diff --git a/peopleportal/server/src/clients/AgendaClient/index.ts b/peopleportal/server/src/clients/AgendaClient/index.ts index 80e2d185..e5569007 100644 --- a/peopleportal/server/src/clients/AgendaClient/index.ts +++ b/peopleportal/server/src/clients/AgendaClient/index.ts @@ -19,10 +19,26 @@ import mongoose from "mongoose"; import { Agenda } from "agenda"; import { MongoBackend } from "@agendajs/mongo-backend"; -import { DefinedJobs, JobSchedulingData, RecurringJobs } from "./Jobs"; +import { + DefinedJobs, + JobSchedulingData, + RecurringJobs, + reconcileApplicationStageUpdateLocks, + recoverQueuedBulkApplicationUpdates, +} from "./Jobs"; +import { logger } from "../../utils/logger"; + +// 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 static readonly ATS_RECOVERY_JOB = + "recoverQueuedBulkApplicationUpdates"; private agenda: Agenda | undefined; constructor() { @@ -41,6 +57,7 @@ export class AgendaClient { mongo: mongoose.connection.db!, }), processEvery: dbQueryInterval, + notificationChannel: new InMemoryNotificationChannel(), }); // Define all jobs @@ -50,6 +67,14 @@ export class AgendaClient { this.agenda!.define(key, job.workerFunction, job.options); }); + this.agenda!.define(AgendaClient.ATS_RECOVERY_JOB, async () => { + await this.reconcileAtsOperations(); + }); + await this.agenda!.every( + "5 minutes", + AgendaClient.ATS_RECOVERY_JOB, + ); + for (const entry of RecurringJobs) { // Agenda automatically checks for duplicates. /* Awaited: an unawaited every() swallowed scheduling failures, so a @@ -63,10 +88,41 @@ export class AgendaClient { } await this.agenda.start(); + try { + await this.reconcileAtsOperations(); + } catch (error: unknown) { + logger.error( + { err: error }, + "Initial ATS operation reconciliation failed; the recurring recovery job will retry", + ); + } } // Schedule a job to be run one time. public async scheduleJobOnce(jobData: JobSchedulingData) { + const payload = jobData.jobPayload; + if ( + jobData.jobName === "sendBulkApplicationUpdates" && + payload !== undefined && + typeof payload === "object" && + payload !== null && + "jobId" in payload && + typeof payload.jobId === "string" + ) { + await this.agenda! + .create(jobData.jobName, payload) + .unique( + { + name: jobData.jobName, + "data.jobId": payload.jobId, + }, + { insertOnly: true }, + ) + .schedule(jobData.runAt) + .save(); + return; + } + await this.agenda!.schedule( jobData.runAt, jobData.jobName, @@ -78,6 +134,17 @@ export class AgendaClient { public async cancelJob(jobName: string, jobData: object) { await this.agenda!.cancel({ name: jobName, data: jobData }); } + + private async reconcileAtsOperations(): Promise { + await recoverQueuedBulkApplicationUpdates(async (jobId) => { + await this.scheduleJobOnce({ + runAt: new Date(), + jobName: "sendBulkApplicationUpdates", + jobPayload: { jobId }, + }); + }); + await reconcileApplicationStageUpdateLocks(); + } } export const agendaClient = new AgendaClient(); diff --git a/peopleportal/server/src/clients/WebhookClient/index.ts b/peopleportal/server/src/clients/WebhookClient/index.ts new file mode 100644 index 00000000..0d447a49 --- /dev/null +++ b/peopleportal/server/src/clients/WebhookClient/index.ts @@ -0,0 +1,63 @@ +import { createHmac } from "crypto"; + +export interface WebhookEvent { + id: string; + type: string; + occurredAt: string; + data: Record; +} + +export type WebhookDeliveryStatus = "disabled" | "delivered"; + +const WEBHOOK_URL_ENV = "PEOPLEPORTAL_ATS_WEBHOOK_URL"; +const WEBHOOK_SECRET_ENV = "PEOPLEPORTAL_ATS_WEBHOOK_SECRET"; +const MIN_SECRET_LENGTH = 32; + +export class WebhookClient { + async send(event: WebhookEvent): Promise { + const endpoint = process.env[WEBHOOK_URL_ENV]?.trim(); + const secret = process.env[WEBHOOK_SECRET_ENV]; + + if (!endpoint && !secret) return "disabled"; + if (!endpoint || !secret) { + throw new Error( + `${WEBHOOK_URL_ENV} and ${WEBHOOK_SECRET_ENV} must be configured together`, + ); + } + if (secret.length < MIN_SECRET_LENGTH) { + throw new Error( + `${WEBHOOK_SECRET_ENV} must be at least ${MIN_SECRET_LENGTH} characters long`, + ); + } + + const url = new URL(endpoint); + const isLocalHttp = + url.protocol === "http:" && + ["localhost", "127.0.0.1", "::1"].includes(url.hostname); + if (url.protocol !== "https:" && !isLocalHttp) { + throw new Error("ATS webhook endpoint must use HTTPS"); + } + + const body = JSON.stringify(event); + const timestamp = Math.floor(Date.now() / 1000).toString(); + const signature = createHmac("sha256", secret) + .update(`${timestamp}.${body}`) + .digest("hex"); + const response = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-PeoplePortal-Event": event.type, + "X-PeoplePortal-Delivery": event.id, + "X-PeoplePortal-Signature": `t=${timestamp},v1=${signature}`, + }, + body, + signal: AbortSignal.timeout(10_000), + }); + + if (!response.ok) { + throw new Error(`ATS webhook returned HTTP ${response.status}`); + } + return "delivered"; + } +} \ No newline at end of file diff --git a/peopleportal/server/src/controllers/ATSController.ts b/peopleportal/server/src/controllers/ATSController.ts index 1d3a0902..065c1f11 100644 --- a/peopleportal/server/src/controllers/ATSController.ts +++ b/peopleportal/server/src/controllers/ATSController.ts @@ -46,9 +46,22 @@ import { Application, IApplication, ApplicationStage, + ApplicationEmailStatus, } from "../models/Application"; +import { + BulkApplicationRecipientStatus, + BulkApplicationUpdateJob, + BulkApplicationUpdateRecipient, + BulkApplicationUpdateStatus, +} from "../models/BulkApplicationUpdate"; +import { isValidApplicationStageTransition } from "../models/application-stage-transitions"; +import { + acquireApplicationStageUpdateLock, + releaseApplicationStageUpdateLock, +} from "../models/application-stage-update-lock"; import { Security } from "tsoa"; import * as express from "express"; +import { Types } from "mongoose"; import path from "path"; import { PutObjectCommand, @@ -61,6 +74,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 +122,13 @@ interface ATSUpdateApplicationStageRequest { hiredSubteamPk?: string; } +interface ATSBulkApplicationUpdateRequest { + applicationIds: string[]; + stage: ApplicationStage; + interviewLink?: string; + interviewGuidelines?: string; +} + interface ATSKanbanApplicationCard { id: string; applicantId: string; @@ -122,6 +143,12 @@ interface ATSKanbanApplicationCard { * @maximum 5 Maximum Stars is 5 */ stars: number; + stageUpdatePending?: boolean; + latestEmailUpdate?: { + stage: ApplicationStage; + status: BulkApplicationRecipientStatus | ApplicationEmailStatus; + updatedAt: Date; + }; } interface ATSApplicationDetails extends ATSKanbanApplicationCard { @@ -136,6 +163,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 @@ -766,7 +802,9 @@ export class ATSController extends Controller { const applications = await Application.find({ teamPk: teamId, }) - .select("applicantId stage rolePreferences appliedAt stars") + .select( + "applicantId stage rolePreferences appliedAt stars lastEmailUpdate stageUpdateLock", + ) .populate<{ applicantId: IApplicant }>( "applicantId", "fullName", @@ -774,17 +812,89 @@ 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 }, + targetStage: { + $in: [ + ApplicationStage.INTERVIEW, + ApplicationStage.REJECTED, + ], + }, + }) + .sort({ updatedAt: -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 latestBulkUpdate = latestUpdateByApplication.get( + app._id.toString(), + ); + const savedEmailUpdate = app.lastEmailUpdate; + const latestSingleEmailUpdate = + savedEmailUpdate?.stage && + savedEmailUpdate.status && + savedEmailUpdate.updatedAt + ? savedEmailUpdate + : undefined; + const latestUpdate = + latestSingleEmailUpdate && + (!latestBulkUpdate || + latestSingleEmailUpdate.updatedAt > + latestBulkUpdate.updatedAt) + ? { + stage: latestSingleEmailUpdate.stage, + status: latestSingleEmailUpdate.status, + updatedAt: + latestSingleEmailUpdate.updatedAt, + } + : latestBulkUpdate + ? { + stage: latestBulkUpdate.targetStage, + status: latestBulkUpdate.status, + updatedAt: latestBulkUpdate.updatedAt, + } + : undefined; + 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, + stageUpdatePending: Boolean( + app.stageUpdateLock?.operationId, + ), + ...(latestUpdate + ? { + latestEmailUpdate: { + stage: latestUpdate.stage, + status: latestUpdate.status, + updatedAt: latestUpdate.updatedAt, + }, + } + : {}), + }; + }, ); return kanbanData; @@ -827,6 +937,24 @@ export class ATSController extends Controller { return { error: "NotFound", message: "Application not found" }; } + const emailUpdates = + await BulkApplicationUpdateRecipient.find({ + teamPk: teamId, + applicationId: app._id.toString(), + targetStage: { + $in: [ + ApplicationStage.INTERVIEW, + ApplicationStage.REJECTED, + ], + }, + }) + .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 +969,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 @@ -1071,7 +1208,7 @@ export class ATSController extends Controller { * * - Transitions to **Interview** need Interview Guidelines and Link for Scheduling * - Transitions to **Rejected** directly send an email without additional information - * - Transitions to **Potential Hire** directly sends an email by auto populating contact info + * - Transitions to **Potential Hire** do not notify applicants * - Transtions to **Hired** happen based on a ruleset: * - If the user is an existing App Dev member, they are automatically added to the team * and an email is sent notifying them about the change. @@ -1099,6 +1236,7 @@ export class ATSController extends Controller { @Path() applicationId: string, @Body() body: ATSUpdateApplicationStageRequest, ) { + let stageUpdateLockId: string | undefined; try { const { stage, @@ -1158,26 +1296,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", @@ -1240,6 +1359,29 @@ export class ATSController extends Controller { application.hiredSubteamPk = hiredSubteamPk; } + const operationId = new Types.ObjectId().toString(); + const lockAcquired = await acquireApplicationStageUpdateLock( + application._id.toString(), + teamId, + currentStage, + operationId, + stage, + ); + if (!lockAcquired) { + this.setStatus(409); + return { + error: "UpdateInProgress", + message: + "This application has another stage update in progress. Refresh and try again.", + }; + } + stageUpdateLockId = operationId; + application.stageUpdateLock = { + operationId, + targetStage: stage, + lockedAt: new Date(), + }; + // Update stage and history application.stage = stage; application.stageHistory.push({ @@ -1251,22 +1393,47 @@ export class ATSController extends Controller { /* Save the Application and Send Emails */ await application.save(); + const sendEmailAndRecordOutcome = async ( + sendEmail: () => Promise, + ) => { + try { + await sendEmail(); + } catch (error: unknown) { + application.lastEmailUpdate = { + stage, + status: "failed", + updatedAt: new Date(), + }; + await application.save(); + throw error; + } + + application.lastEmailUpdate = { + stage, + status: "sent", + updatedAt: new Date(), + }; + await application.save(); + }; + /* Get Parent Team Information and Handle Stage Specific Logic */ if (stage === ApplicationStage.INTERVIEW) { - await this.emailClient.send({ - to: applicant.email, - cc: [req.session.authorizedUser!.email], - replyTo: [req.session.authorizedUser!.email], - subject: `Next Steps: ${teamInfo.attributes.friendlyName} Interview`, - templateName: "RecruitInterviewRequest", - templateVars: { - applicantName: applicant.fullName, - interviewerName: req.session.authorizedUser!.name, - teamName: teamInfo.attributes.friendlyName, - interviewLink: interviewLink, - interviewGuidelines: interviewGuidelines, - }, - }); + await sendEmailAndRecordOutcome(() => + this.emailClient.send({ + to: applicant.email, + cc: [req.session.authorizedUser!.email], + replyTo: [req.session.authorizedUser!.email], + subject: `Next Steps: ${teamInfo.attributes.friendlyName} Interview`, + templateName: "RecruitInterviewRequest", + templateVars: { + applicantName: applicant.fullName, + interviewerName: req.session.authorizedUser!.name, + teamName: teamInfo.attributes.friendlyName, + interviewLink: interviewLink, + interviewGuidelines: interviewGuidelines, + }, + }), + ); /* Potential Hire deliberately notifies nobody. It is an internal grouping the recruiting team uses while deciding, and the old "Waitlisted for ..." mail told applicants they had been passed @@ -1274,26 +1441,36 @@ export class ATSController extends Controller { 2026-09-02. The RecruitPotentialHireInfo template is kept for a future opt-in send. */ } else if (stage === ApplicationStage.HIRED) { - await this.processHiredStageTransition( - req.session.authorizedUser!, - teamInfo, - application, - applicant, + await sendEmailAndRecordOutcome(() => + this.processHiredStageTransition( + req.session.authorizedUser!, + teamInfo, + application, + applicant, + ), ); } else if (stage === ApplicationStage.REJECTED) { - await this.emailClient.send({ - to: applicant.email, - cc: [req.session.authorizedUser!.email], - replyTo: [req.session.authorizedUser!.email], - subject: `Update on ${teamInfo.attributes.friendlyName}`, - templateName: "RecruitApplicationDeclined", - templateVars: { - applicantName: applicant.fullName, - teamName: teamInfo.attributes.friendlyName, - }, - }); + await sendEmailAndRecordOutcome(() => + this.emailClient.send({ + to: applicant.email, + cc: [req.session.authorizedUser!.email], + replyTo: [req.session.authorizedUser!.email], + subject: `Update on ${teamInfo.attributes.friendlyName}`, + templateName: "RecruitApplicationDeclined", + templateVars: { + applicantName: applicant.fullName, + teamName: teamInfo.attributes.friendlyName, + }, + }), + ); } + await releaseApplicationStageUpdateLock( + stageUpdateLockId, + application._id.toString(), + ); + stageUpdateLockId = undefined; + return { message: "Stage updated successfully", application: { @@ -1303,6 +1480,19 @@ export class ATSController extends Controller { }, }; } catch (err) { + if (stageUpdateLockId) { + try { + await releaseApplicationStageUpdateLock( + stageUpdateLockId, + applicationId, + ); + } catch (releaseError) { + log.error( + { err: releaseError, applicationId }, + "Failed to release application stage update lock", + ); + } + } log.error({ err: err }, "Error updating application stage"); this.setStatus(500); return { @@ -1312,6 +1502,743 @@ export class ATSController extends Controller { } } + /** + * Creates a persistent batch stage-change job. Interview and Rejected send + * applicant emails; Potential Hire is an internal stage with no email. + */ + @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 && + body.stage !== ApplicationStage.POTENTIAL_HIRE + ) { + this.setStatus(400); + return { + error: "BadRequest", + message: + "Bulk stage updates are available only for Interview, Rejected, and Potential Hire", + }; + } + + 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; + let reservationOperationId: string | undefined; + 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 lockOperationId = job._id.toString(); + reservationOperationId = lockOperationId; + + const recipients = await Promise.all( + uniqueApplicationIds.map(async (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 (application.stageUpdateLock?.operationId) { + validationError = + "Another stage update is already in progress"; + } else if (!applicant) { + validationError = "Applicant is unavailable"; + } else if ( + body.stage !== ApplicationStage.POTENTIAL_HIRE && + (!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}`; + } + + if (!validationError) { + const lockAcquired = + await acquireApplicationStageUpdateLock( + applicationId, + teamId, + application.stage, + lockOperationId, + body.stage, + ); + if (!lockAcquired) { + validationError = + "Application stage changed or another stage update is in progress"; + } + } + + 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(); + await releaseApplicationStageUpdateLock( + lockOperationId, + ); + 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) { + if (reservationOperationId) { + try { + await releaseApplicationStageUpdateLock( + reservationOperationId, + ); + } catch (releaseError) { + console.error( + "Failed to release application stage update locks:", + releaseError, + ); + } + } + 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, + updated: + counts[BulkApplicationRecipientStatus.UPDATED] ?? 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: "stage", + targetStage: ApplicationStage.POTENTIAL_HIRE, + stageChangedAt: { $ne: null }, + }, + { failurePhase: "queue" }, + ], + }).exec(); + const lockableRecipients = []; + for (const recipient of retryableRecipients) { + const application = await Application.findOne({ + _id: recipient.applicationId, + teamPk: teamId, + }).exec(); + if (!application) continue; + + if (recipient.stageChangedAt) { + const belongsToJob = application.stageHistory.some( + (entry) => + entry.bulkJobId === job._id.toString() && + entry.stage === recipient.targetStage, + ); + if ( + !belongsToJob || + application.stage !== recipient.targetStage + ) { + continue; + } + } + + if ( + application.stageUpdateLock?.operationId === + job._id.toString() + ) { + lockableRecipients.push(recipient); + continue; + } + + if (application.stageUpdateLock?.operationId) continue; + + const expectedStage = recipient.stageChangedAt + ? recipient.targetStage + : recipient.previousStage; + if ( + expectedStage && + (await acquireApplicationStageUpdateLock( + recipient.applicationId, + teamId, + expectedStage, + job._id.toString(), + recipient.targetStage, + )) + ) { + lockableRecipients.push(recipient); + } + } + + if (!lockableRecipients.length) { + this.setStatus(409); + return { + error: "NoRetryableRecipients", + message: + "This batch has no eligible failed recipients to retry", + }; + } + + const retryableRecipientIds = lockableRecipients.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, + emailAttemptStartedAt: 1, + sentAt: 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(); + await Application.updateMany( + { + "stageUpdateLock.operationId": job._id.toString(), + _id: { + $in: lockableRecipients + .filter((recipient) => !recipient.stageChangedAt) + .map((recipient) => recipient.applicationId), + }, + }, + { $unset: { stageUpdateLock: 1 } }, + ).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..7d161501 100644 --- a/peopleportal/server/src/models/Application.ts +++ b/peopleportal/server/src/models/Application.ts @@ -26,6 +26,8 @@ export enum ApplicationStage { HIRED = "Hired", } +export type ApplicationEmailStatus = "sent" | "failed"; + export interface IApplication extends Document { applicantId: Schema.Types.ObjectId; teamPk: string; @@ -37,7 +39,18 @@ export interface IApplication extends Document { stage: ApplicationStage; changedAt: Date; changedBy?: string; + bulkJobId?: string; }>; + lastEmailUpdate?: { + stage: ApplicationStage; + status: ApplicationEmailStatus; + updatedAt: Date; + }; + stageUpdateLock?: { + operationId: string; + targetStage: ApplicationStage; + lockedAt: Date; + }; hiredRole?: string; hiredSubteamPk?: string; appDevInternalPk?: number; @@ -90,8 +103,28 @@ const ApplicationSchema = new Schema( }, changedAt: { type: Date, default: Date.now }, changedBy: { type: String }, + bulkJobId: { type: String }, }, ], + lastEmailUpdate: { + stage: { + type: String, + enum: Object.values(ApplicationStage), + }, + status: { + type: String, + enum: ["sent", "failed"], + }, + updatedAt: { type: Date }, + }, + stageUpdateLock: { + operationId: { type: String }, + targetStage: { + type: String, + enum: Object.values(ApplicationStage), + }, + lockedAt: { type: Date }, + }, hiredRole: { type: String, required: false }, hiredSubteamPk: { type: String, required: false }, stars: { type: Number, required: true, default: 0, min: 0, max: 5 }, diff --git a/peopleportal/server/src/models/BulkApplicationUpdate.ts b/peopleportal/server/src/models/BulkApplicationUpdate.ts new file mode 100644 index 00000000..6296ca64 --- /dev/null +++ b/peopleportal/server/src/models/BulkApplicationUpdate.ts @@ -0,0 +1,159 @@ +/** + 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", + UPDATED = "updated", + 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; + emailAttemptStartedAt?: 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 }, + emailAttemptStartedAt: { 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/models/application-stage-update-lock.ts b/peopleportal/server/src/models/application-stage-update-lock.ts new file mode 100644 index 00000000..51d56f18 --- /dev/null +++ b/peopleportal/server/src/models/application-stage-update-lock.ts @@ -0,0 +1,42 @@ +import { Application, ApplicationStage } from "./Application"; + +export async function acquireApplicationStageUpdateLock( + applicationId: string, + teamPk: string, + expectedStage: ApplicationStage, + operationId: string, + targetStage: ApplicationStage, +): Promise { + const result = await Application.updateOne( + { + _id: applicationId, + teamPk, + stage: expectedStage, + "stageUpdateLock.operationId": { $exists: false }, + }, + { + $set: { + stageUpdateLock: { + operationId, + targetStage, + lockedAt: new Date(), + }, + }, + }, + ).exec(); + + return result.modifiedCount === 1; +} + +export async function releaseApplicationStageUpdateLock( + operationId: string, + applicationId?: string, +): Promise { + await Application.updateMany( + { + "stageUpdateLock.operationId": operationId, + ...(applicationId ? { _id: applicationId } : {}), + }, + { $unset: { stageUpdateLock: 1 } }, + ).exec(); +} diff --git a/peopleportal/server/src/routes.ts b/peopleportal/server/src/routes.ts index 4a19fa81..80775ba5 100644 --- a/peopleportal/server/src/routes.ts +++ b/peopleportal/server/src/routes.ts @@ -1079,6 +1079,16 @@ 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","updated","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 + "ApplicationEmailStatus": { + "dataType": "refAlias", + "type": {"dataType":"union","subSchemas":[{"dataType":"enum","enums":["sent"]},{"dataType":"enum","enums":["failed"]}],"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 "ATSKanbanApplicationCard": { "dataType": "refObject", "properties": { @@ -1089,6 +1099,8 @@ 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}}}, + "stageUpdatePending": {"dataType":"boolean"}, + "latestEmailUpdate": {"dataType":"nestedObjectLiteral","nestedProperties":{"updatedAt":{"dataType":"datetime","required":true},"status":{"dataType":"union","subSchemas":[{"ref":"BulkApplicationRecipientStatus"},{"ref":"ApplicationEmailStatus"}],"required":true},"stage":{"ref":"ApplicationStage","required":true}}}, }, "additionalProperties": false, }, @@ -1103,6 +1115,8 @@ 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}}}, + "stageUpdatePending": {"dataType":"boolean"}, + "latestEmailUpdate": {"dataType":"nestedObjectLiteral","nestedProperties":{"updatedAt":{"dataType":"datetime","required":true},"status":{"dataType":"union","subSchemas":[{"ref":"BulkApplicationRecipientStatus"},{"ref":"ApplicationEmailStatus"}],"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 +1124,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 +1141,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 +3927,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/application-stage-emails.test.js b/peopleportal/server/test/integration/application-stage-emails.test.js index 428f6b3d..c8e0e7c3 100644 --- a/peopleportal/server/test/integration/application-stage-emails.test.js +++ b/peopleportal/server/test/integration/application-stage-emails.test.js @@ -131,6 +131,120 @@ test("no email sent to Potential Hire mentions being waitlisted", async () => { assert.doesNotMatch(wording, /RecruitPotentialHireInfo/); }); +test("a successful single-stage email is persisted and returned for the board", async () => { + const { application } = await seedApplication(ApplicationStage.APPLIED); + const { controller } = controllerWithCapturedEmail(); + + const result = await controller.updateApplicationStage( + recruiterRequest(), TEAM_PK, String(application._id), + { + stage: ApplicationStage.INTERVIEW, + interviewLink: "https://example.invalid/interview", + interviewGuidelines: "Please prepare to discuss your recent work and interests.", + } + ); + + assert.equal(result.error, undefined); + const reloaded = await Application.findById(application._id); + assert.equal(reloaded.lastEmailUpdate.stage, ApplicationStage.INTERVIEW); + assert.equal(reloaded.lastEmailUpdate.status, "sent"); + + const [card] = await controller.getTeamApplications(TEAM_PK); + assert.equal(card.latestEmailUpdate.stage, ApplicationStage.INTERVIEW); + assert.equal(card.latestEmailUpdate.status, "sent"); +}); + +test("a failed single-stage email is persisted and returned for the board", async () => { + const { application } = await seedApplication(ApplicationStage.APPLIED); + const { controller } = controllerWithCapturedEmail(); + controller.emailClient.send = async () => { + throw new Error("Email provider unavailable"); + }; + + const result = await controller.updateApplicationStage( + recruiterRequest(), TEAM_PK, String(application._id), + { + stage: ApplicationStage.INTERVIEW, + interviewLink: "https://example.invalid/interview", + interviewGuidelines: "Please prepare to discuss your recent work and interests.", + } + ); + + assert.equal(result.error, "ServerError"); + const reloaded = await Application.findById(application._id); + assert.equal(reloaded.stage, ApplicationStage.INTERVIEW); + assert.equal(reloaded.lastEmailUpdate.stage, ApplicationStage.INTERVIEW); + assert.equal(reloaded.lastEmailUpdate.status, "failed"); + + const [card] = await controller.getTeamApplications(TEAM_PK); + assert.equal(card.latestEmailUpdate.status, "failed"); +}); + +test("a successful Hired transition records its email outcome", async () => { + const { application } = await seedApplication(ApplicationStage.INTERVIEW); + const { controller } = controllerWithCapturedEmail(); + controller.isValidHireDestination = async () => true; + controller.processHiredStageTransition = async () => undefined; + + const result = await controller.updateApplicationStage( + recruiterRequest(), TEAM_PK, String(application._id), + { + stage: ApplicationStage.HIRED, + hiredRole: "Software Engineer", + hiredSubteamPk: "subteam-webdev-frontend", + } + ); + + assert.equal(result.error, undefined); + const reloaded = await Application.findById(application._id); + assert.equal(reloaded.lastEmailUpdate.stage, ApplicationStage.HIRED); + assert.equal(reloaded.lastEmailUpdate.status, "sent"); + + const [card] = await controller.getTeamApplications(TEAM_PK); + assert.equal(card.latestEmailUpdate.stage, ApplicationStage.HIRED); + assert.equal(card.latestEmailUpdate.status, "sent"); +}); + +test("a confirmed single-stage update blocks conflicting requests until it finishes", async () => { + const { application } = await seedApplication(ApplicationStage.APPLIED); + const { controller } = controllerWithCapturedEmail(); + let releaseEmail; + let signalEmailStarted; + const emailStarted = new Promise((resolve) => { + signalEmailStarted = resolve; + }); + controller.emailClient.send = async () => { + signalEmailStarted(); + await new Promise((resolve) => { + releaseEmail = resolve; + }); + }; + + const firstUpdate = controller.updateApplicationStage( + recruiterRequest(), TEAM_PK, String(application._id), + { + stage: ApplicationStage.INTERVIEW, + interviewLink: "https://example.invalid/interview", + interviewGuidelines: "Please prepare to discuss your recent work and interests.", + } + ); + await emailStarted; + + const conflictingUpdate = await controller.updateApplicationStage( + recruiterRequest(), TEAM_PK, String(application._id), + { stage: ApplicationStage.REJECTED } + ); + assert.equal(conflictingUpdate.error, "UpdateInProgress"); + + releaseEmail(); + const completedUpdate = await firstUpdate; + assert.equal(completedUpdate.error, undefined); + assert.equal( + (await Application.findById(application._id)).stageUpdateLock?.operationId, + undefined, + ); +}); + test("the stage change itself still persists", async () => { const { application } = await seedApplication(ApplicationStage.INTERVIEW); const { controller } = controllerWithCapturedEmail(); @@ -168,17 +282,30 @@ test("Potential Hire cannot be reached directly from Applied", async () => { assert.deepEqual(sent, []); }); -test("Hired and Rejected are terminal", async () => { +test("Hired and Rejected cannot move to any other stage", async () => { for (const terminal of [ApplicationStage.HIRED, ApplicationStage.REJECTED]) { - const { application } = await seedApplication(terminal); - const { controller } = controllerWithCapturedEmail(); - - const result = await controller.updateApplicationStage( - recruiterRequest(), TEAM_PK, String(application._id), - { stage: ApplicationStage.INTERVIEW } - ); - - assert.equal(result.error, "BadRequest", `${terminal} should accept no onward transition`); + for (const target of Object.values(ApplicationStage)) { + if (target === terminal) continue; + + const { application } = await seedApplication(terminal); + const { controller, sent } = controllerWithCapturedEmail(); + const originalHistoryLength = application.stageHistory.length; + + const result = await controller.updateApplicationStage( + recruiterRequest(), TEAM_PK, String(application._id), + { stage: target } + ); + + assert.equal( + result.error, + "BadRequest", + `${terminal} should not transition to ${target}`, + ); + const unchanged = await Application.findById(application._id); + assert.equal(unchanged.stage, terminal); + assert.equal(unchanged.stageHistory.length, originalHistoryLength); + assert.deepEqual(sent, []); + } } }); 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..91e9abf4 --- /dev/null +++ b/peopleportal/server/test/integration/bulk-application-updates.test.js @@ -0,0 +1,589 @@ +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, + BulkApplicationUpdateStatus, +} = 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, + reconcileApplicationStageUpdateLocks, + recoverQueuedBulkApplicationUpdates, +} = require("../../dist/clients/AgendaClient/Jobs/index.js"); +const stageUpdateLocks = require("../../dist/models/application-stage-update-lock.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("reserves queued applications against conflicting single and bulk updates", async () => { + const { application } = await seedApplication(); + const controller = controllerWithTeam(); + + const queued = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + interviewPayload([String(application._id)]), + ); + assert.equal(queued.queued, true); + + const reservedApplication = await Application.findById(application._id); + assert.equal( + reservedApplication.stageUpdateLock.operationId, + queued.jobId, + ); + + const singleUpdate = await controller.updateApplicationStage( + recruiterRequest(), + TEAM_PK, + String(application._id), + { stage: ApplicationStage.REJECTED }, + ); + assert.equal(singleUpdate.error, "UpdateInProgress"); + + const overlappingBatch = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + { + applicationIds: [String(application._id)], + stage: ApplicationStage.REJECTED, + }, + ); + assert.equal(overlappingBatch.queuedRecipients, 0); + assert.equal(overlappingBatch.validationFailedRecipients, 1); + assert.equal(scheduledJobs.length, 1); + + const [card] = await controller.getTeamApplications(TEAM_PK); + assert.equal(card.stageUpdatePending, true); +}); + +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"); + assert.equal(updatedApplication.stageUpdateLock?.operationId, undefined); + assert.equal( + (await controller.getTeamApplications(TEAM_PK))[0].stageUpdatePending, + false, + ); +}); + +test("a lock-release failure does not overwrite a successful email outcome", async () => { + const { application } = await seedApplication(); + const controller = controllerWithTeam(); + const created = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + { + applicationIds: [String(application._id)], + stage: ApplicationStage.REJECTED, + }, + ); + const originalRelease = + stageUpdateLocks.releaseApplicationStageUpdateLock; + stageUpdateLocks.releaseApplicationStageUpdateLock = async () => { + throw new Error("Mongo temporarily unavailable"); + }; + EmailClient.prototype.send = async () => undefined; + + try { + await DefinedJobs.sendBulkApplicationUpdates.workerFunction({ + attrs: { data: { jobId: created.jobId } }, + }); + } finally { + stageUpdateLocks.releaseApplicationStageUpdateLock = originalRelease; + } + + const recipient = await BulkApplicationUpdateRecipient.findOne({ + jobId: created.jobId, + applicationId: String(application._id), + }); + assert.equal(recipient.status, BulkApplicationRecipientStatus.SENT); + assert.ok(recipient.sentAt); + assert.equal( + (await Application.findById(application._id)).stageUpdateLock.operationId, + created.jobId, + ); + + await reconcileApplicationStageUpdateLocks(); + const reconciledApplication = await Application.findById(application._id); + assert.equal(reconciledApplication.stage, ApplicationStage.REJECTED); + assert.equal(reconciledApplication.stageUpdateLock?.operationId, undefined); +}); + +test("recovery requeues only persisted queued batches with pending recipients", async () => { + const { application: queuedApplication } = await seedApplication(); + const { application: processingApplication } = await seedApplication(); + const controller = controllerWithTeam(); + const queuedBatch = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + interviewPayload([String(queuedApplication._id)]), + ); + const processingBatch = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + interviewPayload([String(processingApplication._id)]), + ); + await BulkApplicationUpdateJob.updateOne( + { _id: processingBatch.jobId }, + { $set: { status: BulkApplicationUpdateStatus.PROCESSING } }, + ); + + const recoveredJobIds = []; + await recoverQueuedBulkApplicationUpdates(async (jobId) => { + recoveredJobIds.push(jobId); + }); + + assert.deepEqual(recoveredJobIds, [queuedBatch.jobId]); +}); + +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, + }, + ); + let sendAttempts = 0; + EmailClient.prototype.send = async () => { + sendAttempts += 1; + 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); + assert.ok(failedRecipient.emailAttemptStartedAt); + assert.equal( + (await Application.findById(application._id)).stageUpdateLock.operationId, + created.jobId, + ); + + await DefinedJobs.sendBulkApplicationUpdates.workerFunction({ + attrs: { data: { jobId: created.jobId } }, + }); + assert.equal(sendAttempts, 1, "failed email must not retry automatically"); + + const originalHistoryLength = ( + await Application.findById(application._id) + ).stageHistory.length; + let retriedEmail; + EmailClient.prototype.send = async (request) => { + sendAttempts += 1; + 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); + assert.equal(finalApplication.stageUpdateLock?.operationId, undefined); + assert.ok(completedRecipient.emailAttemptStartedAt); +}); + +test("a worker restart does not resend an email with an uncertain outcome", async () => { + const { application } = await seedApplication(); + const controller = controllerWithTeam(); + const created = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + { + applicationIds: [String(application._id)], + stage: ApplicationStage.REJECTED, + }, + ); + const recipient = await BulkApplicationUpdateRecipient.findOne({ + jobId: created.jobId, + }); + const changedAt = new Date(); + const applicationDoc = await Application.findById(application._id); + applicationDoc.stage = ApplicationStage.REJECTED; + applicationDoc.stageHistory.push({ + stage: ApplicationStage.REJECTED, + changedAt, + changedBy: "Recruiter (recruiter)", + bulkJobId: created.jobId, + }); + await applicationDoc.save(); + + recipient.status = BulkApplicationRecipientStatus.PROCESSING; + recipient.stageChangedAt = changedAt; + recipient.emailAttemptStartedAt = new Date(); + await recipient.save(); + + let sendAttempts = 0; + EmailClient.prototype.send = async () => { + sendAttempts += 1; + }; + await DefinedJobs.sendBulkApplicationUpdates.workerFunction({ + attrs: { data: { jobId: created.jobId } }, + }); + + const interruptedRecipient = + await BulkApplicationUpdateRecipient.findById(recipient._id); + assert.equal(sendAttempts, 0); + assert.equal( + interruptedRecipient.status, + BulkApplicationRecipientStatus.FAILED, + ); + assert.equal(interruptedRecipient.failurePhase, "email"); + assert.match(interruptedRecipient.error, /delivery is uncertain/i); + assert.equal( + (await Application.findById(application._id)).stageUpdateLock + ?.operationId, + created.jobId, + ); + + const retryResult = await controller.retryBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + created.jobId, + ); + assert.equal(retryResult.queuedRecipients, 1); + const retryingRecipient = + await BulkApplicationUpdateRecipient.findById(recipient._id); + assert.equal(retryingRecipient.emailAttemptStartedAt, undefined); +}); + +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); + assert.equal( + (await Application.findById(application._id)).stageUpdateLock?.operationId, + undefined, + ); + + 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( + (await Application.findById(application._id)).stageUpdateLock?.operationId, + created.jobId, + ); + assert.equal(queuedRecipient.status, BulkApplicationRecipientStatus.PENDING); + assert.equal(queuedRecipient.stageChangedAt, undefined); + assert.equal(scheduledJobs.length, 1); + + EmailClient.prototype.send = async () => undefined; + await DefinedJobs.sendBulkApplicationUpdates.workerFunction({ + attrs: { data: { jobId: created.jobId } }, + }); + assert.equal( + (await BulkApplicationUpdateRecipient.findById(failedRecipient._id)).status, + BulkApplicationRecipientStatus.SENT, + ); + assert.equal( + (await Application.findById(application._id)).stageUpdateLock + ?.operationId, + undefined, + ); +}); + +test("Potential Hire batches update stages without sending applicant email", async () => { + const { applicant, application } = await seedApplication( + ApplicationStage.INTERVIEW, + ); + const controller = controllerWithTeam(); + + const result = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + { + applicationIds: [String(application._id)], + stage: ApplicationStage.POTENTIAL_HIRE, + }, + ); + + assert.equal(result.queued, true); + assert.equal(result.queuedRecipients, 1); + assert.equal(scheduledJobs.length, 1); + + const sent = []; + EmailClient.prototype.send = async (request) => { + sent.push(request); + }; + await DefinedJobs.sendBulkApplicationUpdates.workerFunction({ + attrs: { data: { jobId: result.jobId } }, + }); + + const updatedApplication = await Application.findById(application._id); + const recipient = await BulkApplicationUpdateRecipient.findOne({ + jobId: result.jobId, + applicationId: String(application._id), + }); + const summaries = await controller.getBulkApplicationUpdates( + recruiterRequest(), + TEAM_PK, + ); + + assert.equal(updatedApplication.stage, ApplicationStage.POTENTIAL_HIRE); + assert.equal(updatedApplication.stageHistory.at(-1).bulkJobId, result.jobId); + assert.equal(recipient.status, BulkApplicationRecipientStatus.UPDATED); + assert.equal(recipient.email, applicant.email); + assert.equal(sent.length, 0); + assert.equal( + summaries.find((summary) => summary.jobId === result.jobId).counts.updated, + 1, + ); +}); + +test("bulk updates do not support Hired transitions", async () => { + const { application } = await seedApplication(ApplicationStage.INTERVIEW); + const controller = controllerWithTeam(); + + const result = await controller.createBulkApplicationUpdate( + recruiterRequest(), + TEAM_PK, + { + applicationIds: [String(application._id)], + stage: ApplicationStage.HIRED, + }, + ); + + assert.equal(result.error, "BadRequest"); + assert.equal(scheduledJobs.length, 0); +}); diff --git a/peopleportal/server/test/unit/ats-webhook.test.js b/peopleportal/server/test/unit/ats-webhook.test.js new file mode 100644 index 00000000..a1b8cb8f --- /dev/null +++ b/peopleportal/server/test/unit/ats-webhook.test.js @@ -0,0 +1,87 @@ +const assert = require("node:assert/strict"); +const { createHmac } = require("node:crypto"); +const test = require("node:test"); + +const { WebhookClient } = require("../../dist/clients/WebhookClient/index.js"); + +const URL_ENV = "PEOPLEPORTAL_ATS_WEBHOOK_URL"; +const SECRET_ENV = "PEOPLEPORTAL_ATS_WEBHOOK_SECRET"; +const originalUrl = process.env[URL_ENV]; +const originalSecret = process.env[SECRET_ENV]; + +test.afterEach(() => { + if (originalUrl === undefined) delete process.env[URL_ENV]; + else process.env[URL_ENV] = originalUrl; + if (originalSecret === undefined) delete process.env[SECRET_ENV]; + else process.env[SECRET_ENV] = originalSecret; +}); + +test("webhook delivery signs the exact event body and includes its event type", async () => { + const secret = "a".repeat(32); + process.env[URL_ENV] = "http://localhost:9000/ats"; + process.env[SECRET_ENV] = secret; + let delivered; + const originalFetch = global.fetch; + global.fetch = async (url, options) => { + delivered = { url: String(url), options }; + return new Response(null, { status: 204 }); + }; + + try { + const event = { + id: "batch-123", + type: "ats.application-stage-batch.completed", + occurredAt: "2026-11-16T00:00:00.000Z", + data: { teamId: "team-a", results: [] }, + }; + assert.equal(await new WebhookClient().send(event), "delivered"); + assert.equal(delivered.url, process.env[URL_ENV]); + assert.equal( + delivered.options.headers["X-PeoplePortal-Event"], + event.type + ); + assert.equal( + delivered.options.headers["X-PeoplePortal-Delivery"], + event.id + ); + const [timestamp, signature] = delivered.options.headers[ + "X-PeoplePortal-Signature" + ] + .split(",") + .map((part) => part.split("=")[1]); + const expected = createHmac("sha256", secret) + .update(`${timestamp}.${delivered.options.body}`) + .digest("hex"); + assert.equal(signature, expected); + assert.deepEqual(JSON.parse(delivered.options.body), event); + } finally { + global.fetch = originalFetch; + } +}); + +test("webhook delivery is disabled when no endpoint is configured", async () => { + delete process.env[URL_ENV]; + delete process.env[SECRET_ENV]; + assert.equal( + await new WebhookClient().send({ id: "batch", type: "event", data: {} }), + "disabled" + ); +}); + +test("webhook endpoint and secret must be configured together", async () => { + process.env[URL_ENV] = "https://hooks.example.invalid/ats"; + delete process.env[SECRET_ENV]; + await assert.rejects( + new WebhookClient().send({ id: "batch", type: "event", data: {} }), + /must be configured together/ + ); +}); + +test("webhook delivery rejects non-local insecure endpoints", async () => { + process.env[URL_ENV] = "http://hooks.example.invalid/ats"; + process.env[SECRET_ENV] = "a".repeat(32); + await assert.rejects( + new WebhookClient().send({ id: "batch", type: "event", data: {} }), + /must use HTTPS/ + ); +}); \ No newline at end of file diff --git a/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.test.tsx b/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.test.tsx index d9375394..747efa50 100644 --- a/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.test.tsx +++ b/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.test.tsx @@ -7,7 +7,7 @@ import { waitFor, } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { StrictMode } from "react"; +import { StrictMode, type ComponentProps } from "react"; import { createMemoryRouter, RouterProvider } from "react-router-dom"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { DashboardTeamRecruitment } from "./DashboardTeamRecuitment"; @@ -17,6 +17,34 @@ import { type RecruitmentDetails, } from "./recruitment-queries"; +vi.mock("@/components/ui/shadcn-io/kanban", async (importOriginal) => { + const actual = + await importOriginal< + typeof import("@/components/ui/shadcn-io/kanban") + >(); + return { + ...actual, + KanbanProvider: ( + props: ComponentProps, + ) => ( + <> + + + + ), + }; +}); + const basePath = "/org/teams/team-a/recruitment"; const apiPath = "/api/ats/applications/team-a"; const makeApplication = (id: string): RecruitmentApplication => ({ @@ -41,10 +69,17 @@ function deferred() { let applications: RecruitmentApplication[]; let details: Map; -let requests: { path: string; signal: AbortSignal | null | undefined }[]; +let queuedStage: string; +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,17 +90,24 @@ beforeEach(() => { profile: { whyAppDev: `Background ${application.id}` }, responses: {}, notes: `Notes ${application.id}`, + emailUpdates: [], }, ]), ); requests = []; + queuedStage = "Rejected"; responses = new Map(); // Fake HTTP is the boundary; the router, query client, dialogs are real. vi.stubGlobal( "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 +132,42 @@ beforeEach(() => { "Hired", ].map((id) => ({ id, name: id })), ); + if (path === `${apiPath}/bulk-updates`) { + if (init?.method === "POST") { + queuedStage = JSON.parse(String(init.body)).stage; + 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: queuedStage, + status: "queued", + createdAt: "2026-09-01T12:00:00.000Z", + recipients: [ + { + applicationId: "a", + applicantName: "Applicant A", + targetStage: queuedStage, + status: + queuedStage === "Potential Hire" + ? "updated" + : "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`) @@ -131,7 +209,9 @@ function openBoard(search = "") { } async function openA() { - await userEvent.click(await screen.findByText("Applicant A")); + await userEvent.dblClick( + await screen.findByRole("button", { name: /Applicant A/ }), + ); await screen.findByText("Background a"); await screen.findByRole("link", { name: /Open resume/ }); } @@ -182,7 +262,9 @@ describe("recruitment review", () => { responses.set(`${apiPath}/person-a/resume`, slowResume.promise); responses.set(`${apiPath}/person-a/otherapps`, slowHistory.promise); openBoard(); - await userEvent.click(await screen.findByText("Applicant A")); + await userEvent.dblClick( + await screen.findByRole("button", { name: /Applicant A/ }), + ); expect( screen.getByText("Loading other applications…"), ).toBeInTheDocument(); @@ -261,4 +343,233 @@ 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("button", { name: /Applicant A/ }), + ); + await userEvent.click( + screen.getByRole("button", { name: "Update selected (1)" }), + ); + const stageSelect = screen.getByRole("combobox", { + name: "New application stage", + }); + stageSelect.focus(); + await userEvent.keyboard("{ENTER}{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("queues Potential Hire as a stage-only batch", async () => { + openBoard(); + await userEvent.click( + await screen.findByRole("button", { name: /Applicant A/ }), + ); + await userEvent.click( + screen.getByRole("button", { name: "Update selected (1)" }), + ); + const stageSelect = screen.getByRole("combobox", { + name: "New application stage", + }); + stageSelect.focus(); + await userEvent.keyboard("{ENTER}{ARROWDOWN}{ARROWDOWN}{ENTER}"); + expect( + screen.getByText(/Applicants will not be emailed/), + ).toBeInTheDocument(); + 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("Moved: 1"); + expect(progressDialog).not.toHaveTextContent("updated (no email)"); + + const submittedRequest = requests.find( + (request) => + request.path === `${apiPath}/bulk-updates` && + request.method === "POST", + ); + expect(JSON.parse(String(submittedRequest?.body))).toEqual({ + applicationIds: ["a"], + stage: "Potential Hire", + }); + }); + + it("uses a selected-card drag to confirm and queue the whole selection", async () => { + openBoard(); + await userEvent.click( + await screen.findByRole("button", { name: /Applicant A/ }), + ); + await userEvent.click( + screen.getByRole("button", { name: /Applicant B/ }), + ); + + await userEvent.click( + screen.getByRole("button", { + name: "Simulate selected group drag", + }), + ); + + expect( + await screen.findByText("Interview scheduling link"), + ).toBeInTheDocument(); + expect( + screen.getByText( + /Click cards to select; double-click to open details\..*Drag a selected card to a status to queue the group \(Hired excluded\)\./, + ), + ).toBeInTheDocument(); + + await userEvent.type( + screen.getByPlaceholderText("https://..."), + "https://example.invalid/interview", + ); + await userEvent.type( + screen.getByPlaceholderText( + "50-500 characters", + ), + "Please prepare to discuss your recent work and interests.", + ); + await userEvent.click( + screen.getByRole("button", { + name: "Queue update for 2 applicants", + }), + ); + + const submittedRequest = requests.find( + (request) => + request.path === `${apiPath}/bulk-updates` && + request.method === "POST", + ); + expect(JSON.parse(String(submittedRequest?.body))).toEqual({ + applicationIds: ["a", "b"], + stage: "Interview", + interviewLink: "https://example.invalid/interview", + interviewGuidelines: + "Please prepare to discuss your recent work and interests.", + }); + }); + + it("shows a sent-email indicator and batch email history without timestamps", 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(); + expect( + await screen.findByRole("img", { + name: "Email sent for Rejected", + }), + ).toBeInTheDocument(); + await openA(); + + expect(screen.getByText("Batch email history")).toBeInTheDocument(); + expect(screen.getByText("Attempts: 1")).toBeInTheDocument(); + expect(screen.queryByText(/Sent 2026/)).not.toBeInTheDocument(); + expect(screen.queryByText(/updated \(no email\)/)).not.toBeInTheDocument(); + }); + + it("shows a failed-email indicator for a single-card stage update", async () => { + applications[0].latestEmailUpdate = { + stage: "Hired", + status: "failed", + updatedAt: "2026-09-01T12:00:00.000Z", + }; + + openBoard(); + + expect( + await screen.findByRole("img", { + name: "Email not sent for Hired", + }), + ).toBeInTheDocument(); + }); + + it("disables selecting a card while its confirmed stage update is pending", async () => { + applications[0].stageUpdatePending = true; + + openBoard(); + + expect( + await screen.findByRole("button", { name: /Applicant A/ }), + ).toHaveAttribute("aria-disabled", "true"); + expect(screen.queryByText("Update pending")).not.toBeInTheDocument(); + }); + + it("selects and highlights a card on click without a checkbox", async () => { + openBoard(); + const applicantCard = await screen.findByRole("button", { + name: /Applicant A/, + }); + + await userEvent.click(applicantCard); + + expect(applicantCard).toHaveAttribute("aria-pressed", "true"); + expect(applicantCard.querySelector(".ring-primary")).toBeInTheDocument(); + expect( + screen.queryByRole("checkbox", { name: /Applicant A/ }), + ).not.toBeInTheDocument(); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + }); + + it("opens applicant details on double-click", async () => { + const { router } = openBoard(); + await userEvent.dblClick( + await screen.findByRole("button", { name: /Applicant A/ }), + ); + + expect(await screen.findByText("Background a")).toBeInTheDocument(); + expect(router.state.location.search).toBe("?application=a"); + }); + + it.each(["Rejected", "Hired"])( + "prevents dragging terminal %s applications", + async (terminalStage) => { + applications[0].stage = terminalStage; + + openBoard(); + + expect( + await screen.findByRole("button", { + name: /Applicant A/, + }), + ).toHaveAttribute("aria-disabled", "true"); + }, + ); }); diff --git a/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.tsx b/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.tsx index d3252721..79d89973 100644 --- a/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.tsx +++ b/peopleportal/webui/src/components/fabric/DashboardTeamRecuitment.tsx @@ -45,6 +45,8 @@ import { Loader2, Loader2Icon, ExternalLinkIcon, + CheckIcon, + XIcon, ChevronLeft, ChevronRight, MailIcon, @@ -101,6 +103,101 @@ 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; + updated: 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; + stageChangedAt?: string; + sentAt?: string; + createdAt: string; + }[]; +} + +function EmailStatusIndicator({ + status, + stage, +}: { + status: string; + stage: string; +}) { + if (status === "updated") return null; + + const sent = status === "sent"; + const failed = status === "failed" || status === "validation_failed"; + const label = sent + ? `Email sent for ${stage}` + : failed + ? `Email not sent for ${stage}` + : `Email ${status.replace(/_/g, " ")} for ${stage}`; + + return ( + + + {sent ? ( + + ) : failed ? ( + + ) : null} + + ); +} + +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 +239,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 +273,32 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { [key: string]: { [key: string]: string[] }; }>({}); + const [selectedApplicationIds, setSelectedApplicationIds] = React.useState< + string[] + >([]); + const [bulkUpdateDialogOpen, setBulkUpdateDialogOpen] = + React.useState(false); + const [bulkDragTargetStage, setBulkDragTargetStage] = React.useState< + string | null + >(null); + 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"], @@ -279,6 +403,13 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { newStage: string, ) { if (currentStage === newStage || isStageSubmitting) return; + const application = applications.find( + (candidate) => candidate.id === applicationId, + ); + if (application?.stageUpdatePending) { + toast.error("This application has a confirmed update in progress."); + return; + } // 1. Validate if (!validateTransition(currentStage, newStage)) { toast.error("Invalid Stage Transition", { @@ -378,10 +509,228 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { applications.find((a) => a.id === over.id)?.stage ?? stages.find((stage) => stage.id === over.id)?.id; if (app && targetStage) { + if (app.stageUpdatePending) { + toast.error( + "This application has a confirmed update in progress.", + ); + return; + } + if ( + selectedApplicationIds.length > 1 && + selectedApplicationIds.includes(app.id) + ) { + if (selectedApplicationIds.length > 100) { + toast.error( + "Bulk updates are limited to 100 applications.", + ); + return; + } + if (targetStage === "Hired") { + toast.error( + "Hired status cannot be set by bulk drag. Move applicants individually.", + ); + return; + } + if (targetStage === "Applied") { + toast.error( + "Applications cannot be moved back to Applied.", + ); + return; + } + setBulkTargetStage(targetStage); + setBulkDragTargetStage(targetStage); + setBulkUpdateDialogOpen(true); + return; + } initiateStageUpdate(app.id, app.stage, targetStage); } } + 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); + setBulkDragTargetStage(null); + 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 +946,75 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { )} +
+ + {selectedApplicationIds.length > 0 && ( + <> + + {selectedApplicationIds.length > 0 && ( + + Click cards to select; double-click + to open details. + {selectedApplicationIds.length > + 1 && + " Drag a selected card to a status to queue the group (Hired excluded)."} + + )} + + )} + {bulkUpdateJobs.length > 0 && ( +
+ + Recent batches: + + {bulkUpdateJobs.slice(0, 5).map((job) => ( + + ))} +
+ )} +
{ + const isSelected = + selectedApplicationIds.includes( + item.id, + ); return ( + selected={ + isSelected + } + disabled={ + item.stageUpdatePending || + review.stage.isPending || + isSubmittingBulkUpdate || + item.stage === + "Rejected" || + item.stage === + "Hired" + } + className={cn( + "bg-background hover:bg-muted/50 transition-colors border-border p-3", + isSelected && + "border-primary bg-primary/5 ring-2 ring-primary", + )} + onClick={() => { + if ( + item.stageUpdatePending || + review.stage.isPending || + isSubmittingBulkUpdate || + item.stage === + "Rejected" || + item.stage === + "Hired" + ) { + return; + } + setSelectedApplicationIds( + (current) => + current.includes( + item.id, + ) + ? current.filter( + ( + id, + ) => + id !== + item.id, + ) + : [ + ...current, + item.id, + ], + ); + }} + onDoubleClick={() => selectApplication( item.id, ) @@ -644,11 +1112,13 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { >
- - { - item.name - } - +
+ + { + item.name + } + +
{new Date( item.appliedAt, @@ -689,6 +1159,20 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { 12 } /> + {item.latestEmailUpdate && ( + + )}
@@ -1453,6 +1937,68 @@ function RecruitmentBoard({ teamId }: { teamId: string }) { ))} +
+

+ Batch email history +

+ {selectedApplicationDetails?.emailUpdates + ?.length ? ( +
+ {selectedApplicationDetails.emailUpdates.map( + (update) => ( +
+
+ + {update.stage} + + + {update.status === + "updated" + ? "Stage moved" + : update.status.replace( + /_/g, + " ", + )} + +
+

+ {update.status === + "updated" + ? "Stage moved" + : `Attempts: ${update.attempts}`} +

+ {update.error && ( +

+ {update.error} +

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

+ No batch updates recorded. +

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

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

{ + setBulkUpdateDialogOpen(open); + if (!open) setBulkDragTargetStage(null); + }} + > + + + Bulk stage update + + {bulkTargetStage === "Potential Hire" + ? "Move up to 100 selected applications to Potential Hire. Applicants will not be emailed. Applications that fail validation will be recorded and skipped." + : "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."} + + +
+
+ + {bulkDragTargetStage ? ( +

+ {bulkDragTargetStage} +

+ ) : ( + + )} +
+ {bulkTargetStage === "Interview" && ( + <> +
+ + + setBulkInterviewLink( + event.target.value, + ) + } + placeholder="https://..." + /> +
+
+ +