All files / src/features/Merchants/MerchantSidePanel/Modals/SetManualRiskLevelModal SetManualRiskLevelModal.tsx

100% Statements 38/38
86.36% Branches 19/22
100% Functions 10/10
100% Lines 38/38

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 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336                                                                                                                                  1x               1x                   43x 43x 43x       43x 43x 43x   43x   43x       43x   43x 43x   43x 43x 43x             43x 43x   43x 3x             3x 3x 3x             3x           43x                                                                                                     1x       43x                             1x                                                                                 172x                                             28x   28x         28x   6x       112x   112x                         112x 82x     30x                                                            
import { Fragment, useRef, useState } from "react";
import NiceModal from "@ebay/nice-modal-react";
import { Box, FormControlLabel, RadioGroup, Stack } from "@mui/material";
import { useForm, Controller, FormProvider, useFormContext } from "react-hook-form";
import { capitalize } from "lodash";
import { ChatsCircleIcon } from "@phosphor-icons/react";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import GiveButton from "@shared/Button/GiveButton";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import GiveText from "@shared/Text/GiveText";
import GiveRadio from "@shared/Radio/GiveRadio";
import GiveTooltip from "@shared/Tooltip/GiveTooltip";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import {
  TRiskLevel,
  TRiskStatus,
} from "@components/Merchants/MerchantPreview/RiskProfile/types";
import { useOpenGiveConversation } from "@features/GiveConversation/hooks/useOpenGiveConversation";
import {
  MerchantInfoContent,
  NotesContent,
} from "../../UnderwritingTasks/components/Sections";
import TaskCard from "../../UnderwritingTasks/components/TaskCard";
import { TaskActionType } from "../../UnderwritingTasks/types";
import { isBelowComputed } from "../../components/RiskSection/manualRiskLevel/riskLevelOrder";
import {
  SET_MANUAL_RISK_LEVEL_MODAL_TITLE,
  MINIMUM_RISK_LEVEL_SECTION_TITLE,
  CURRENT_RISK_SUMMARY_TITLE,
  MERCHANT_SECTION_TITLE,
  RISK_LEVEL_OPTIONS,
  NONE_OPTION_LABEL,
  NONE_OPTION_VALUE,
  RISK_REASON_LABEL,
  RISK_REASON_PLACEHOLDER,
  MANUAL_RISK_LEVEL_THREAD_NAME,
  SAVE_DISABLED_TOOLTIP,
  belowComputedTooltip,
} from "../../components/RiskSection/manualRiskLevel/constants";
import useUpdateManualRiskLevel from "../../hooks/useUpdateManualRiskLevel";
import RiskSummaryLabels from "../../components/RiskSection/RiskSummaryLabels";
import RiskActivity from "../../components/RiskSection/RiskActivity";
 
type SelectValue = TRiskLevel | typeof NONE_OPTION_VALUE;
 
export interface SetManualRiskLevelModalProps {
  merchantId: number;
  profileId: number;
  computedLevel: TRiskLevel;
  currentManualLevel: TRiskLevel | null;
  riskLabel: TRiskLevel;
  currentStatusName: TRiskStatus;
  merchantData: { name: string; identifier: string; imageURL?: string };
}
 
type FormInputs = { level: SelectValue; reason: string };
 
interface ModalItem {
  title: string;
  content: JSX.Element;
  onEdit?: () => void;
  actions?: TaskActionType[];
}
 
const radioLabelSx = {
  "&.MuiFormControlLabel-root": {
    margin: "0px",
    gap: "12px",
    alignItems: "flex-start",
  },
};
 
