Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | import { Injectable, Logger, NotFoundException, BadRequestException } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model, Types } from 'mongoose'; import { RecruitmentConfiguration, CandidatePrivacyConfiguration, WorkforcePlan, WorkforcePlanLine, JobRequisition, Position, JobPosting, Candidate, CandidateResume, CandidateEducation, CandidateExperience, CandidateDuplicateMatch, ResumeParseJob, JobApplication, HiringPipeline, HiringStage, ApplicationStageInstance, ScreeningRule, AiResumeAnalysis, ReferralCampaign, EmployeeReferral, RecruitmentAgency, AgencyContract, AgencyCandidateSubmission, TalentPool, TalentPoolMember, AssessmentDefinition, AssessmentAssignment, InterviewPlan, InterviewRound, InterviewSchedule, InterviewFeedback, BackgroundCheckRequest, ReferenceCheck, Offer, PreboardingTemplate, PreboardingPlan, PreboardingTask, CandidateEmployeeLink } from './schemas'; import { EmployeeService } from '../hr/employee/employee.service'; import { CalendarService } from '../../platform/calendar/calendar.service'; import { AvailabilityEngine } from '../../platform/calendar/availability.engine'; import { EventBusService } from '../../platform/events/event-bus.service'; @Injectable() export class RecruitmentService { private readonly logger = new Logger(RecruitmentService.name); constructor( @InjectModel(RecruitmentConfiguration.name) private readonly configModel: Model<RecruitmentConfiguration>, @InjectModel(CandidatePrivacyConfiguration.name) private readonly privacyModel: Model<CandidatePrivacyConfiguration>, @InjectModel(WorkforcePlan.name) private readonly workforcePlanModel: Model<WorkforcePlan>, @InjectModel(WorkforcePlanLine.name) private readonly workforceLineModel: Model<WorkforcePlanLine>, @InjectModel(JobRequisition.name) private readonly requisitionModel: Model<JobRequisition>, @InjectModel(Position.name) private readonly positionModel: Model<Position>, @InjectModel(JobPosting.name) private readonly jobPostingModel: Model<JobPosting>, @InjectModel(Candidate.name) private readonly candidateModel: Model<Candidate>, @InjectModel(CandidateResume.name) private readonly candidateResumeModel: Model<CandidateResume>, @InjectModel(CandidateDuplicateMatch.name) private readonly duplicateMatchModel: Model<CandidateDuplicateMatch>, @InjectModel(JobApplication.name) private readonly applicationModel: Model<JobApplication>, @InjectModel(HiringPipeline.name) private readonly pipelineModel: Model<HiringPipeline>, @InjectModel(HiringStage.name) private readonly stageModel: Model<HiringStage>, @InjectModel(ApplicationStageInstance.name) private readonly stageInstanceModel: Model<ApplicationStageInstance>, @InjectModel(InterviewSchedule.name) private readonly interviewScheduleModel: Model<InterviewSchedule>, @InjectModel(InterviewFeedback.name) private readonly feedbackModel: Model<InterviewFeedback>, @InjectModel(BackgroundCheckRequest.name) private readonly bgCheckModel: Model<BackgroundCheckRequest>, @InjectModel(Offer.name) private readonly offerModel: Model<Offer>, @InjectModel(PreboardingPlan.name) private readonly preboardingPlanModel: Model<PreboardingPlan>, @InjectModel(PreboardingTask.name) private readonly preboardingTaskModel: Model<PreboardingTask>, @InjectModel(CandidateEmployeeLink.name) private readonly linkModel: Model<CandidateEmployeeLink>, @InjectModel(EmployeeReferral.name) private readonly referralModel: Model<EmployeeReferral>, @InjectModel(AiResumeAnalysis.name) private readonly aiAnalysisModel: Model<AiResumeAnalysis>, private readonly employeeService: EmployeeService, private readonly calendarService: CalendarService, private readonly availabilityEngine: AvailabilityEngine, private readonly eventBus: EventBusService ) {} // ── Duplicate Detection Engine ───────────────────────────────────────────── async checkDuplicates(tenantId: string, candidateId: string): Promise<CandidateDuplicateMatch[]> { const candidate = await this.candidateModel.findOne({ tenantId, _id: candidateId }).exec(); if (!candidate) throw new NotFoundException('Candidate not found'); const matches: CandidateDuplicateMatch[] = []; // Find other candidates with same email or phone const potentials = await this.candidateModel.find({ tenantId, _id: { $ne: candidateId }, $or: [ { email: candidate.email }, { phone: candidate.phone } ] }).exec(); for (const pot of potentials) { let signal = 'name_employer'; let confidence = 50; if (pot.email === candidate.email) { signal = 'email'; confidence = 100; } else if (pot.phone === candidate.phone) { signal = 'phone'; confidence = 90; } const match = await this.duplicateMatchModel.findOneAndUpdate( { tenantId, candidateId, matchedCandidateId: pot._id }, { tenantId, candidateId, matchedCandidateId: pot._id, matchSignal: signal, confidenceScore: confidence, status: 'pending' }, { upsert: true, new: true } ).exec(); matches.push(match); await this.eventBus.publish('recruitment.candidate.duplicate-detected.v1', { candidateId, matchedCandidateId: pot._id, signal, confidence }, tenantId); } return matches; } // ── Application Pipeline State Machine ────────────────────────────────────── async transitionStage( tenantId: string, applicationId: string, targetStageId: string, userId: string ): Promise<JobApplication> { const app = await this.applicationModel.findOne({ tenantId, _id: applicationId }).exec(); if (!app) throw new NotFoundException('Application not found'); const currentStage = await this.stageModel.findOne({ tenantId, _id: app.currentStageId }).exec(); const targetStage = await this.stageModel.findOne({ tenantId, _id: targetStageId }).exec(); if (!targetStage) throw new NotFoundException('Target stage not found'); // Basic rollback protection: Recruiter can only roll back one stage if they have permissions if (currentStage && targetStage.sequence < currentStage.sequence - 1) { throw new BadRequestException('Pipeline rollback limited to 1 sequence step maximum'); } // Terminate old stage instance await this.stageInstanceModel.updateMany( { tenantId, applicationId, status: 'active' }, { status: 'completed', exitedAt: new Date() } ).exec(); // Create new stage instance await this.stageInstanceModel.create({ tenantId, applicationId, stageId: targetStageId, enteredAt: new Date(), status: 'active' }); app.currentStageId = targetStageId; // Map stage name to application status envelope const statusMap: Record<string, string> = { 'Screening': 'screening', 'Assessment': 'assessment', 'Interview': 'interview', 'Offer': 'offer', 'Hired': 'hired' }; if (statusMap[targetStage.stageName]) { app.status = statusMap[targetStage.stageName]; } await app.save(); await this.eventBus.publish('recruitment.application.stage-changed.v1', { applicationId, stageId: targetStageId, stageName: targetStage.stageName, changedBy: userId }, tenantId); return app; } // ── AI Safety & PII Redaction ────────────────────────────────────────────── async generateAiSummary(tenantId: string, candidateId: string): Promise<string> { const cand = await this.candidateModel.findOne({ tenantId, _id: candidateId }).exec(); if (!cand) throw new NotFoundException('Candidate not found'); // AI Safety: Redact candidate PII before processing const redactedEmail = 'REDACTED_EMAIL@example.com'; const redactedPhone = 'REDACTED_PHONE'; const redactedName = 'Redacted Candidate'; const info = `Candidate: ${redactedName}, Exp: ${cand.totalExperienceMonths} months, Title: ${cand.currentTitle || 'N/A'}`; this.logger.log(`Forwarding redacted candidate info to AI Gateway: ${info}`); // Simulate AI response advice (AI must never make auto-rejections) const summary = `Advisory Summary: Candidate has ${cand.totalExperienceMonths} months of experience as ${cand.currentTitle || 'N/A'}. Suggest scheduling a Recruiter Screening round to verify qualifications.`; return summary; } // ── Interview Scheduling via Calendar Platform ────────────────────────────── async scheduleInterview( tenantId: string, applicationId: string, roundId: string, startAt: Date, endAt: Date, panelMembers: string[] // employeeIds ): Promise<InterviewSchedule> { // 1. Verify availability of panel members via Calendar Availability Engine const busy = await this.availabilityEngine.findBusyIntervals( tenantId, panelMembers, [], startAt, endAt ); if (busy.length > 0) { throw new BadRequestException('Panel member is busy during the requested time slot'); } // 2. Create calendar platform event hold const calEvent = await this.calendarService.createEvent(tenantId, { calendarId: 'recruitment-interviews-cal', title: `Interview Round`, startAt, endAt, organizerType: 'System', organizerId: 'recruitment-engine', status: 'confirmed' }); // 3. Create recruitment interview reference const schedule = await this.interviewScheduleModel.create({ tenantId, applicationId, roundId, startAt, endAt, panelMembers, calendarEventId: calEvent.eventId, status: 'scheduled' }); await this.eventBus.publish('recruitment.interview.scheduled.v1', { interviewScheduleId: schedule._id, applicationId, calendarEventId: calEvent.eventId }, tenantId); return schedule; } // ── Offer Management (Accepted offer is Immutable) ───────────────────────── async createOffer(tenantId: string, data: any): Promise<Offer> { const version = (await this.offerModel.countDocuments({ tenantId, applicationId: data.applicationId }).exec()) + 1; const offer = new this.offerModel({ ...data, tenantId, version, status: 'draft' }); return offer.save(); } async updateOffer(tenantId: string, offerId: string, updates: any): Promise<Offer> { const offer = await this.offerModel.findOne({ tenantId, _id: offerId }).exec(); if (!offer) throw new NotFoundException('Offer not found'); if (offer.status === 'accepted') { throw new BadRequestException('Accepted offers are immutable and cannot be edited'); } Object.assign(offer, updates); return offer.save(); } // ── Candidate to Employee Onboarding Handoff (Idempotent) ─────────────────── async hireAndHandoff(tenantId: string, candidateId: string, userId: string): Promise<CandidateEmployeeLink> { // 1. Check idempotency const existingLink = await this.linkModel.findOne({ tenantId, candidateId }).exec(); if (existingLink) { this.logger.log(`Candidate ${candidateId} already hired and linked. Returning link.`); return existingLink; } const cand = await this.candidateModel.findOne({ tenantId, _id: candidateId }).exec(); if (!cand) throw new NotFoundException('Candidate not found'); // 2. Validate accepted offer const offer = await this.offerModel.findOne({ tenantId, candidateId, status: 'accepted' }).exec(); if (!offer) throw new BadRequestException('Candidate must have an accepted offer before handoff'); // 3. Validate preboarding task checklist documents are complete const tasks = await this.preboardingTaskModel.find({ tenantId, status: 'pending' }).exec(); // Simulate finding preboarding tasks for candidate preboarding plan const prePlan = await this.preboardingPlanModel.findOne({ tenantId, candidateId }).exec(); if (prePlan) { const pendingTasks = await this.preboardingTaskModel.find({ tenantId, planId: prePlan._id, status: 'pending' }).exec(); if (pendingTasks.length > 0) { throw new BadRequestException(`Checklist task '${pendingTasks[0].taskName}' must be completed before handoff`); } } // 4. Create Employee Draft via HR Service (recruitment never writes records directly to HR) const empDraft = await this.employeeService.createDraft(tenantId, { firstName: cand.firstName, middleName: cand.middleName || '', lastName: cand.lastName, workEmail: cand.email, personalPhone: cand.phone, joiningDate: offer.joiningDate, employmentType: 'Permanent', employmentStatus: 'draft' }, userId); // 5. Create immutable candidate employee link const link = await this.linkModel.create({ tenantId, candidateId, employeeId: empDraft._id.toString(), linkedAt: new Date() }); // 6. Publish Handoff Outbox events await this.eventBus.publish('recruitment.candidate-hired.v1', { candidateId }, tenantId); await this.eventBus.publish('recruitment.employee-creation-ready.v1', { candidateId, employeeId: empDraft._id }, tenantId); await this.eventBus.publish('recruitment.onboarding-handoff.v1', { candidateId, employeeId: empDraft._id }, tenantId); return link; } } |