All files / app/features/profile/view NewHostRequest.tsx

77.08% Statements 37/48
50% Branches 9/18
35.71% Functions 5/14
76.08% Lines 35/46

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                1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x   8x                                                                         1x       12x 12x 12x 12x 12x                   12x       12x   12x                               12x   12x       12x 96x 96x             12x 12x 12x                 12x                                                                                                                                                                                                                                          
import {
  CardActions,
  FormControlLabel,
  MenuItem,
  Radio,
  RadioGroup,
  Select,
  Typography,
} from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import { Skeleton } from "@material-ui/lab";
import Alert from "components/Alert";
import Button from "components/Button";
import Datepicker from "components/Datepicker";
import TextField from "components/TextField";
import { useProfileUser } from "features/profile/hooks/useProfileUser";
import { useUser } from "features/userQueries/useUsers";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { GLOBAL, PROFILE } from "i18n/namespaces";
import React, { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useMutation } from "react-query";
import { service } from "service";
import { CreateHostRequestWrapper } from "service/requests";
import { isSameOrFutureDate } from "utils/date";
 
const useStyles = makeStyles((theme) => ({
  buttonContainer: {
    display: "flex",
    justifyContent: "center",
    paddingTop: theme.spacing(1),
  },
  form: {
    "& > *": {
      marginTop: theme.spacing(2),
    },
  },
  title: {
    marginBottom: theme.spacing(1),
  },
  request: {
    display: "flex",
    flexDirection: "row",
  },
  date: {
    marginLeft: theme.spacing(2),
    marginRight: theme.spacing(2),
  },
  requestField: {
    marginTop: theme.spacing(2),
  },
  send: {
    display: "flex",
    justifyContent: "flex-end",
    marginTop: theme.spacing(2),
  },
}));
 
interface NewHostRequestProps {
  setIsRequestSuccess: (value: boolean) => void;
  setIsRequesting: (value: boolean) => void;
}
 
export default function NewHostRequest({
  setIsRequestSuccess,
  setIsRequesting,
}: NewHostRequestProps) {
  const { t } = useTranslation([GLOBAL, PROFILE]);
  const classes = useStyles();
  const isPostBetaEnabled = process.env.NEXT_PUBLIC_IS_POST_BETA_ENABLED;
  const [numVisitors, setNumVisitors] = useState(1);
  const user = useProfileUser();
 
  const {
    control,
    errors,
    getValues,
    handleSubmit,
    register,
    setValue,
    watch,
  } = useForm<CreateHostRequestWrapper>({
    defaultValues: { hostUserId: user.userId },
  });
 
  useEffect(() => register("hostUserId"));
 
  const { error, mutate } = useMutation<
    number,
    RpcError,
    CreateHostRequestWrapper
  >(
    (data: CreateHostRequestWrapper) => {
      return service.requests.createHostRequest(data);
    },
    {
      onSuccess: () => {
        setIsRequesting(false);
        setIsRequestSuccess(true);
      },
    }
  );
 
  const { isLoading: hostLoading, error: hostError } = useUser(user.userId);
 
  const onSubmit = handleSubmit((data) => {
    mutate(data);
  });
 
  const guests = Array.from({ length: 8 }, (_, i) => {
    const num = i + 1;
    return (
      <MenuItem key={num} value={num} ref={register}>
        {num}
      </MenuItem>
    );
  });
 
  const watchFromDate = watch("fromDate", undefined);
  useEffect(() => {
    Iif (
      watchFromDate &&
      getValues("toDate") &&
      isSameOrFutureDate(watchFromDate, getValues("toDate"))
    ) {
      setValue("toDate", watchFromDate.add(1, "day"));
    }
  });
 
  return (
    <>
      <Typography variant="h1">
        {hostLoading ? (
          <Skeleton width="100" />
        ) : (
          t("profile:request_form.send_request", { name: user.name })
        )}
      </Typography>
      {error && <Alert severity="error">{error.message}</Alert>}
      {hostError ? (
        <Alert severity={"error"}>{hostError}</Alert>
      ) : (
        <form onSubmit={onSubmit}>
          <div className={classes.request}>
            {isPostBetaEnabled && (
              <Controller
                name="stayType"
                control={control}
                defaultValue={1}
                render={({ onChange, value }) => (
                  <RadioGroup
                    aria-label={t("profile:request_form.stay_type_a11y_text")}
                    name="stay-radio"
                    value={value}
                    onChange={(value) => onChange(value)}
                  >
                    <FormControlLabel
                      value={t("profile:request_form.overnight_stay")}
                      control={<Radio />}
                      label={t("profile:request_form.overnight_stay")}
                    />
                    <FormControlLabel
                      value={t("profile:request_form.meetup_only")}
                      control={<Radio />}
                      label={t("profile:request_form.meetup_only")}
                    />
                  </RadioGroup>
                )}
              />
            )}
            <Datepicker
              control={control}
              error={!!errors.fromDate}
              helperText={
                //@ts-ignore
                errors?.fromDate?.message
              }
              id="from-date"
              label={t("profile:request_form.arrival_date")}
              name="fromDate"
              defaultValue={null}
              rules={{
                required: t("profile:request_form.arrival_date_empty"),
                validate: (stringDate) => stringDate !== "",
              }}
            />
            <Datepicker
              className={classes.date}
              control={control}
              error={!!errors.toDate}
              helperText={
                //@ts-ignore
                errors?.toDate?.message
              }
              id="to-date"
              label={t("profile:request_form.departure_date")}
              minDate={
                watchFromDate
                  ? watchFromDate.add(1, "day").toDate()
                  : new Date()
              }
              name="toDate"
              defaultValue={null}
              rules={{
                required: t("profile:request_form.departure_date_empty"),
                validate: (stringDate) => stringDate !== "",
              }}
            />
            {isPostBetaEnabled && (
              <Select
                name="visitorCount"
                value={numVisitors}
                onChange={(event) => setNumVisitors(Number(event.target.value))}
              >
                {guests}
              </Select>
            )}
          </div>
          <TextField
            id="text"
            className={classes.requestField}
            label={t("profile:request_form.request")}
            name="text"
            minRows={6}
            multiline
            fullWidth
            placeholder={t("profile:request_form.request_description")}
            error={!!errors.text}
            helperText={errors.text?.message || ""}
            inputRef={register({
              required: t("profile:request_form.request_description_empty"),
            })}
          />
          <CardActions className={classes.send}>
            <Button onClick={() => setIsRequesting(false)}>
              {t("global:cancel")}
            </Button>
            <Button type="submit" onClick={onSubmit}>
              {t("global:send")}
            </Button>
          </CardActions>
        </form>
      )}
    </>
  );
}