All files / app/features/auth/phone ChangePhone.tsx

0% Statements 0/55
0% Branches 0/24
0% Functions 0/15
0% Lines 0/54

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import "react-phone-number-input/style.css";
 
import { Typography, useMediaQuery, useTheme } from "@material-ui/core";
import Alert from "components/Alert";
import Button from "components/Button";
import StyledLink from "components/StyledLink";
import TextField from "components/TextField";
import { accountInfoQueryKey } from "features/queryKeys";
import { Empty } from "google-protobuf/google/protobuf/empty_pb";
import { RpcError } from "grpc-web";
import { AUTH } from "i18n/namespaces";
import luhn from "luhn";
import { Trans, useTranslation } from "next-i18next";
import { GetAccountInfoRes } from "proto/account_pb";
import { Controller, useForm } from "react-hook-form";
import PhoneInput, {
  formatPhoneNumberIntl,
  isValidPhoneNumber,
} from "react-phone-number-input";
import { useMutation, useQueryClient } from "react-query";
import { service } from "service";
 
import useChangeDetailsFormStyles from "../useChangeDetailsFormStyles";
 
export const validatePhoneCode = (code: string) =>
  code.length == 6 && luhn.validate(code);
 
interface ChangePhoneFormData {
  phone: string;
}
 
interface VerifyPhoneFormData {
  code: string;
}
 
type ChangePhoneProps = {
  accountInfo: GetAccountInfoRes.AsObject;
  className?: string;
};
 
