All files / libs/lti/components/src/lib/hooks useLtiPlanParticipantGrantsAndShareValues.ts

0% Statements 0/64
0% Branches 0/1
0% Functions 0/1
0% Lines 0/64

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                                                                                                                                 
import { useMemo } from 'react';

import { getGrantedShares } from '@amalia/lti/shared';
import { useLtiParticipantGrants } from '@amalia/lti/state';
import { type LtiParticipantGrants, type LtiPlan } from '@amalia/lti/types';
import { type UserContract } from '@amalia/tenants/users/types';

export const useLtiPlanParticipantGrantsAndShareValues = ({
  ltiPlanId,
  userId,
}: {
  ltiPlanId: LtiPlan['id'];
  userId?: UserContract['id'];
}) => {
  // We could only fetch the grants for this specific plan but since we already have to fetch all the grants for the participant in the list page, we might as well reuse that data instead of doing another request here to prevent loading states and query again the same data we already have.
  const { data: ltiGrants, isLoading: isGrantsLoading } = useLtiParticipantGrants(userId);

  const grantsForThisPlan: LtiParticipantGrants | undefined = useMemo(() => {
    const grantForThisPlan = (ltiGrants ?? []).find((g) => g.plan.id === ltiPlanId);
    if (!grantForThisPlan) {
      return undefined;
    }
    return {
      ...grantForThisPlan,
      grants: grantForThisPlan.grants.filter((grant) => grant.acceptedAt),
    };
  }, [ltiGrants, ltiPlanId]);

  const shareValues = useMemo(() => {
    if (!grantsForThisPlan) {
      return null;
    }

    const { grantedShares, earnedShares } = getGrantedShares(grantsForThisPlan);
    const remainingShares = grantedShares - (earnedShares ?? 0);

    const sharePriceForPlan = grantsForThisPlan.share;

    return {
      sharePriceForPlan,
      granted: {
        nbShares: grantedShares,
        monetaryValue: sharePriceForPlan
          ? { value: grantedShares * (sharePriceForPlan.value ?? 0), symbol: sharePriceForPlan.currency }
          : undefined,
      },
      earned: {
        nbShares: earnedShares,
        monetaryValue:
          sharePriceForPlan && earnedShares !== null
            ? { value: earnedShares * (sharePriceForPlan.value ?? 0), symbol: sharePriceForPlan.currency }
            : undefined,
      },
      remaining: {
        nbShares: remainingShares,
        monetaryValue: sharePriceForPlan
          ? { value: remainingShares * (sharePriceForPlan.value ?? 0), symbol: sharePriceForPlan.currency }
          : undefined,
      },
    };
  }, [grantsForThisPlan]);

  return { shareValues, grantsForThisPlan, isGrantsLoading };
};