All files / src/hooks/common useAccount.tsx

80% Statements 28/35
57.14% Branches 12/21
45.45% Functions 5/11
82.35% Lines 28/34

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                                                                                                              9x 1904x   1904x 1904x 1904x                                                                                 1904x 1904x 1904x   1904x 2x     1904x                 1904x   1904x               1904x 468x 180x                               1904x   1904x 2x 2x       2x                                             2x                   2x 2x 2x 2x           1904x                         9x                            
import React from "react";
// utils
import { matchIsValidTel } from "mui-tel-input";
// form
import { yupResolver } from "@hookform/resolvers/yup";
import { SubmitHandler, useForm } from "react-hook-form";
import * as Yup from "yup";
import { VALIDATION_MESSAGES } from "@validation/messages";
// services
import { customInstance } from "@services/api";
import { useGetUser } from "@services/api/onboarding/user";
import { useMutation, useQueryClient } from "react-query";
 
// localization
import { namespaces } from "localization/resources/i18n.constants";
import { useTranslation } from "react-i18next";
// redux
import { updatePartialUser } from "@redux/slices/auth/auth";
// components
import { showMessage } from "@common/Toast/ShowToast";
// utils
import {
  MAXIMUM_REQUIRED_AGE,
  MINIMUM_REQUIRED_AGE,
} from "@constants/constants";
import { QKEY_GET_MERCHANT_BY_ID } from "@constants/queryKeys";
import { useChangeProfileAvatar } from "@hooks/upload-api/useChangeProfileAvatar";
import {
  convertPhoneNumber,
  formatInUTCMoment,
  toISODateString,
} from "@utils/date.helpers";
import { getServicePhoneNumber } from "@utils/helpers";
import { PLATFORM_TIMEZONE } from "@utils/timezones";
import { subYears } from "date-fns";
import { useDispatch } from "react-redux";
import { STATE_REGEX, TEXT_ALPHABETIC_REGEX } from "@validation/regex";
import useGetCurrentMerchantId from "./useGetCurrentMerchantId";
 
type IFormInputs = {
  firstName: string;
  lastName: string;
  email: string;
  pendingEmail: string;
  phone: string;
  address: string;
  date: number | Date | null;
  occupation: string;
  language: string;
  employer: string;
  currency: string;
  timezone: string;
  emailStatus?: string;
};
 
export const useAccount = () => {
  const dispatch = useDispatch();
 
  const { handleChangeStatus, updateUserImage } = useChangeProfileAvatar();
  const { merchantId } = useGetCurrentMerchantId();
  const schema = Yup.object().shape({
    firstName: Yup.string().required(VALIDATION_MESSAGES.REQUIRED),
    lastName: Yup.string().required(VALIDATION_MESSAGES.REQUIRED),
    email: Yup.string()
      .email(VALIDATION_MESSAGES.INVALID_EMAIL)
      .required(VALIDATION_MESSAGES.REQUIRED)
      .matches(
        /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,
        VALIDATION_MESSAGES.INVALID_EMAIL,
      ),
    phone: Yup.string().when({
      is: (exists: string) =>
        Boolean(exists && exists !== "+1" && dirtyFields.phone),
      then: (schema) =>
        schema.test(
          "is-valid-number",
          VALIDATION_MESSAGES.INVALID_PHONE,
          function (value) {
            const phoneNumber = value as string;
            return matchIsValidTel(phoneNumber);
          },
        ),
    }),
    address: Yup.string(),
    date: Yup.date()
      .typeError(VALIDATION_MESSAGES.INVALID_DATE_POLITE)
      .nullable()
      .min(subYears(new Date(), MAXIMUM_REQUIRED_AGE), "Must be 100 or less")
      .max(subYears(new Date(), MINIMUM_REQUIRED_AGE), `Must be 18 or older`),
 
    state: Yup.string().matches(STATE_REGEX, "Please enter a valid state"),
    occupation: Yup.string().matches(
      TEXT_ALPHABETIC_REGEX,
      `Please enter a valid job title`,
    ),
    employer: Yup.string().matches(
      TEXT_ALPHABETIC_REGEX,
      "Please enter a valid employer",
    ),
  });
 
  const { data: userData } = useGetUser();
  const queryClient = useQueryClient();
  const { i18n } = useTranslation(namespaces.pages.settings);
 
  const changeLanguage = (language: string) => {
    i18n.changeLanguage(language);
  };
 
  const methods = useForm<IFormInputs>({
    resolver: yupResolver(schema),
    defaultValues: initialValues,
  });
  const {
    watch,
    control,
    reset,
    formState: { dirtyFields, isDirty },
  } = methods;
 
  const updateUserData = useMutation((data: any) => {
    return customInstance({
      url: `/users/${userData.accID}`,
      method: "PATCH",
      data,
    });
  });
 
  React.useEffect(() => {
    if (userData) {
      reset({
        email: userData.email,
        emailStatus: userData.emailStatus,
        firstName: userData.firstName,
        lastName: userData.lastName,
        phone: getServicePhoneNumber(userData?.phoneNumber) ?? "+1",
        date: (formatInUTCMoment(userData?.dateOfBirth) || null) as any,
        employer: userData.employer,
        occupation: userData.occupation,
        language: userData.language || "eng",
        timezone: PLATFORM_TIMEZONE.toLowerCase(),
        currency: userData.currency || "usd",
      });
    }
  }, [userData, userData?.pendingEmail]);
 
  const removeImage = () => updateUserImage(null);
 
  const onSubmit: SubmitHandler<IFormInputs> = (updatedData) => {
    changeLanguage(updatedData.language);
    const dateOfBirth = updatedData.date
      ? toISODateString(watch("date") as Date | string)
      : null;
 
    updateUserData.mutate(
      {
        firstName: updatedData.firstName,
        lastName: updatedData.lastName,
        ...(userData?.email !== updatedData.email && {
          email: updatedData?.email,
        }),
        phoneNumber:
          updatedData.phone && updatedData.phone.length > 0
            ? convertPhoneNumber(updatedData.phone)
            : null,
        dateOfBirth,
        occupation: updatedData.occupation,
        employer: updatedData.employer,
        language: updatedData.language.toLowerCase(),
        timezone: updatedData.timezone.toLowerCase(),
        currency: updatedData.currency,
      },
      {
        onError: () => {
          showMessage("Error", "Invalid Inputs, please verify you data");
        },
        onSuccess: () => {
          dispatch(
            updatePartialUser({
              globalName: {
                firstName: updatedData.firstName,
                lastName: updatedData.lastName,
                phoneNumber: updatedData.phone,
              },
              timezone: updatedData.timezone,
            }),
          );
          reset(updatedData);
          queryClient.invalidateQueries("user");
          queryClient.invalidateQueries([QKEY_GET_MERCHANT_BY_ID, merchantId]);
          showMessage("Success", "Info has been edited successfully");
        },
      },
    );
  };
 
  return {
    methods,
    onSubmit,
    handleChangeStatus,
    control,
    defaultValues: initialValues,
    isLoading: updateUserData.isLoading,
    isDirty,
    removeImage,
    userData,
  };
};
 
const initialValues = {
  firstName: "",
  lastName: "",
  email: "",
  pendingEmail: "",
  phone: "",
  address: "",
  date: undefined,
  employer: "",
  occupation: "",
  currency: "usd",
  language: "eng",
  timezone: "",
};