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 | 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 2x 2x 2x 3x 3x 3x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 3x 1x 4x 1x 3x 3x 3x 12x 12x 12x 10x 9x 8x 7x 5x 4x 3x 2x 1x 1x 2x 2x 2x | import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import {
PerformanceCycle,
PerformanceRatingScale,
PerformanceBellCurveDefinition,
PerformanceConfiguration,
PerformanceGoal,
PerformanceGoalTemplate,
PerformanceObjective,
PerformanceKeyResult,
PerformanceKpiLibrary,
PerformanceKpiMeasurement,
PerformanceKpiHistorySnapshot,
PerformanceReviewTemplate,
PerformanceReview,
PerformanceCalibrationSession,
PerformanceIncrementPolicy,
PerformanceCompensationRecommendation,
PerformanceCompetencyLibrary,
PerformanceEmployeeSkillMatrix,
PerformanceCareerTrack,
PerformanceTalentMatrix,
PerformanceSuccessionPlan,
PerformanceIndividualDevelopmentPlan,
PerformanceTrainingRequest,
PerformanceCertificationTracker,
PerformanceImprovementPlan,
PerformanceAward
} from './schemas';
@Injectable()
export class PerformanceService {
constructor(
@InjectModel(PerformanceCycle.name) private cycleModel: Model<PerformanceCycle>,
@InjectModel(PerformanceRatingScale.name) private scaleModel: Model<PerformanceRatingScale>,
@InjectModel(PerformanceBellCurveDefinition.name) private bellCurveModel: Model<PerformanceBellCurveDefinition>,
@InjectModel(PerformanceConfiguration.name) private configModel: Model<PerformanceConfiguration>,
@InjectModel(PerformanceGoal.name) private goalModel: Model<PerformanceGoal>,
@InjectModel(PerformanceGoalTemplate.name) private goalTemplateModel: Model<PerformanceGoalTemplate>,
@InjectModel(PerformanceObjective.name) private objectiveModel: Model<PerformanceObjective>,
@InjectModel(PerformanceKeyResult.name) private keyResultModel: Model<PerformanceKeyResult>,
@InjectModel(PerformanceKpiLibrary.name) private kpiLibraryModel: Model<PerformanceKpiLibrary>,
@InjectModel(PerformanceKpiMeasurement.name) private kpiMeasurementModel: Model<PerformanceKpiMeasurement>,
@InjectModel(PerformanceKpiHistorySnapshot.name) private snapshotModel: Model<PerformanceKpiHistorySnapshot>,
@InjectModel(PerformanceReviewTemplate.name) private reviewTemplateModel: Model<PerformanceReviewTemplate>,
@InjectModel(PerformanceReview.name) private reviewModel: Model<PerformanceReview>,
@InjectModel(PerformanceCalibrationSession.name) private calibrationSessionModel: Model<PerformanceCalibrationSession>,
@InjectModel(PerformanceIncrementPolicy.name) private incrementPolicyModel: Model<PerformanceIncrementPolicy>,
@InjectModel(PerformanceCompensationRecommendation.name) private recommendationModel: Model<PerformanceCompensationRecommendation>,
@InjectModel(PerformanceCompetencyLibrary.name) private competencyModel: Model<PerformanceCompetencyLibrary>,
@InjectModel(PerformanceEmployeeSkillMatrix.name) private skillModel: Model<PerformanceEmployeeSkillMatrix>,
@InjectModel(PerformanceCareerTrack.name) private careerModel: Model<PerformanceCareerTrack>,
@InjectModel(PerformanceTalentMatrix.name) private talentModel: Model<PerformanceTalentMatrix>,
@InjectModel(PerformanceSuccessionPlan.name) private successionModel: Model<PerformanceSuccessionPlan>,
@InjectModel(PerformanceIndividualDevelopmentPlan.name) private idpModel: Model<PerformanceIndividualDevelopmentPlan>,
@InjectModel(PerformanceTrainingRequest.name) private trainingModel: Model<PerformanceTrainingRequest>,
@InjectModel(PerformanceCertificationTracker.name) private certificationModel: Model<PerformanceCertificationTracker>,
@InjectModel(PerformanceImprovementPlan.name) private pipModel: Model<PerformanceImprovementPlan>,
@InjectModel(PerformanceAward.name) private awardModel: Model<PerformanceAward>
) {}
// ----------------------------------------------------
// 1. KPI Formula Engine
// ----------------------------------------------------
async calculateKpiAchievement(tenantId: string, measurementId: string): Promise<number> {
const meas = await this.kpiMeasurementModel.findById(measurementId).populate('kpiId').exec();
Iif (!meas) throw new BadRequestException('KPI measurement not found');
const kpi = meas.kpiId as unknown as PerformanceKpiLibrary;
const formula = kpi.formulaExpression || '((actual / target) * 100)';
let score = 0;
try {
// Safe dynamic expression evaluation for basic arithmetic expressions
const actual = meas.actualValue;
const target = meas.targetValue;
if (target <= 0) {
score = 0;
} else {
// Basic expression evaluation parsing actual and target variables
const normalizedFormula = formula
.replace(/actual/g, actual.toString())
.replace(/target/g, target.toString());
// Safe evaluation of standard operators only to prevent arbitrary code execution
Eif (/^[0-9+\-*/().\s]+$/.test(normalizedFormula)) {
// eslint-disable-next-line no-eval
score = eval(normalizedFormula);
}
}
} catch {
score = 0;
}
meas.achievementScore = Math.max(0, Math.min(score, 200)); // cap score if needed
await meas.save();
return meas.achievementScore;
}
// ----------------------------------------------------
// 2. OKR Engine progress rollup
// ----------------------------------------------------
async calculateOkrProgress(tenantId: string, objectiveId: string): Promise<number> {
const objective = await this.objectiveModel.findById(objectiveId).exec();
Iif (!objective) throw new BadRequestException('Objective not found');
const keyResults = await this.keyResultModel.find({ objectiveId }).exec();
if (keyResults.length === 0) {
objective.progress = 0;
await objective.save();
return 0;
}
let totalWeight = 0;
let weightedProgress = 0;
for (const kr of keyResults) {
const krProgress = kr.targetValue > 0 ? (kr.currentValue / kr.targetValue) * 100 : 0;
weightedProgress += Math.min(100, Math.max(0, krProgress)) * (kr.weight || 1);
totalWeight += kr.weight || 1;
}
objective.progress = Math.round(weightedProgress / (totalWeight || 1));
await objective.save();
return objective.progress;
}
// ----------------------------------------------------
// 3. Goal Cascading
// ----------------------------------------------------
async cascadeGoalProgress(tenantId: string, parentGoalId: string): Promise<number> {
const parentGoal = await this.goalModel.findById(parentGoalId).exec();
Iif (!parentGoal) throw new BadRequestException('Parent Goal not found');
const childGoals = await this.goalModel.find({ parentGoalId }).exec();
if (childGoals.length === 0) {
return parentGoal.progress;
}
let progressSum = 0;
for (const child of childGoals) {
progressSum += child.progress;
}
parentGoal.progress = Math.round(progressSum / childGoals.length);
await parentGoal.save();
// Recurse upwards if the parent goal also has a parent aligned
Iif (parentGoal.parentGoalId) {
await this.cascadeGoalProgress(tenantId, parentGoal.parentGoalId.toString());
}
return parentGoal.progress;
}
// ----------------------------------------------------
// 4. Calibration & Bell Curve Check
// ----------------------------------------------------
async getBellCurveDeviation(tenantId: string, cycleId: string): Promise<{ ratingLabel: string; target: number; actual: number }[]> {
const bellCurveDef = await this.bellCurveModel.findOne({ tenantId: new Types.ObjectId(tenantId), cycleId }).exec();
Iif (!bellCurveDef) return [];
// Aggregate active ratings from completed/calibrated reviews
const reviews = await this.reviewModel.find({
tenantId: new Types.ObjectId(tenantId),
cycleId,
status: { $in: ['submitted', 'calibrated', 'locked'] },
role: 'manager' // typically manager ratings are calibrated
}).exec();
const totalReviews = reviews.length;
Iif (totalReviews === 0) {
return bellCurveDef.targets.map(t => ({
ratingLabel: t.ratingLabel,
target: t.targetPercentage,
actual: 0
}));
}
// Map numerical calibrated score or answers target rating labels
const distributionMap: Record<string, number> = {};
for (const review of reviews) {
const ratingVal = review.calibratedRatingValue || 0;
let label = 'Average';
if (ratingVal >= 4.5) label = 'Top';
else if (ratingVal >= 3.0) label = 'Average';
else label = 'Low';
distributionMap[label] = (distributionMap[label] || 0) + 1;
}
return bellCurveDef.targets.map(t => {
const count = distributionMap[t.ratingLabel] || 0;
const actualPct = Math.round((count / totalReviews) * 100);
return {
ratingLabel: t.ratingLabel,
target: t.targetPercentage,
actual: actualPct
};
});
}
// ----------------------------------------------------
// 5. Talent 9-Box Matrix Assignment
// ----------------------------------------------------
calculateNineBoxCell(performance: string, potential: string): string {
const perf = performance.toLowerCase();
const pot = potential.toLowerCase();
if (perf === 'high' && pot === 'high') return 'Star (High Perf, High Pot)';
if (perf === 'medium' && pot === 'high') return 'High Potential (Med Perf, High Pot)';
if (perf === 'low' && pot === 'high') return 'Enigma (Low Perf, High Pot)';
if (perf === 'high' && pot === 'medium') return 'High Performer (High Perf, Med Pot)';
if (perf === 'medium' && pot === 'medium') return 'Key Player (Med Perf, Med Pot)';
if (perf === 'low' && pot === 'medium') return 'Dilemma (Low Perf, Med Pot)';
if (perf === 'high' && pot === 'low') return 'Solid Specialist (High Perf, Low Pot)';
if (perf === 'medium' && pot === 'low') return 'Effective (Med Perf, Low Pot)';
return 'Under Performer (Low Perf, Low Pot)';
}
async assignEmployeeToTalentMatrix(
tenantId: string,
cycleId: string,
employeeId: string,
performance: string,
potential: string
): Promise<PerformanceTalentMatrix> {
const nineBoxCell = this.calculateNineBoxCell(performance, potential);
let talentRecord = await this.talentModel.findOne({
tenantId: new Types.ObjectId(tenantId),
cycleId,
employeeId
}).exec();
if (!talentRecord) {
talentRecord = new this.talentModel({
tenantId: new Types.ObjectId(tenantId),
cycleId,
employeeId,
performanceRating: performance,
potentialRating: potential,
nineBoxCell
});
} else {
talentRecord.performanceRating = performance;
talentRecord.potentialRating = potential;
talentRecord.nineBoxCell = nineBoxCell;
}
return talentRecord.save();
}
// ----------------------------------------------------
// 6. IDP Skill Gap Analysis
// ----------------------------------------------------
async getEmployeeSkillGapReport(tenantId: string, employeeId: string): Promise<{ competencyName: string; gap: number; target: number; actual: number }[]> {
const skills = await this.skillModel.find({
tenantId: new Types.ObjectId(tenantId),
employeeId
}).populate('competencyId').exec();
return skills.map(skill => {
const comp = skill.competencyId as unknown as PerformanceCompetencyLibrary;
const gap = skill.targetLevel - skill.acquiredLevel;
return {
competencyName: comp.name,
gap: gap > 0 ? gap : 0,
target: skill.targetLevel,
actual: skill.acquiredLevel
};
});
}
}
|