Blame view

components/signup/Signup.js 13 KB
jaymehta committed
1
import React, { useState, useRef, useEffect } from "react";
2 3 4 5 6
import { Formik } from "formik";
import Link from "next/link";
import { Fragment } from "react";
import { Button, Form } from "react-bootstrap";
import * as Yup from "yup";
jay committed
7 8 9
import { renderImage } from "../../services/imageHandling";
import Image from "next/image";
import { useRouter } from "next/router";
jay committed
10 11 12 13 14 15
import axios from "axios";
import { useDispatch } from "react-redux";
import { registerUser } from "../../redux/actions/userActions";
import { toast } from "react-toastify";
import OTPInput from "../common-components/OTPInput";
import { finishVendorOtpVerification } from "../../redux/actions/vendorActions";
jay committed
16
import { signIn } from "next-auth/react";
.  
jaymehta committed
17
import { Loader } from "react-bootstrap-typeahead";
18

jay committed
19
const Signup = props => {
jaymehta committed
20
  console.log("props.type", props.type);
jay committed
21
  const [otp, setOtp] = useState(new Array(4).fill(""));
jay committed
22 23
  const [isOtpSent, setOtpSent] = useState(false);
  const [otpVerified, setOtpVerified] = useState(false);
jay committed
24 25
  const [loading, setLoading] = useState();
  const dispatch = useDispatch();
jaymehta committed
26
  const router = useRouter()
jay committed
27 28 29 30 31 32 33 34
  const otpValue = useRef();
  const changeOtpRef = value => {
    console.log(otpValue);
    if (otpValue.current?.length > 0) {
      otpValue.current = [...otpValue.current, value];
    } else {
      otpValue.current = [value];
    }
jay committed
35
  };
36

jay committed
37
  const signupValidationSchema = Yup.object().shape({
jay committed
38
    fullname: Yup.string().required("Full name is required"),
jay committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    email: Yup.string().required("Email Id is Required").email("Please Enter An Valid Email Id"),
    password: Yup.string().required("Password is Required").min(6, "Password must be minimum 6 characters"),
    confirmPassword: Yup.string()
      .required("Confirm Password is Required")
      .oneOf([Yup.ref("password"), null], "Passwords must match"),
    countryCode: Yup.string().required("Country Code is Required"),
    mobile: Yup.string()
      .required("Mobile Number is Required")
      .matches(/^[0-9\s]+$/, "Please Enter Correct Mobile No."),
    termsConditions: Yup.bool().oneOf([true], "Please Accept Terms & Conditions"),
    otp: Yup.string().when("isOtpSent", {
      is: true,
      then: Yup.string()
        .required("Otp is Required")
        .matches(/^[0-9\s]+$/, "Please Enter Correct OTP")
    })
  });
56

jay committed
57 58 59 60 61 62 63 64 65
  // Initial errors for required fields
  const initialErrors = {
    fullname: "Full Name is required",
    email: "Email is required",
    password: "Password is required",
    confirmPassword: "Confirm Password is required",
    countryCode: "Country Code is Required",
    mobile: "Mobile Number is Required"
  };
66

jay committed
67 68 69
  const handleSendOtp = values => {
    setOtpSent(true);
  };
70

jay committed
71 72 73
  const handleVerifyOtp = values => {
    setOtpVerified(true);
    if (props.type == "user") {
74
    }
jay committed
75
  };
76

jay committed
77

jay committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
  return (
    <Fragment>
      <div className="contaier-fluid login-banner-image">
        {(props?.type == "user" || (props?.type == "vendor" && !otpVerified)) && (
          <div className="row">
            <div className="col-11 col-lg-4 login-div signupdiv">
              <div className="">
                <h2>{props.type == "vendor" ? "Vendor Signup" : "Signup to get more out of the platform"}</h2>
                <div className="form-container">
                  <Formik
                    initialValues={{
                      fullname: "",
                      email: "",
                      password: "",
                      confirmPassword: "",
                      countryCode: "",
                      mobile: "",
jay committed
95 96
                      termsConditions: false
                      //   otp: Otp ? Otp : ""
jay committed
97 98 99 100
                    }}
                    // initialErrors={initialErrors}
                    validationSchema={signupValidationSchema}
                    enableReinitialize={true}
jay committed
101 102 103 104 105 106 107 108 109 110 111
                    // onSubmit={e => {
                    //     // e.preventDefault();
                    //     console.log("signup values", e);
                    //     setOtpSent(true)
                    //     if (!isOtpSent) {
                    //     //   handleSendOtp(values);
                    //     }
                    //     if (isOtpSent) {
                    //     //   handleVerifyOtp(values);
                    //     }
                    //   }}
jay committed
112 113 114
                  >
                    {({ values, errors, touched, handleChange, handleBlur, handleSubmit, isValid, isSubmitting }) => (
                      <Form
jay committed
115 116 117 118 119
                        onSubmit={async e => {
                          if (!isOtpSent) {
                            setLoading(true);
                            e.preventDefault();
                            console.log("values", values);
jaymehta committed
120 121 122 123 124 125 126
                            let user;
                            if (props.type == "vendor") {
                              user = await dispatch(registerUser({ ...values, role: "vendor" }));
                            } 
                            if (props.type == "user") {
                              user = await dispatch(registerUser({ ...values, role: "endUser" }));
                            }
jay committed
127 128 129 130 131 132 133
                            console.log("response", user);
                            if (user?.data?.status == "fail") {
                              toast.error(user?.data.message);
                              setLoading(false);
                              return;
                            }
                            setOtpSent(true);
.  
jaymehta committed
134
                            setLoading(false);
jay committed
135 136
                          } else {
                            e.preventDefault();
jay committed
137
                            const oneTimePassword = otp.join("");
.  
jaymehta committed
138
                            setLoading(false);
jay committed
139
                            const otpRes = await finishVendorOtpVerification({ email: values.email, oneTimePassword });
jay committed
140
                            console.log("otpRes", otpRes);
jay committed
141
                            if (otpRes.data.ok) {
jay committed
142 143 144 145 146
                              const result = await signIn("credentials", {
                                email: values.email,
                                password: values.password,
                                redirect: false
                              });
.  
jaymehta committed
147
                              setLoading(false);
jay committed
148
                              console.log("result", result);
jaymehta committed
149 150 151 152 153 154
                              if (props.type == "vendor") {
                                router.push("/vendor/business-details");
                              } 
                              if (props.type == "user") {
                                router.push("/signup/user/thankyou");
                              }
jay committed
155 156
                              //   toast.success("User registered successflly");
                            } else if (!otpRes.data.ok) {
.  
jaymehta committed
157
                              setLoading(false);
jay committed
158 159
                              setOtp(new Array(4).fill(""));
                              toast.error("Invalid OTP, please try again.");
jay committed
160 161
                            }
                          }
jay committed
162 163 164
                        }}
                      >
                        <div className="input-group">
jay committed
165
                          <label>Full Name</label>
jay committed
166
                          <input type="text" name="fullname" onChange={handleChange} onBlur={handleBlur} value={values.fullname} placeholder="Your name" />
jay committed
167
                          {errors.fullname && touched.fullname && <span className="form-error">{errors.fullname}</span>}
168
                        </div>
jay committed
169 170
                        <div className="input-group">
                          <label>Email Id</label>
jay committed
171
                          <input type="text" name="email" onChange={handleChange} onBlur={handleBlur} value={values.email} placeholder="yourname@example.com" />
jay committed
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
                          {errors.email && touched.email && <span className="form-error">{errors.email}</span>}
                        </div>
                        <div className="input-group">
                          <label>Password</label>
                          <input type="password" name="password" onChange={handleChange} onBlur={handleBlur} value={values.password} placeholder="Enter password" />
                          {errors.password && touched.password && <span className="form-error">{errors.password}</span>}
                        </div>
                        <div className="input-group">
                          <label>Confirm Password</label>
                          <input
                            type="password"
                            name="confirmPassword"
                            onChange={handleChange}
                            onBlur={handleBlur}
                            value={values.confirmPassword}
                            placeholder="Enter password"
                          />
                          {errors.confirmPassword && touched.confirmPassword && <span className="form-error">{errors.confirmPassword}</span>}
                        </div>
                        <div className="input-group">
                          <label>Mobile No.</label>
                          <div className="contact-number">
                            <select
                              id="countryCode"
                              name="countryCode"
                              onChange={handleChange}
                              onBlur={e => {
                                handleBlur(e);
                                setCountryCode(e.target.value);
                              }}
                              style={{ width: "80px" }}
                            >
                              <option value="+91">+91</option>
                              <option value="+44">+44</option>
                            </select>
                            <input
                              type="text"
                              name="mobile"
                              onChange={handleChange}
                              onBlur={handleBlur}
                              value={values.mobile}
                              placeholder="#@$!%@#"
                              style={{ flex: "0 100%" }}
                            />
                          </div>
                          {errors.mobile && touched.mobile && <span className="form-error">{errors.mobile}</span>}
                        </div>
jay committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
                        <div className="input-group mb-3">
                          <label className="check-container mb-0 pt-1" htmlFor="termsConditions">
                            <input
                              type="checkbox"
                              id="termsConditions"
                              name="termsConditions"
                              className="check-box me-2"
                              checked={values.termsConditions}
                              onChange={handleChange}
                              onBlur={handleBlur}
                            />
                            <span className="checkmark"></span>I Agree to the <Link href="">terms & conditions*</Link>
                          </label>
                          <br />

                          {errors.termsConditions && touched.termsConditions && <span className="form-error">{errors.termsConditions}</span>}
                        </div>
jay committed
236 237 238 239 240 241 242
                        {isOtpSent && (
                          <>
                            <div className="input-group">
                              <label>
                                OTP <span style={{ marginLeft: "190px" }}>00:30</span>
                              </label>
                              <div className="otp-input">
jay committed
243
                                <OTPInput setOtp={setOtp} otp={otp} />
jay committed
244 245
                              </div>
                              {errors.otp && touched.otp && <span className="form-error">{errors.otp}</span>}
246
                            </div>
jay committed
247 248 249 250 251 252 253 254 255
                            <div>
                              <p>4 digit OTP is been sent on your email address.</p>
                              <div className="d-flex align-items-center mb-4">
                                <p className="mb-0 me-5">Didnt Receive Yet?</p>
                                <div className="d-flex resend-otp">
                                  <span className="image-container me-2">
                                    <Image src={renderImage("/images/login/icon-resend.png")} layout="fill" className="image" />
                                  </span>
                                  <p className="mb-0">Resend</p>
256
                                </div>
jay committed
257
                              </div>
258
                            </div>
jay committed
259 260 261
                          </>
                        )}
                        <div className="input-group mb-0">
.  
jaymehta committed
262
                          <Button type="submit" className="btn btn-primary btn-submit" disabled={(!values.termsConditions && !isValid) || loading}>
jaymehta committed
263
                            {loading ? <Loader /> : `${isOtpSent ? "Verify OTP" : "Sign Up Now"}`}
jay committed
264
                          </Button>
265
                        </div>
jay committed
266 267 268 269 270 271 272 273 274 275 276 277
                      </Form>
                    )}
                  </Formik>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </Fragment>
  );
};
278

jay committed
279
export default Signup;