50 lines
2.3 KiB
TypeScript
50 lines
2.3 KiB
TypeScript
import { Prisma } from '@prisma/client'
|
|
import { percentageBasisPoints, type PositionDimension } from './salary-position-contract'
|
|
|
|
type BaseWages = {
|
|
baseSalary: Prisma.Decimal
|
|
gradeSalary: Prisma.Decimal
|
|
performanceSalary: Prisma.Decimal
|
|
}
|
|
|
|
export function calculatePositionScore(dimensions: PositionDimension[], scores: Record<string, number | null>) {
|
|
let complete = dimensions.length > 0
|
|
let totalCents = 0
|
|
const contributions: Record<string, number | null> = {}
|
|
for (const dimension of dimensions) {
|
|
const weight = percentageBasisPoints(dimension.weight)
|
|
for (const metric of dimension.metrics) {
|
|
const value = scores[metric.id]
|
|
const combinedWeight = weight * percentageBasisPoints(metric.weight)
|
|
// Two basis-point weights divided by 10000², then scaled by 100 for score cents.
|
|
const cents = typeof value === 'number' && Number.isFinite(value)
|
|
? new Prisma.Decimal(value).times(combinedWeight).div(1_000_000).toDecimalPlaces(0, Prisma.Decimal.ROUND_HALF_UP).toNumber()
|
|
: null
|
|
contributions[metric.id] = cents === null ? null : cents / 100
|
|
if (combinedWeight === 0) continue
|
|
if (cents === null) complete = false
|
|
else totalCents += cents
|
|
}
|
|
}
|
|
return { contributions, totalScore: complete ? totalCents / 100 : null }
|
|
}
|
|
|
|
/** The rounded coefficient is both displayed and used for the monetary calculation. */
|
|
export function calculateSalaryPay(totalScore: number | null, wages: BaseWages) {
|
|
if (totalScore === null || !Number.isFinite(totalScore)) {
|
|
return { performanceCoefficient: null, currentTotal: null }
|
|
}
|
|
const coefficient = new Prisma.Decimal(totalScore).div(100).toDecimalPlaces(2, Prisma.Decimal.ROUND_HALF_UP)
|
|
const total = wages.baseSalary.plus(wages.gradeSalary).plus(wages.performanceSalary.times(coefficient))
|
|
return {
|
|
performanceCoefficient: coefficient.toNumber(),
|
|
currentTotal: total.toFixed(2, Prisma.Decimal.ROUND_HALF_UP),
|
|
}
|
|
}
|
|
|
|
/** Subtract the displayed, cent-rounded totals; missing is never treated as zero. */
|
|
export function calculateSalaryDifference(currentTotal: string | null, previousTotal: string | null): string | null {
|
|
if (currentTotal === null || previousTotal === null) return null
|
|
return new Prisma.Decimal(currentTotal).minus(previousTotal).toFixed(2, Prisma.Decimal.ROUND_HALF_UP)
|
|
}
|