All files / client/src/views/program-item/body/components AdminActionCard.tsx

87.2% Statements 75/86
75% Branches 24/32
76.66% Functions 23/30
87.2% Lines 75/86

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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361                                                              520x 96x 96x   96x 96x 124x     96x 96x 96x   96x   96x   96x   96x 96x 96x       96x   28x     6x       6x       28x     6x     6x       96x 6x   6x   6x 3x   6x   6x 3x 3x 3x     6x     3x         5x       5x     5x     96x 2x   2x       2x       2x     2x               96x       6x 6x 6x 3x   6x 6x       96x 6x   6x                     6x       6x     6x     6x 6x 6x 6x                               6x                                           11x                         7x         7x                           92x           3x                     3x                                             3x                                                               3x                     1x 96x                   1x           1x           1x       26x        
import { ChangeEvent, ReactElement, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import {
  ProgramItem,
  ProgramItemSignupStrategy,
} from "shared/types/models/programItem";
import {
  SignupQuestionSelectOption,
  SignupQuestionType,
} from "shared/types/models/settings";
import loaderImage from "assets/loading.gif";
import { Button } from "client/components/Button";
import { ButtonGroup } from "client/components/ButtonGroup";
import { Checkbox } from "client/components/Checkbox";
import { ControlledInput } from "client/components/ControlledInput";
import { Dropdown } from "client/components/Dropdown";
import { UncontrolledInput } from "client/components/UncontrolledInput";
import { ButtonStyle } from "client/components/componentStyles";
import { useAppDispatch, useAppSelector } from "client/utils/hooks";
import { selectHiddenProgramItems } from "client/views/admin/adminSlice";
import {
  submitAddSignupQuestion,
  submitDeleteSignupQuestion,
  submitUpdateHidden,
} from "client/views/admin/adminThunks";
 
interface Props {
  programItem: ProgramItem;
}
 
export const AdminActionCard = ({ programItem }: Props): ReactElement => {
  const dispatch = useAppDispatch();
  const { t } = useTranslation();
 
  const hiddenProgramItems = useAppSelector(selectHiddenProgramItems);
  const signupQuestions = useAppSelector(
    (state) => state.admin.signupQuestions,
  );
 
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [hidden, setHidden] = useState<boolean>(false);
  const [hasSignupQuestion, setHasSignupQuestion] = useState<boolean>(false);
  const [isPrivateSignupQuestion, setIsPrivateSignupQuestion] =
    useState<boolean>(false);
  const [signupQuestionInputFi, setSignupQuestionInputFi] =
    useState<string>("");
  const [signupQuestionInputEn, setSignupQuestionInputEn] =
    useState<string>("");
  const [signupQuestionInputVisible, setSignupQuestionInputVisible] =
    useState<boolean>(false);
  const [questionType, setQuestionType] = useState(SignupQuestionType.TEXT);
  const [selectOptions, setSelectOptions] = useState<
    SignupQuestionSelectOption[]
  >([]);
 
  useEffect(() => {
    // Check if hidden
    if (
      hiddenProgramItems.some(
        (hiddenProgramItem) =>
          hiddenProgramItem.programItemId === programItem.programItemId,
      )
    ) {
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setHidden(true);
    }
 
    // Check if sign-up question exists
    if (
      signupQuestions.some(
        (signupQuestion) =>
          signupQuestion.programItemId === programItem.programItemId,
      )
    ) {
      setHasSignupQuestion(true);
    }
  }, [programItem.programItemId, hiddenProgramItems, signupQuestions]);
 
  const updateHidden = async (): Promise<void> => {
    setSubmitting(true);
 
    const newHidden = !hidden;
 
    const programItemIndex = hiddenProgramItems.findIndex(
      (p) => p.programItemId === programItem.programItemId,
    );
    const allHiddenProgramItems = [...hiddenProgramItems];
 
    if (newHidden && programItemIndex === -1) {
      allHiddenProgramItems.push(programItem);
    } else Eif (!newHidden && programItemIndex > -1) {
      allHiddenProgramItems.splice(programItemIndex, 1);
    }
 
    const error = await dispatch(
      submitUpdateHidden(
        allHiddenProgramItems.map(
          (hiddenProgramItem) => hiddenProgramItem.programItemId,
        ),
      ),
    );
 
    Iif (error) {
      // eslint-disable-next-line no-console
      console.log(`submitUpdateHidden error: ${error}`);
    } else {
      setHidden(newHidden);
    }
 
    setSubmitting(false);
  };
 
  const deleteSignupQuestion = async (): Promise<void> => {
    setSubmitting(true);
 
    const error = await dispatch(
      submitDeleteSignupQuestion(programItem.programItemId),
    );
 
    Iif (error) {
      // eslint-disable-next-line no-console
      console.log(`deleteSignupQuestion error: ${error}`);
    } else {
      setHasSignupQuestion(false);
    }
 
    setSubmitting(false);
  };
 
  // Each select option is edited through two inputs, one per language, so an
  // edit merges into whatever the other language already put there. The inputs
  // can be filled in any order, and an option is only valid with both languages
  // set, so the entries up to the edited one are filled in rather than left as
  // holes the server would reject
  const updateSelectOption = (
    index: number,
    option: Partial<SignupQuestionSelectOption>,
  ): void => {
    setSelectOptions((previousOptions) => {
      const updatedOptions = [...previousOptions];
      while (updatedOptions.length <= index) {
        updatedOptions.push({ optionFi: "", optionEn: "" });
      }
      updatedOptions[index] = { ...updatedOptions[index], ...option };
      return updatedOptions;
    });
  };
 
  const addSignupQuestion = async (): Promise<void> => {
    setSubmitting(true);
 
    const error = await dispatch(
      submitAddSignupQuestion({
        programItemId: programItem.programItemId,
        questionFi: signupQuestionInputFi,
        questionEn: signupQuestionInputEn,
        private: isPrivateSignupQuestion,
        type: questionType,
        selectOptions,
      }),
    );
 
    Iif (error) {
      // eslint-disable-next-line no-console
      console.log(`addSignupQuestion error: ${error}`);
    } else {
      setHasSignupQuestion(true);
    }
 
    setSubmitting(false);
 
    // Clear inputs
    setSignupQuestionInputVisible(false);
    setSignupQuestionInputFi("");
    setSignupQuestionInputEn("");
    setIsPrivateSignupQuestion(false);
  };
 
  return (
    <Container>
      <HeaderContainer>
        <h4>{t("programItemInfo.adminActions")}</h4>
        {submitting && (
          <img alt={t("loading")} src={loaderImage} height="24" width="24" />
        )}
      </HeaderContainer>
      <ButtonGroup>
        <Button
          key="hideButton"
          disabled={submitting}
          buttonStyle={ButtonStyle.PRIMARY}
          onClick={async () => await updateHidden()}
        >
          {t(hidden ? "button.showProgramItem" : "button.hideProgramItem")}
        </Button>
        {hasSignupQuestion && (
          <Button
            key="signUpButton"
            disabled={submitting}
            buttonStyle={ButtonStyle.PRIMARY}
            onClick={deleteSignupQuestion}
          >
            {t("button.removeSignupQuestion")}
          </Button>
        )}
        {!hasSignupQuestion &&
          !signupQuestionInputVisible &&
          programItem.signupStrategy !== ProgramItemSignupStrategy.LOTTERY && (
            <Button
              key="addSignUpQuestionButton"
              disabled={submitting}
              buttonStyle={ButtonStyle.PRIMARY}
              onClick={() =>
                setSignupQuestionInputVisible(!signupQuestionInputVisible)
              }
            >
              {t("button.addSignupQuestion")}
            </Button>
          )}
      </ButtonGroup>
      {signupQuestionInputVisible && (
        <WithRowGap>
          <span>{t("signupQuestion.addSignupTextField")}</span>
          <ControlledInput
            placeholder={t("signupQuestion.inFinnish")}
            value={signupQuestionInputFi}
            onChange={(event) => setSignupQuestionInputFi(event.target.value)}
          />
          <ControlledInput
            placeholder={t("signupQuestion.inEnglish")}
            value={signupQuestionInputEn}
            onChange={(event) => setSignupQuestionInputEn(event.target.value)}
          />
          <Checkbox
            checked={isPrivateSignupQuestion}
            onChange={() => {
              setIsPrivateSignupQuestion(!isPrivateSignupQuestion);
            }}
            label={t("signupQuestion.privateQuestion")}
            id={"privateQuestionCheckbox"}
          />
 
          <div>
            <span>{t("signupQuestion.questionType")}</span>{" "}
            <Dropdown
              options={Object.values(SignupQuestionType).map((type) => ({
                value: type,
                title: t(`signupQuestionType.${type}`),
              }))}
              selectedValue={questionType}
              onChange={(event: ChangeEvent<HTMLSelectElement>) =>
                setQuestionType(event.target.value as SignupQuestionType)
              }
            />
          </div>
 
          {questionType === SignupQuestionType.SELECT && (
            <>
              <InputsContainer>
                <span>{t("signupQuestion.inFinnish")}</span>
                <UncontrolledInput
                  onChange={(event) =>
                    updateSelectOption(0, { optionFi: event.target.value })
                  }
                />
                <UncontrolledInput
                  onChange={(event) =>
                    updateSelectOption(1, { optionFi: event.target.value })
                  }
                />
                <UncontrolledInput
                  onChange={(event) =>
                    updateSelectOption(2, { optionFi: event.target.value })
                  }
                />
                <UncontrolledInput
                  onChange={(event) =>
                    updateSelectOption(3, { optionFi: event.target.value })
                  }
                />
              </InputsContainer>
              <InputsContainer>
                <span>{t("signupQuestion.inEnglish")}</span>
                <UncontrolledInput
                  onChange={(event) =>
                    updateSelectOption(0, { optionEn: event.target.value })
                  }
                />
                <UncontrolledInput
                  onChange={(event) =>
                    updateSelectOption(1, { optionEn: event.target.value })
                  }
                />
                <UncontrolledInput
                  onChange={(event) =>
                    updateSelectOption(2, { optionEn: event.target.value })
                  }
                />
                <UncontrolledInput
                  onChange={(event) =>
                    updateSelectOption(3, { optionEn: event.target.value })
                  }
                />
              </InputsContainer>
            </>
          )}
 
          <ButtonGroup>
            <Button
              onClick={addSignupQuestion}
              buttonStyle={ButtonStyle.PRIMARY}
            >
              {t("button.save")}
            </Button>
            <Button
              disabled={submitting}
              buttonStyle={ButtonStyle.SECONDARY}
              onClick={() => setSignupQuestionInputVisible(false)}
            >
              {t("button.cancel")}
            </Button>
          </ButtonGroup>
        </WithRowGap>
      )}
    </Container>
  );
};
 
const Container = styled.div`
  border: 1px solid ${(props) => props.theme.borderActive};
  border-radius: 4px;
  margin: 8px 0;
  padding: 16px 8px 8px 8px;
  h4 {
    margin-bottom: 4px;
    margin-top: 4px;
  }
`;
 
const HeaderContainer = styled.div`
  align-items: center;
  display: flex;
  gap: 8px;
`;
 
const WithRowGap = styled.div`
  row-gap: 8px;
  display: grid;
  padding-top: 8px;
`;
 
const InputsContainer = styled.div`
  display: flex;
  flex-direction: column;
  gap: 8px;
  @media (min-width: ${(props) => props.theme.breakpointPhoneMin}) {
    max-width: 40%;
  }
`;