All files / libs/payout-definition/plans/views/hub/rule-designer/src/lib/compute/result use-statement-total.tsx

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

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                                                                                                                                                                                                                                                                                           
import { css } from '@emotion/react';
import { useMemo } from 'react';
import { FormattedMessage } from 'react-intl';

import { Tooltip, Typography } from '@allshares/studio-design-system';
import { type Statement } from '@amalia/core/types';
import { FormattedAmount } from '@amalia/kernel/intl/components';
import { type CurrencyValue } from '@amalia/kernel/monetary/types';
import { useStatementChallengesPayout } from '@amalia/payout-calculation/statements/components';
import { ComputedItemTypes, type ComputedRule } from '@amalia/payout-calculation/types';
import { getChallengeStatus } from '@amalia/payout-definition/challenges/shared';
import { useChallengesByRulePeriod } from '@amalia/payout-definition/challenges/state';
import { isRulePayout, RuleType, type PlanRule } from '@amalia/payout-definition/plans/types';

import { useRuleDesignerComputeContext } from '../RuleDesignerCompute.context';

import { getChallengeResult, InfoIcon } from './getChallengeResult';
import { useAdjustmentsPayout } from './use-adjustments-payout';

export const useStatementTotal = (
  statement?: Pick<Statement, 'adjustments' | 'currency' | 'period' | 'results' | 'total' | 'userId'> | null,
) => {
  // Get payments for the statement.
  const { statement: achievedStatement } = useRuleDesignerComputeContext();
  const paymentsByChallengeRules = useStatementChallengesPayout(achievedStatement);
  const adjustmentsPayout = useAdjustmentsPayout();

  const { data: challenges } = useChallengesByRulePeriod(
    (statement?.results.definitions.plan.rules ?? [])
      .filter((rule) => rule.type === RuleType.CHALLENGE)
      .map((rule) => ({ ruleId: rule.id, periodId: statement?.period?.id })),
  );

  const ruleResultWithLabel = useMemo(() => {
    if (!statement) {
      return [];
    }

    return (
      statement.results.definitions.plan.rules
        // Hide challenges that are expired or not started.
        // Ignore status if the user has a challenge result on the period anyway.
        .filter(
          (rule) =>
            rule.type !== RuleType.CHALLENGE ||
            getChallengeStatus(rule.configuration, statement.period?.startDate) === 'ongoing' ||
            challenges.some(
              (challenge) =>
                challenge.rule?.id === rule.id &&
                challenge.leaderboard?.some((result) => result.userId === statement.userId),
            ),
        )
        .map((rule) => ({
          definition: rule,
          result: statement.results.computedObjects.find(
            (computedItem): computedItem is ComputedRule =>
              computedItem.type === ComputedItemTypes.RULE && computedItem.ruleMachineName === rule.ruleMachineName,
          ),
        }))
        .map(({ definition, result }) => ({
          definition: definition as PlanRule | null,
          label: definition.name,
          ...(definition.type === RuleType.CHALLENGE
            ? getChallengeResult({
                definition,
                payment: paymentsByChallengeRules[definition.id],
                defaultCurrency: statement.currency,
              })
            : isRulePayout(definition)
              ? definition.formula
                ? {
                    currencyAmount: result
                      ? ({ value: result.value ?? null, symbol: statement.currency } satisfies CurrencyValue)
                      : null,
                    amount: (
                      <Typography variant="bodySmallMedium">
                        <FormattedAmount
                          currencySymbol={statement.currency}
                          value={result?.value ?? 0}
                        />
                      </Typography>
                    ),
                    help: null,
                  }
                : {
                    currencyAmount: null,
                    amount: (
                      <Typography
                        variant="bodySmallRegular"
                        css={(theme) => css`
                          color: ${theme.ds.colors.gray[500]};

                          [data-color-scheme='dark'] & {
                            color: ${theme.ds.colors.gray[600]};
                          }
                        `}
                      >
                        <FormattedMessage defaultMessage="No value" />
                      </Typography>
                    ),
                    help: (
                      <Tooltip
                        content={
                          <FormattedMessage defaultMessage="Configure rule total in step 3 “Configure payment” and compute statement to view value." />
                        }
                      >
                        <InfoIcon />
                      </Tooltip>
                    ),
                  }
              : {
                  currencyAmount: null,
                  amount: (
                    <Typography
                      variant="bodySmallRegular"
                      css={(theme) => css`
                        color: ${theme.ds.colors.gray[700]};

                        [data-color-scheme='dark'] & {
                          color: ${theme.ds.colors.gray[400]};
                        }
                      `}
                    >
                      <FormattedMessage defaultMessage="Non-payout" />
                    </Typography>
                  ),
                  help: null,
                }),
        }))
        .toSorted((a, b) => a.label.localeCompare(b.label))
        .concat(adjustmentsPayout ?? [])
    );
  }, [statement, adjustmentsPayout, challenges, paymentsByChallengeRules]);

  const total = useMemo(
    () => ruleResultWithLabel.reduce((acc, { currencyAmount }) => acc + (currencyAmount?.value ?? 0), 0),
    [ruleResultWithLabel],
  );

  return { ruleResultWithLabel, total };
};