const SetManualRiskLevelModal = NiceModal.create(
  ({
    merchantId,
    profileId,
    computedLevel,
    currentManualLevel,
    riskLabel,
    currentStatusName,
    merchantData,
  }: SetManualRiskLevelModalProps) => {
    const { open, onRemove } = useNiceModal();
    const { isMobileView } = useCustomThemeV2();
    const { updateManualRiskLevel, isLoading } = useUpdateManualRiskLevel(
      profileId,
      merchantId,
    );
    const { handleOpenConversation } = useOpenGiveConversation();
    const [isNotesFocused, setIsNotesFocused] = useState(false);
    const notesRef = useRef<HTMLTextAreaElement | null>(null);
 
    const initialValue: SelectValue = currentManualLevel ?? NONE_OPTION_VALUE;
 
    const methods = useForm<FormInputs>({
      mode: "onChange",
      defaultValues: { level: initialValue, reason: "" },
    });
    const { handleSubmit, watch } = methods;
 
    const level = watch("level");
    const reason = watch("reason");
 
    const isChanged = level !== initialValue;
    const isMandatoryInfoComplete = isChanged && reason.trim().length > 0;
    const canSave = isMandatoryInfoComplete && !isLoading;
 
    // The tooltip only explains what is still missing before an *automatic*
    // risk level can be overridden, so it is irrelevant once a manual level is
    // already applied, and it must disappear as soon as both mandatory fields
    // are filled — including while the save request is in flight, which is why
    // it keys off isMandatoryInfoComplete rather than canSave (GB-21603).
    const hasManualOverride = !!currentManualLevel;
    const showSaveTooltip = !hasManualOverride && !isMandatoryInfoComplete;
 
    const onSubmit = (data: FormInputs) => {
      updateManualRiskLevel(
        {
          riskLevel: data.level === NONE_OPTION_VALUE ? null : data.level,
          reason: data.reason.trim(),
        },
        {
          onSuccess: (responseData) => {
            const threadId = responseData?.manualRiskLevelThreadID;
            Eif (threadId) {
              handleOpenConversation({
                merchantData: { id: merchantId },
                threadName: MANUAL_RISK_LEVEL_THREAD_NAME,
                initialThreadID: threadId,
                initialTab: "team",
              });
            }
            onRemove();
          },
        },
      );
    };
 
    const items: ModalItem[] = [
      {
        title: MERCHANT_SECTION_TITLE,
        content: (
          <MerchantInfoContent
            name={merchantData.name}
            // BE doesn't expose a separate legal name to this modal yet, so we
            // fall back to the merchant (display) name for the recap line.
            legalName={merchantData.name}
            taxID={merchantData.identifier}
            imageURL={merchantData.imageURL}
            merchantID={merchantId}
            threadName={MANUAL_RISK_LEVEL_THREAD_NAME}
          />
        ),
      },
      {
        title: CURRENT_RISK_SUMMARY_TITLE,
        content: (
          <RiskActivity
            profileId={profileId}
            merchantId={merchantId}
            riskLabel={riskLabel}
          />
        ),
        actions: [
          {
            element: (
              <RiskSummaryLabels
                effectiveLevel={riskLabel}
                riskStatusName={currentStatusName}
              />
            ),
          },
        ],
      },
      {
        title: MINIMUM_RISK_LEVEL_SECTION_TITLE,
        content: <MinimumRiskLevelContent computedLevel={computedLevel} />,
      },
      {
        title: RISK_REASON_LABEL,
        content: (
          <NotesContent
            name="reason"
            placeholder={RISK_REASON_PLACEHOLDER}
            inputRef={notesRef}
            setIsNotesFocused={setIsNotesFocused}
            maxLength={5000}
          />
        ),
        onEdit: isNotesFocused ? undefined : () => notesRef.current?.focus(),
      },
    ];
 
    return (
      <FormProvider {...methods}>
        <GiveBaseModal
          data-testid="set-manual-risk-level-modal"
          open={open}
          onClose={onRemove}
          title={SET_MANUAL_RISK_LEVEL_MODAL_TITLE}
          headerRightContent={
            isMobileView ? undefined : (
              <GiveIconButton
                variant="ghost"
                Icon={ChatsCircleIcon}
                data-testid="open-conversation-header-icon"
                aria-label="Open conversation"
                onClick={() =>
                  handleOpenConversation({
                    merchantData: { id: merchantId },
                    initialTab: "team",
                  })
                }
              />
            )
          }
          buttons={
            <>
              <GiveButton
                label="Cancel"
                size="large"
                variant="ghost"
                onClick={onRemove}
              />
              <GiveTooltip
                title={showSaveTooltip ? SAVE_DISABLED_TOOLTIP : ""}
                // GiveTooltip always renders a popper body, so an empty title
                // still shows a blank bubble on hover/click — suppress the
                // listeners instead of relying on an empty title (GB-21603).
                disableHoverListener={!showSaveTooltip}
                fluidWidth
              >
                <span
                  data-testid="save-tooltip-anchor"
                  style={{ display: "inline-flex" }}
                >
                  <GiveButton
                    label="Save"
                    size="large"
                    disabled={!canSave}
                    onClick={handleSubmit(onSubmit)}
                  />
                </span>
              </GiveTooltip>
            </>
          }
        >
          <Stack gap="20px">
            {items.map((item, index) => (
              <TaskCard
                key={index}
                title={item.title}
                onEdit={item.onEdit}
                actions={item.actions}
              >
                {item.content}
              </TaskCard>
            ))}
          </Stack>
        </GiveBaseModal>
      </FormProvider>
    );
  },
);
 
export default SetManualRiskLevelModal;
 
function MinimumRiskLevelContent({
  computedLevel,
}: {
  computedLevel: TRiskLevel;
}) {
  const { control } = useFormContext<FormInputs>();
 
  return (
    <Controller
      name="level"
      control={control}
      render={({ field: { onChange, value } }) => (
        <RadioGroup
          value={value || ""}
          onChange={(e) => onChange(e.target.value)}
          sx={{ gap: "12px" }}
        >
          {RISK_LEVEL_OPTIONS.map((option) => {
            const isBelow = isBelowComputed(option.value, computedLevel);
            const radioControl = (
              <FormControlLabel
                value={option.value}
                control={<GiveRadio />}
                label={
                  <GiveText variant="bodyS" color="primary">
                    {option.label}
                  </GiveText>
                }
                checked={`${value}` === `${option.value}`}
                sx={radioLabelSx}
              />
            );
 
            if (!isBelow) {
              return <Fragment key={option.value}>{radioControl}</Fragment>;
            }
 
            return (
              <GiveTooltip
                key={option.value}
                title={belowComputedTooltip(capitalize(computedLevel))}
              >
                <Box
                  data-testid={`below-computed-tooltip-${option.value}`}
                  sx={{ display: "flex", width: "100%", justifyContent: "flex-start" }}
                >
                  {radioControl}
                </Box>
              </GiveTooltip>
            );
          })}
          <FormControlLabel
            value={NONE_OPTION_VALUE}
            control={<GiveRadio />}
            label={
              <GiveText variant="bodyS" color="primary">
                {NONE_OPTION_LABEL}
              </GiveText>
            }
            checked={`${value}` === NONE_OPTION_VALUE}
            sx={radioLabelSx}
          />
        </RadioGroup>
      )}
    />
  );
}