All files / libs/lti/shared/src/lib condense-lti-grants-for-plan-for-user.ts

100% Statements 48/48
94.73% Branches 18/19
100% Functions 1/1
100% Lines 48/48

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 491x 1x 1x 1x 9x 9x 9x 9x 2x 2x 2x 2x 2x 2x 2x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 9x 9x 9x 9x 9x 9x 9x 9x 11x 11x 11x 11x 9x 11x 11x 11x 6x 5x 9x 9x 9x 9x  
import { assert } from '@amalia/ext/typescript';
import { type LtiGrant, type LtiGrantsCondensedPerformanceValuesForPlanForUser } from '@amalia/lti/types';
 
export const condenseLtiGrantsPerformanceValuesForPlanForUser = <T extends object = Record<string, never>>(
  grants: LtiGrant[],
  baseValues?: T,
): LtiGrantsCondensedPerformanceValuesForPlanForUser & T => {
  if (!grants.length) {
    return {
      ...(baseValues ?? ({} as T)),
      nbShares: 0,
      outcomeNbShares: 0,
      employmentAdjustment: null,
    };
  }
 
  const [firstGrant] = grants;
 
  assert(
    grants.every((grant) => grant.planId === firstGrant.planId && grant.userId === firstGrant.userId),
    'All grants must belong to the same plan and user',
  );
 
  const hasEmploymentAdjustment = grants.some((grant) => grant.employmentAdjustment !== null);
 
  const initialValues: LtiGrantsCondensedPerformanceValuesForPlanForUser & T = {
    ...(baseValues ?? ({} as T)),
    nbShares: 0,
    outcomeNbShares: 0,
    employmentAdjustment: hasEmploymentAdjustment ? 0 : null,
  };
 
  return grants.reduce<LtiGrantsCondensedPerformanceValuesForPlanForUser & T>(
    (acc, curr) => ({
      ...acc,
      nbShares: acc.nbShares + curr.nbShares,
      outcomeNbShares:
        acc.outcomeNbShares !== null && curr.outcomeNbShares !== null
          ? acc.outcomeNbShares + curr.outcomeNbShares
          : null,
      employmentAdjustment:
        acc.employmentAdjustment !== null || curr.employmentAdjustment !== null
          ? (acc.employmentAdjustment ?? 0) + (1 - (curr.employmentAdjustment ?? 0)) * curr.nbShares
          : null,
    }),
    initialValues,
  );
};