All files / libs/payout-definition/plans/views/hub/rule-designer/src/lib/tabs/standard-rules PlanHubRuleDesignerTabs.tsx

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

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                                                                                                                                                                                                                                                                                                                                                                                                                         
import { useTheme } from '@emotion/react';
import styled from '@emotion/styled';
import { IconSquareNumber1Filled, IconSquareNumber2Filled, IconSquareNumber3Filled } from '@tabler/icons-react';
import { memo, useCallback, useEffect, type ReactNode } from 'react';
import { FormattedMessage } from 'react-intl';
import { generatePath } from 'react-router-dom';
import { match, P } from 'ts-pattern';

import {
  AlertBanner,
  Button,
  ButtonLink,
  Group,
  Tooltip,
  Typography,
  UnstyledButton,
} from '@allshares/studio-design-system';
import { routes } from '@amalia/core/routes';
import { isRuleConfigurationComplete } from '@amalia/payout-definition/plans/shared';
import { useRulePlanConfiguration } from '@amalia/payout-definition/state';

import { useRuleDesignerForecastContext } from '../../forecast/RuleDesignerForecast.context';
import { usePlanHubRuleDesignerStepTab } from '../../hooks/use-plan-hub-rule-designer-step-tab';
import { usePlanHubRuleDesignerContext } from '../../PlanHubRuleDesigner.context';
import { type PlanHubRuleDesignerStepTabs } from '../plan-hub-rule-designer-step-tabs.types';

const StyledContainer = styled(Group)`
  width: 100%;
  justify-content: space-between;
  padding: 0 24px;
`;

const StyledTabs = styled(Group)`
  align-items: center;
  height: 70px;
  // To apply the blue border to the border-bottom of the group
  margin-bottom: -6px;
`;

const StyledTabButton = styled(UnstyledButton, {
  shouldForwardProp: (prop) => !['isForecastView', 'isSelected'].includes(prop),
})<{ isSelected: boolean; isForecastView: boolean }>`
  display: flex;
  align-items: center;
  padding: 6px 16px 16px 16px;
  border-bottom: 4px solid
    ${({ isSelected, theme, isForecastView }) =>
      isSelected ? (isForecastView ? theme.ds.hues.purple[400] : theme.ds.colors.primary[400]) : 'none'};
`;

const StyledTabTitle = styled(Typography, {
  shouldForwardProp: (prop) => !['isDisabled', 'isSelected'].includes(prop),
})<{ isSelected: boolean; isDisabled: boolean }>`
  margin-left: 8px;
  color: ${({ isSelected, theme, isDisabled }) => theme.ds.colors.gray[isSelected ? 900 : isDisabled ? 300 : 700]};

  [data-color-scheme='dark'] & {
    color: ${({ isSelected, theme, isDisabled }) => theme.ds.colors.gray[isSelected ? 100 : isDisabled ? 600 : 400]};
  }
`;

const StyledRightSection = styled(Group)`
  align-items: center;
  gap: 16px;
`;

