All files / src/utils costCalculationUtils.ts

97.12% Statements 169/174
86.48% Branches 32/37
100% Functions 8/8
97.12% Lines 169/174

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                                                                    1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x             44x 44x 44x 44x     44x   44x 44x 44x 44x 44x     1x 1x         1x 44x 44x 44x 44x   44x     44x           44x 44x     44x 44x 44x 44x 44x         1x 4x 4x 4x 4x 4x               4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x         1x 5x 5x 5x 5x           5x   5x     5x     5x     5x 5x 4x 5x 1x 1x     5x     5x 5x   4x 4x 4x 5x 1x 1x   5x 5x 5x 5x 5x 5x 5x         1x 5x 5x 5x 5x         5x   5x 5x 5x   5x   5x   1x 1x 1x 1x 1x 1x     4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x       44x 44x 44x 1x   44x   44x 44x 44x   44x   15x 15x 15x 3x 15x 3x 15x 6x 15x 3x 15x   15x   15x 15x  
/**
 * Cost Calculation Utilities
 *
 * This module provides business-oriented cost calculation functions for
 * security implementations across the CIA triad.
 *
 * ## Business Perspective
 *
 * These utilities help organizations understand the financial implications
 * of different security level choices. They provide consistent cost models
 * that can be used for budgeting and ROI analysis. 💰
 *
 * @packageDocumentation
 */
 
import { SecurityLevel } from "../types/cia";
 
// Export the types so they can be imported elsewhere
export type OrganizationSize = "small" | "medium" | "large" | "enterprise";
export type Industry =
  | "general"
  | "financial"
  | "healthcare"
  | "government"
  | "retail"
  | "technology"
  | "manufacturing";
 
interface CostResult {
  capex: number;
  opex: number;
}
 
// Base implementation costs per security level
const BASE_IMPLEMENTATION_COSTS = {
  None: { capex: 0, opex: 0 },
  Low: { capex: 5000, opex: 2000 },
  Moderate: { capex: 15000, opex: 5000 },
  High: { capex: 50000, opex: 15000 },
  "Very High": { capex: 200000, opex: 50000 },
};
 
// Organization size multipliers
const ORG_SIZE_MULTIPLIERS = {
  small: 0.5,
  medium: 1.0,
  large: 2.5,
  enterprise: 5.0,
};
 
// Industry complexity factors
const INDUSTRY_COST_FACTORS = {
  general: 1.0,
  financial: 1.5,
  healthcare: 1.7,
  government: 1.3,
  retail: 1.2,
  technology: 1.4,
  manufacturing: 1.1,
};
 
/**
 * Normalize security level to ensure it matches expected keys
 * @param level Security level to normalize
 * @returns Normalized security level that matches BASE_IMPLEMENTATION_COSTS keys
 */
function normalizeSecurityLevel(
  level: string | SecurityLevel | undefined
): SecurityLevel {
  if (!level) return "None";
 
  // Handle case-insensitive matching
  const normalizedLevel = typeof level === "string" ? level.trim() : "";
 
  if (/^none$/i.test(normalizedLevel)) return "None";
  if (/^low$/i.test(normalizedLevel)) return "Low";
  if (/^(moderate|medium)$/i.test(normalizedLevel)) return "Moderate";
  if (/^high$/i.test(normalizedLevel)) return "High";
  if (/^very\s*high$/i.test(normalizedLevel)) return "Very High";
 
  // Default to "None" if no match
  return "None";
}
 
/**
 * Calculate implementation cost based on security level
 */
export function calculateImplementationCost(
  securityLevel: SecurityLevel | string, // Allow string for more flexible inputs
  orgSize: OrganizationSize = "medium",
  industry: Industry = "general"
): CostResult {
  // Normalize the security level and handle case variations
  const normalizedLevel = normalizeSecurityLevel(securityLevel);
 
  // Get base costs for the normalized level
  const baseCosts = BASE_IMPLEMENTATION_COSTS[normalizedLevel] || {
    capex: 0,
    opex: 0,
  };
 
  // Get scaling factors
  const sizeFactor = getSizeFactor(orgSize);
  const industryFactor = getIndustryFactor(industry);
 
  // Apply factors to base costs
  return {
    capex: Math.round(baseCosts.capex * sizeFactor * industryFactor),
    opex: Math.round(baseCosts.opex * sizeFactor * industryFactor),
  };
}
 
/**
 * Calculate total security costs across all CIA components
 */