export default function ChangePhone({
  className,
  accountInfo,
}: ChangePhoneProps) {
  const { t } = useTranslation([AUTH]);
  const formClasses = useChangeDetailsFormStyles();
  const theme = useTheme();
  const isMdOrWider = useMediaQuery(theme.breakpoints.up("md"));
  const queryClient = useQueryClient();
 
  const {
    handleSubmit: changeHandleSubmit,
    reset: resetChangeForm,
    control,
  } = useForm<ChangePhoneFormData>();
  const onChangeSubmit = changeHandleSubmit(({ phone }) => {
    changePhone({ phone });
  });
 
  const {
    error: changeError,
    isLoading: isChangeLoading,
    isSuccess: isChangeSuccess,
    mutate: changePhone,
    reset: resetChange,
  } = useMutation<Empty, RpcError, ChangePhoneFormData>(
    ({ phone }) => service.account.changePhone(phone),
    {
      onSuccess: () => {
        queryClient.invalidateQueries(accountInfoQueryKey);
        resetChangeForm();
        resetVerify();
        resetRemove();
      },
    }
  );
 
  const {
    handleSubmit: verifyHandleSubmit,
    register: verifyRegister,
    reset: resetVerifyForm,
    errors: verifyFormErrors,
  } = useForm<VerifyPhoneFormData>({ mode: "onBlur" });
  const onVerifySubmit = verifyHandleSubmit(({ code }) => {
    verifyPhone({ code });
  });
 
  const {
    error: verifyError,
    isLoading: isVerifyLoading,
    isSuccess: isVerifySuccess,
    mutate: verifyPhone,
    reset: resetVerify,
  } = useMutation<Empty, RpcError, VerifyPhoneFormData>(
    ({ code }) => service.account.verifyPhone(code),
    {
      onSuccess: () => {
        queryClient.invalidateQueries(accountInfoQueryKey);
        resetVerifyForm();
        resetChange();
        resetRemove();
      },
    }
  );
 
  const {
    error: removeError,
    isLoading: isRemoveLoading,
    isSuccess: isRemoveSuccess,
    mutate: removePhone,
    reset: resetRemove,
  } = useMutation<Empty, RpcError>(service.account.removePhone, {
    onSuccess: () => {
      queryClient.invalidateQueries(accountInfoQueryKey);
      resetChangeForm();
      resetVerifyForm();
      resetChange();
      resetVerify();
    },
  });
 
  return (
    <div className={className}>
      <Typography variant="h2">{t("auth:change_phone.title")}</Typography>
      {changeError && <Alert severity="error">{changeError.message}</Alert>}
      {verifyError && <Alert severity="error">{verifyError.message}</Alert>}
      {removeError && <Alert severity="error">{removeError.message}</Alert>}
      {isChangeSuccess && (
        <Alert severity="success">{t("auth:change_phone.add_success")}</Alert>
      )}
      {isVerifySuccess && (
        <Alert severity="success">
          {t("auth:change_phone.verify_success")}
        </Alert>
      )}
      {isRemoveSuccess && (
        <Alert severity="success">
          {t("auth:change_phone.remove_success")}
        </Alert>
      )}
      {!accountInfo.phone ? (
        !accountInfo.hasDonated ? (
          <Typography variant="body1">
            <Trans i18nKey="auth:change_phone.need_to_donate">
              You need to{" "}
              <StyledLink href="https://help.couchers.org/hc/couchersorg-help-center/articles/1715658357-how-to-write-a-request-that-gets-accepted">
                donate
              </StyledLink>
              before you can complete phone verification.
            </Trans>
          </Typography>
        ) : (
          <form className={formClasses.form} onSubmit={onChangeSubmit}>
            <Typography variant="body1">
              {t("auth:change_phone.no_phone_description")}
            </Typography>
            <Controller
              name="phone"
              control={control}
              rules={{
                validate: (value) => isValidPhoneNumber(value),
              }}
              render={({ onChange, value }) => (
                <PhoneInput
                  international
                  placeholder={t("auth:change_phone.phone_label")}
                  value={value}
                  onChange={onChange}
                  id="phone"
                />
              )}
            />
            <Button
              fullWidth={!isMdOrWider}
              loading={isChangeLoading}
              type="submit"
            >
              {t("auth:change_phone.add_button_text")}
            </Button>
          </form>
        )
      ) : (
        <>
          {!accountInfo.phoneVerified ? (
            <form className={formClasses.form} onSubmit={onVerifySubmit}>
              <Typography variant="body1">
                <Trans
                  t={t}
                  i18nKey="auth:change_phone.phone_not_verified_description"
                >
                  We sent you a code to{" "}
                  <b>{{ phone: formatPhoneNumberIntl(accountInfo.phone) }}</b>.
                  To verify your number, please enter the code below:
                </Trans>
              </Typography>
              <TextField
                id="code"
                inputRef={verifyRegister({
                  required: true,
                  validate: (code) =>
                    validatePhoneCode(code) ||
                    t("auth:change_phone.wrong_code"),
                })}
                helperText={verifyFormErrors?.code?.message ?? " "}
                error={!!verifyFormErrors?.code?.message}
                label={t("auth:change_phone.code_label")}
                name="code"
                fullWidth={!isMdOrWider}
              />
              <Button
                fullWidth={!isMdOrWider}
                loading={isVerifyLoading}
                type="submit"
              >
                {t("auth:change_phone.verify_button_text")}
              </Button>
            </form>
          ) : (
            <>
              <Typography variant="body1">
                <Trans
                  t={t}
                  i18nKey="auth:change_phone.remove_phone_description"
                >
                  Your phone number is currently{" "}
                  <b>{{ phone: formatPhoneNumberIntl(accountInfo.phone) }}</b>.
                  You can remove your phone number below, but you will loose
                  verification.
                </Trans>
              </Typography>
              <Button
                fullWidth={!isMdOrWider}
                loading={isRemoveLoading}
                onClick={() => removePhone()}
              >
                {t("auth:change_phone.remove_button_text")}
              </Button>
            </>
          )}
          <form className={formClasses.form} onSubmit={onChangeSubmit}>
            <Typography variant="body1">
              {t("auth:change_phone.change_to_different_description")}
            </Typography>
            <Controller
              name="phone"
              control={control}
              rules={{
                validate: (value) => isValidPhoneNumber(value),
              }}
              render={({ onChange, value }) => (
                <PhoneInput
                  countrySelectProps={{ unicodeFlags: true }}
                  international
                  placeholder={t("auth:change_phone.phone_label")}
                  value={value}
                  onChange={onChange}
                  id="phone"
                />
              )}
            />
            <Button
              fullWidth={!isMdOrWider}
              loading={isChangeLoading}
              type="submit"
            >
              {t("auth:change_phone.change_button_text")}
            </Button>
          </form>
        </>
      )}
    </div>
  );
}