export const PlanHubRuleDesignerTabs = memo(function PlanHubRuleDesignerTabs() {
  const [selectedRuleDesignerTab, setSelectedRuleDesignerTab] = usePlanHubRuleDesignerStepTab();

  const theme = useTheme();
  const { planId, ruleId } = usePlanHubRuleDesignerContext();
  const { data: rulePlanConfiguration, error } = useRulePlanConfiguration(planId, ruleId);
  const { isForecastedView } = useRuleDesignerForecastContext();

  const handleClickNavigationButton = useCallback(
    (action: 'back' | 'next') => {
      match([selectedRuleDesignerTab, action, isForecastedView])
        // Previous navigation
        .with(['2-design-commission-structure', 'back', P.any], () => setSelectedRuleDesignerTab('1-define-crediting'))
        .with(['3-configure-payment', 'back', P.any], () => setSelectedRuleDesignerTab('2-design-commission-structure'))
        // Next navigation
        .with(['1-define-crediting', 'next', P.any], () => setSelectedRuleDesignerTab('2-design-commission-structure'))
        .with(['2-design-commission-structure', 'next', false], () => setSelectedRuleDesignerTab('3-configure-payment'))
        .with(['2-design-commission-structure', 'next', true], () => setSelectedRuleDesignerTab('1-define-crediting'))
        .otherwise(() => {
          throw new Error(`Unexpected combination of tab value and action: ${selectedRuleDesignerTab}, ${action}`);
        });
    },
    [selectedRuleDesignerTab, setSelectedRuleDesignerTab, isForecastedView],
  );

  // Don't allow to navigate to the last tab if the view is forecasted
  useEffect(() => {
    if (isForecastedView && selectedRuleDesignerTab === '3-configure-payment') {
      setSelectedRuleDesignerTab('2-design-commission-structure');
    }
  }, [isForecastedView, selectedRuleDesignerTab, setSelectedRuleDesignerTab]);

  if (error) {
    return <AlertBanner variant="error">{error.message}</AlertBanner>;
  }

  const isFirstTabSelected = selectedRuleDesignerTab === '1-define-crediting';
  const isLastTabSelected =
    selectedRuleDesignerTab === '3-configure-payment' ||
    (isForecastedView && selectedRuleDesignerTab === '2-design-commission-structure');

  return (
    <StyledContainer>
      <StyledTabs>
        {Array.from<{
          tabValue: PlanHubRuleDesignerStepTabs;
          TabIcon: typeof IconSquareNumber1Filled | typeof IconSquareNumber2Filled | typeof IconSquareNumber3Filled;
          tabLabel: ReactNode;
          isTabDisabled?: boolean;
        }>([
          {
            tabValue: '1-define-crediting',
            TabIcon: IconSquareNumber1Filled,
            tabLabel: <FormattedMessage defaultMessage="Define crediting" />,
          },
          {
            tabValue: '2-design-commission-structure',
            TabIcon: IconSquareNumber2Filled,
            tabLabel: <FormattedMessage defaultMessage="Design commission structure" />,
          },
          {
            tabValue: '3-configure-payment',
            TabIcon: IconSquareNumber3Filled,
            tabLabel: <FormattedMessage defaultMessage="Configure payment" />,
            isTabDisabled: isForecastedView,
          },
        ]).map(({ tabValue, TabIcon, tabLabel, isTabDisabled = false }, tabIndex) => {
          const isSelectedTab = selectedRuleDesignerTab === tabValue;
          const titlePrefix = `${tabIndex + 1}. `;

          return (
            <Tooltip
              key={tabValue}
              content={
                !!isTabDisabled && (
                  <FormattedMessage defaultMessage="Payment can only be configured from the actual rule." />
                )
              }
            >
              <StyledTabButton
                key={tabValue}
                disabled={isTabDisabled}
                isForecastView={isForecastedView}
                isSelected={isSelectedTab}
                onClick={() => setSelectedRuleDesignerTab(tabValue)}
              >
                {!!isSelectedTab && (
                  <TabIcon
                    fill={isForecastedView ? theme.ds.hues.purple[400] : theme.ds.colors.primary[400]}
                    size={24}
                  />
                )}

                <StyledTabTitle
                  isDisabled={isTabDisabled}
                  isSelected={isSelectedTab}
                  variant={isSelectedTab ? 'heading2Bold' : 'bodyLargeRegular'}
                >
                  {!isSelectedTab && titlePrefix}
                  {tabLabel}
                </StyledTabTitle>
              </StyledTabButton>
            </Tooltip>
          );
        })}
      </StyledTabs>

      <StyledRightSection>
        {!isFirstTabSelected && (
          <Button
            size="large"
            variant="primary-light"
            onClick={() => handleClickNavigationButton('back')}
          >
            <FormattedMessage defaultMessage="Previous" />
          </Button>
        )}

        {isLastTabSelected ? (
          <ButtonLink
            disabled={!rulePlanConfiguration?.rule || !isRuleConfigurationComplete(rulePlanConfiguration.rule)}
            size="large"
            to={generatePath(routes.PLAN_HUB_RULES, { planId })}
          >
            <FormattedMessage defaultMessage="Finish" />
          </ButtonLink>
        ) : (
          <Button
            size="large"
            onClick={() => handleClickNavigationButton('next')}
          >
            <FormattedMessage defaultMessage="Next" />
          </Button>
        )}
      </StyledRightSection>
    </StyledContainer>
  );
});