export function calculateTotalSecurityCost(
  availabilityLevel: SecurityLevel,
  integrityLevel: SecurityLevel,
  confidentialityLevel: SecurityLevel,
  orgSize: OrganizationSize = "medium",
  industry: Industry = "general"
): {
  availabilityCost: CostResult;
  integrityCost: CostResult;
  confidentialityCost: CostResult;
  totalCapex: number;
  totalOpex: number;
  totalCost: number;
} {
  const availabilityCost = calculateImplementationCost(
    availabilityLevel,
    orgSize,
    industry
  );
  const integrityCost = calculateImplementationCost(
    integrityLevel,
    orgSize,
    industry
  );
  const confidentialityCost = calculateImplementationCost(
    confidentialityLevel,
    orgSize,
    industry
  );
 
  const totalCapex =
    availabilityCost.capex + integrityCost.capex + confidentialityCost.capex;
  const totalOpex =
    availabilityCost.opex + integrityCost.opex + confidentialityCost.opex;
 
  return {
    availabilityCost,
    integrityCost,
    confidentialityCost,
    totalCapex,
    totalOpex,
    totalCost: totalCapex + totalOpex,
  };
}
 
/**
 * Calculate security ROI
 */
export function calculateSecurityROI(
  securityCost: number,
  riskReductionPercent: number,
  potentialLoss: number,
  timeframeYears: number = 3
): {
  roi: number;
  roiPercentage: string;
  paybackPeriodMonths: number;
  costAvoidance: number;
} {
  // Risk reduction as decimal
  const riskReduction = riskReductionPercent / 100;
 
  // Annual cost avoidance
  const annualCostAvoidance = potentialLoss * riskReduction;
 
  // Total cost avoidance over timeframe
  const costAvoidance = annualCostAvoidance * timeframeYears;
 
  // ROI calculation
  let roi = 0;
  if (securityCost > 0) {
    roi = (costAvoidance - securityCost) / securityCost;
  } else {
    roi = costAvoidance > 0 ? Infinity : 0;
  }
 
  // ROI as percentage
  const roiPercentage = `${Math.round(roi * 100)}%`;
 
  // Payback period in months - Fix floating-point precision by rounding to 1 decimal
  let paybackPeriodMonths = 0;
  if (annualCostAvoidance > 0) {
    // Use toFixed(1) and convert back to number to avoid floating-point precision issues
    paybackPeriodMonths = Number(
      ((securityCost / annualCostAvoidance) * 12).toFixed(1)
    );
  } else {
    paybackPeriodMonths = Infinity;
  }
 
  return {
    roi,
    roiPercentage,
    paybackPeriodMonths,
    costAvoidance,
  };
}
 
/**
 * Get recommended budget allocation based on security levels
 */
export function getRecommendedBudgetAllocation(
  totalBudget: number,
  availabilityLevel: SecurityLevel,
  integrityLevel: SecurityLevel,
  confidentialityLevel: SecurityLevel
): {
  availability: number;
  integrity: number;
  confidentiality: number;
} {
  // Convert security levels to numeric values
  const availabilityValue = getSecurityLevelValue(availabilityLevel);
  const integrityValue = getSecurityLevelValue(integrityLevel);
  const confidentialityValue = getSecurityLevelValue(confidentialityLevel);
 
  const totalValue = availabilityValue + integrityValue + confidentialityValue;
 
  if (totalValue === 0) {
    // If all None, divide equally
    return {
      availability: Math.round(totalBudget / 3),
      integrity: Math.round(totalBudget / 3),
      confidentiality: Math.round(totalBudget / 3),
    };
  }
 
  // Allocate proportionally
  const availabilityBudget = Math.round(
    (availabilityValue / totalValue) * totalBudget
  );
  const integrityBudget = Math.round(
    (integrityValue / totalValue) * totalBudget
  );
  const confidentialityBudget = Math.round(
    (confidentialityValue / totalValue) * totalBudget
  );
 
  return {
    availability: availabilityBudget,
    integrity: integrityBudget,
    confidentiality: confidentialityBudget,
  };
}
 
// Helper functions
 
function getSizeFactor(size?: OrganizationSize): number {
  return (
    ORG_SIZE_MULTIPLIERS[size as OrganizationSize] ||
    ORG_SIZE_MULTIPLIERS.medium
  );
}
 
function getIndustryFactor(industry?: Industry): number {
  return (
    INDUSTRY_COST_FACTORS[industry as Industry] || INDUSTRY_COST_FACTORS.general
  );
}
 
function getSecurityLevelValue(level: SecurityLevel): number {
  switch (level) {
    case "None":
      return 0;
    case "Low":
      return 1;
    case "Moderate":
      return 2;
    case "High":
      return 3;
    case "Very High":
      return 4;
    default:
      return 0;
  }
}