All files / libs/lti/components/src/lib/enrollment/simulation-widget/configuration SimulationWidgetPresentationConfiguration.tsx

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

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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { css } from '@emotion/react';
import { IconReload } from '@tabler/icons-react';
import { memo, useCallback, useMemo } from 'react';
import { FormattedMessage, useIntl } from 'react-intl';

import {
  FormFieldLabel,
  Group,
  IconButton,
  Input,
  Stack,
  TextOverflow,
  Typography,
} from '@allshares/studio-design-system';
import { FormatsEnum } from '@amalia/data-capture/fields/types';
import { type CurrencySymbolsEnum } from '@amalia/ext/iso-4217';
import {
  type CompanyShareWithPrice,
  type EnrollmentSimulationWidget,
  type LtiPlan,
  type LtiPlanKpi,
} from '@amalia/lti/types';

import { KpiFormatIcon } from '../../../forms/fields/kpi-performance/KpiFormatIcon';
import {
  percentTransformFrom,
  percentTransformTo,
} from '../../../forms/fields/kpi-performance/KpiPerformanceLinearForm';
import { LtiTracingButton } from '../../../tracing/LtiTracingButton';
import { MonetaryValueForWidget } from '../../common/MonetaryValueForWidget';
import { type SimulationWidgetSize } from '../types';

const computeInputStepForKpi = (kpi: Pick<LtiPlanKpi, 'configuration'>) => {
  const lastStep = kpi.configuration.steps.at(-1)?.[0] ?? 0;
  if (lastStep <= 10) {
    return 0.1;
  }
  if (lastStep <= 100) {
    return 1;
  }

  // Use base-10 logarithm to determine step size
  return 10 ** (Math.floor(Math.log10(lastStep)) - 2);
};

export type SimulationWidgetPresentationConfigurationProps = {
  readonly kpis: LtiPlan['kpis'];
  readonly kpisValues: NonNullable<LtiPlan['kpiValues']>;
  readonly initialKpisValues: LtiPlan['kpiValues'];
  readonly sharePrice?: CompanyShareWithPrice;
  readonly sharesCount: number;
  readonly currency: CurrencySymbolsEnum;
  readonly size: SimulationWidgetSize;
  readonly totalSharesEarned: number;
  readonly totalAmountEarned: number;
  readonly simulatedSharePrice: number;
  readonly onChangeKpiValue: (kpiId: LtiPlanKpi['id'], value: number) => void;
  readonly onReset: () => void;
  readonly onChangeSimulatedSharePrice: (value: number) => void;
  readonly widgetConfiguration: Pick<
    EnrollmentSimulationWidget,
    'showKpiBreakdown' | 'showMonetaryValues' | 'showSharePriceSlider'
  >;
};

