All files / client/src/views/program-item/signup/components/lottery-signup LotterySignupForm.tsx

84.09% Statements 37/44
21.42% Branches 3/14
83.33% Functions 10/12
83.33% Lines 35/42

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                                                              356x   356x         74x 74x     74x 184x 184x   74x       6x   6x     74x 222x     74x   74x     74x     74x   74x   74x       74x       74x 36x 36x 36x       36x       36x   36x     36x 36x   36x     74x 222x 222x                                                                                                                                                               1x       1x       1x      
import { ChangeEvent, SyntheticEvent, ReactElement, useState } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { capitalize } from "remeda";
import { ProgramItem } from "shared/types/models/programItem";
import {
  PostLotterySignupErrorMessage,
  submitPostLotterySignup,
} from "client/views/my-program-items/myProgramItemsThunks";
import { useAppDispatch, useAppSelector } from "client/utils/hooks";
import { Button, ButtonStyle } from "client/components/Button";
import { ErrorMessage } from "client/components/ErrorMessage";
import { Dropdown } from "client/components/Dropdown";
import { ButtonGroup } from "client/components/ButtonGroup";
import {
  DirectSignupWithProgramItem,
  selectLotterySignups,
} from "client/views/my-program-items/myProgramItemsSlice";
import { PostLotterySignupRequest } from "shared/types/api/myProgramItems";
import { InfoText, InfoTextVariant } from "client/components/InfoText";
import { startLoading, stopLoading } from "client/state/loading/loadingSlice";
import { getEntryCondition } from "client/views/program-item/programItemUtils";
import { isSignupConfirmDisabled } from "client/views/program-item/signup/components/signupFormUtils";
import { Checkbox } from "client/components/Checkbox";
 
interface Props {
  programItem: ProgramItem;
  closeSignupForm: () => void;
  directSignupForSlot?: DirectSignupWithProgramItem;
}
 
const OPTIONS = [1, 2, 3];
 
export const LotterySignupForm = ({
  programItem,
  closeSignupForm,
  directSignupForSlot,
}: Props): ReactElement => {
  const { t } = useTranslation();
  const dispatch = useAppDispatch();
 
  // We need all lottery signups here
  const lotterySignups = useAppSelector(selectLotterySignups);
  const isGroupCreator = useAppSelector((state) => state.group.isGroupCreator);
  const loading = useAppSelector((state) => state.loading);
 
  const selectedPriorities = new Set(
    lotterySignups
      .filter(
        (lotterySignup) =>
          lotterySignup.programItem.startTime === programItem.startTime,
      )
      .map((lotterySignup) => lotterySignup.priority),
  );
 
  const firstUnselected = OPTIONS.filter(
    (option) => !selectedPriorities.has(option),
  );
 
  const firstOption = firstUnselected.length > 0 ? firstUnselected[0] : 1;
 
  const [priority, setPriority] = useState<number>(firstOption);
 
  const [errorMessage, setErrorMessage] =
    useState<PostLotterySignupErrorMessage | null>(null);
 
  const [agreeEntryCondition, setAgreeEntryCondition] =
    useState<boolean>(false);
 
  const entryCondition = getEntryCondition(programItem, t);
 
  const onChange = (event: ChangeEvent<HTMLSelectElement>): void => {
    setPriority(Number(event.target.value));
  };
 
  const handleCancel = (): void => {
    closeSignupForm();
  };
 
  const handleSignup = async (event: SyntheticEvent): Promise<void> => {
    event.preventDefault();
    dispatch(startLoading());
    Iif (!priority) {
      return;
    }
 
    const newSignupRequest: PostLotterySignupRequest = {
      programItemId: programItem.programItemId,
      priority,
    };
    const error = await dispatch(submitPostLotterySignup(newSignupRequest));
 
    Iif (error) {
      setErrorMessage(error);
    } else {
      setErrorMessage(null);
      closeSignupForm();
    }
    dispatch(stopLoading());
  };
 
  const options = OPTIONS.map((n) => {
    const nStr = n.toString(10);
    return {
      value: nStr,
      title: nStr,
      disabled: selectedPriorities.has(n),
    };
  });
 
  return (
    <form>
      {t("signup.programItemPriority", {
        PROGRAM_TYPE: capitalize(
          t(`programTypeSingular.${programItem.programType}`),
        ),
      })}{" "}
      <StyledDropdown
        onChange={onChange}
        options={options}
        selectedValue={priority.toString()}
      />
      {entryCondition && (
        <Checkbox
          checked={agreeEntryCondition}
          onChange={() => {
            setAgreeEntryCondition(!agreeEntryCondition);
          }}
          label={entryCondition.label}
          id={entryCondition.id}
        />
      )}
      {directSignupForSlot && (
        <InfoText variant={InfoTextVariant.WARNING}>
          {t("signup.alreadySignedToProgramItem", {
            PROGRAM_TYPE: t(
              `programTypeIllative.${directSignupForSlot.programItem.programType}`,
            ),
          })}{" "}
          <b>{directSignupForSlot.programItem.title}</b>
          {". "}
          {t("signup.signupWillBeRemoved", {
            PROGRAM_TYPE_THIS: t(
              `programTypeIllative.${programItem.programType}`,
            ),
            PROGRAM_TYPE_OTHER: t(
              `programTypeIllative.${directSignupForSlot.programItem.programType}`,
            ),
            OTHER_PROGRAM_NAME: directSignupForSlot.programItem.title,
          })}
        </InfoText>
      )}
      {isGroupCreator && <InfoText>{t("signup.groupSignupInfo")}</InfoText>}
      <StyledButtonGroup>
        <StyledButton
          onClick={handleSignup}
          buttonStyle={ButtonStyle.PRIMARY}
          disabled={isSignupConfirmDisabled(
            Boolean(entryCondition),
            agreeEntryCondition,
            loading,
          )}
        >
          {t("signup.confirm")}
        </StyledButton>
        <StyledButton
          onClick={handleCancel}
          buttonStyle={ButtonStyle.SECONDARY}
          disabled={loading}
        >
          {t("signup.cancel")}
        </StyledButton>
      </StyledButtonGroup>
      {errorMessage && (
        <ErrorMessage
          message={t(errorMessage)}
          closeError={() => setErrorMessage(null)}
        />
      )}
    </form>
  );
};
 
const StyledDropdown = styled(Dropdown)`
  margin-right: 8px;
`;
 
const StyledButton = styled(Button)`
  min-width: 200px;
`;
 
const StyledButtonGroup = styled(ButtonGroup)`
  justify-content: center;
`;