export const SimulationWidgetPresentationConfiguration = memo(function SimulationWidgetPresentationConfiguration({
  kpis,
  kpisValues,
  initialKpisValues,
  sharePrice,
  sharesCount,
  currency,
  size,
  widgetConfiguration,
  totalSharesEarned,
  totalAmountEarned,
  simulatedSharePrice,
  onReset,
  onChangeKpiValue,
  onChangeSimulatedSharePrice,
}: SimulationWidgetPresentationConfigurationProps) {
  const { formatMessage, formatNumber } = useIntl();

  const handleChangeKpiValue = useCallback(
    (kpiId: LtiPlanKpi['id'], value: string) => {
      onChangeKpiValue(kpiId, +value);
    },
    [onChangeKpiValue],
  );

  const handleSharePriceChange = useCallback(
    (value: string) => {
      onChangeSimulatedSharePrice(+value);
    },
    [onChangeSimulatedSharePrice],
  );

  const inputStepForKpi = useMemo(
    () =>
      kpis.reduce<Record<LtiPlanKpi['id'], number>>((acc, kpi) => {
        acc[kpi.id] = computeInputStepForKpi(kpi);
        return acc;
      }, {}),
    [kpis],
  );

  return (
    <Stack
      gap={size === 'compact' ? 16 : 24}
      css={css`
        padding: ${size === 'compact' ? '24px 32px 32px' : '24px 40px 32px'};
        flex: none;
        width: var(--widget-block-width);
      `}
    >
      <Stack gap={size === 'compact' ? 6 : 8}>
        <Typography
          variant={size === 'compact' ? 'bodyXsmallRegular' : 'bodySmallRegular'}
          css={css`
            color: var(--ds-text-color-500);
          `}
        >
          <FormattedMessage defaultMessage="Simulated total shares" />
        </Typography>

        <Group
          align="baseline"
          justify="space-between"
        >
          <Group
            align="center"
            gap={8}
          >
            <Typography variant={size === 'compact' ? 'heading4Medium' : 'heading1Medium'}>
              {formatNumber(totalSharesEarned)}
            </Typography>

            {size === 'default' && (
              <LtiTracingButton
                simulated
                kpis={kpis}
                kpiValues={initialKpisValues}
                sharesCount={sharesCount}
              />
            )}
          </Group>

          {!!(sharePrice && widgetConfiguration.showMonetaryValues) && (
            <MonetaryValueForWidget
              symbol={sharePrice.currency}
              symbolTypographyVariant={size === 'compact' ? 'bodyXsmallRegular' : 'bodyLargeRegular'}
              value={totalAmountEarned}
              valueTypographyVariant={size === 'compact' ? 'bodyLargeRegular' : 'heading2Regular'}
              css={css`
                justify-self: end;
              `}
            />
          )}
        </Group>
      </Stack>

      <Stack gap={8}>
        <Group justify="flex-end">
          <IconButton
            icon={<IconReload />}
            label={formatMessage({ defaultMessage: 'Reset values' })}
            size="small"
            onClick={onReset}
          />
        </Group>

        <Stack gap={size === 'compact' ? 16 : 24}>
          <Stack
            gap={size === 'compact' ? 8 : 16}
            css={css`
              &:empty {
                display: none;
              }
            `}
          >
            {kpis.map((kpi) => (
              <Group
                key={kpi.id}
                align="center"
                gap={size === 'compact' ? 8 : 16}
                justify="space-between"
                css={css`
                  width: 100%;
                `}
              >
                <FormFieldLabel
                  size="small"
                  css={css`
                    width: ${size === 'compact' ? '100px' : '120px'};
                  `}
                >
                  <TextOverflow content={kpi.name}>{kpi.name}</TextOverflow>
                </FormFieldLabel>

                <Input
                  size={size === 'compact' ? 'xsmall' : 'small'}
                  step={inputStepForKpi[kpi.id]}
                  type="number"
                  value={`${kpi.format === FormatsEnum.percent ? percentTransformFrom(kpisValues[kpi.id]) : kpisValues[kpi.id]}`}
                  css={css`
                    max-width: 180px;
                  `}
                  rightIcon={
                    <KpiFormatIcon
                      kpi={kpi}
                      kpiCurrencySymbol={currency}
                    />
                  }
                  onChange={(v) =>
                    handleChangeKpiValue(kpi.id, kpi.format === FormatsEnum.percent ? percentTransformTo(v) : v)
                  }
                />
              </Group>
            ))}
          </Stack>

          {!!(sharePrice && widgetConfiguration.showSharePriceSlider && widgetConfiguration.showMonetaryValues) && (
            <Group
              align="center"
              gap={16}
              justify="space-between"
            >
              <FormFieldLabel
                size="small"
                css={css`
                  width: ${size === 'compact' ? '100px' : '120px'};
                `}
              >
                <FormattedMessage defaultMessage="Share price" />
              </FormFieldLabel>

              <Group
                align="center"
                gap={8}
              >
                <Input
                  max={(sharePrice.value ?? 0) * 2}
                  min={0}
                  size="small"
                  step={0.1}
                  type="range"
                  value={`${simulatedSharePrice}`}
                  css={css`
                    padding-left: 0;
                    padding-right: 0;
                    box-shadow: none;
                  `}
                  onChange={handleSharePriceChange}
                />

                <Group
                  align="baseline"
                  gap={8}
                  justify="flex-end"
                  css={css`
                    width: 70px;
                  `}
                >
                  <Typography variant="bodyBaseMedium">{formatNumber(+simulatedSharePrice.toFixed(1))}</Typography>
                  <Typography variant="bodyXsmallMedium">{sharePrice.currency}</Typography>
                </Group>
              </Group>
            </Group>
          )}
        </Stack>
      </Stack>
    </Stack>
  );
});