Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 2633 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 www 1
import {axios} from "../../../utils";
2
import React, { useEffect, useState } from "react";
3
import { useForm } from "react-hook-form";
4
import { connect } from "react-redux";
5
import styled from "styled-components";
6
import { addNotification } from "../../../redux/notification/notification.actions";
7
import FormErrorFeedback from "../../../shared/form-error-feedback/FormErrorFeedback";
8
import Spinner from "../../../shared/loading-spinner/Spinner";
9
 
10
const StyledSpinnerContainer = styled.div`
11
  position: absolute;
12
  left: 0;
13
  top: 0;
14
  width: 100%;
15
  height: 100%;
16
  background: rgba(255, 255, 255, 0.4);
17
  display: flex;
18
  justify-content: center;
19
  align-items: center;
20
  z-index: 300;
21
`;
22
 
23
const ChangePassword = (props) => {
24
  // redux destructuring
25
  const { addNotification } = props;
26
 
27
  const {
28
    register,
29
    handleSubmit,
30
    getValues,
31
    errors,
32
    reset,
33
    formState: { isSubmitSuccessful },
34
  } = useForm();
35
 
36
  // states
37
  const [loading, setLoading] = useState(false);
38
 
39
  // Error password message
40
  const [isErrorPassword, setIsErrorPassword] = useState(false);
41
  const [isErrorConfirmation, setIsErrorConfirmation] = useState(false);
42
 
43
  const handleOnSubmit = async (data) => {
44
    setLoading(true);
45
 
46
    let errorPassword = false;
47
 
48
    const validPassword = new RegExp('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$^x%x*-]).{6,16}$');
49
 
50
    // se verifica si la clave cumple la expresion regular
51
    if (!validPassword.test(data.password)) {
52
      setIsErrorPassword(true);
53
      setTimeout(() => {
54
        setIsErrorPassword(false);
55
      }, 10000);
56
      setLoading(false);
57
      errorPassword = true;
58
    }
59
 
60
    // se verifica si las dos claves son identicas
61
    if (data.password !== data.confirmation) {
62
      setIsErrorConfirmation(true);
63
      setTimeout(() => {
64
        setIsErrorConfirmation(false);
65
      }, 10000);
66
      setLoading(false);
67
      errorPassword = true;
68
    }
69
 
70
    if(!errorPassword){
71
      const formData = new FormData();
72
      Object.entries(data).map(([key, value]) => {
73
        formData.append(key, value);
74
      });
75
      await axios
76
        .post("/account-settings/password", formData)
77
        .then((response) => {
78
          const resData = response.data;
79
          if (resData.success) {
80
            addNotification({
81
              style: "success",
82
              msg: resData.data,
83
            });
84
          } else {
85
            if (typeof resData.data === "object") {
86
              resData.data;
87
              Object.entries(resData.data).map(([key, value]) => {
88
                setError(key, { type: "manual", message: value[0] });
89
              });
90
            } else {
91
              const errorMessage =
92
                typeof resData.data === "string"
93
                  ? resData.data
94
                  : "Ha ocurrido un error, Por favor intente mas tarde";
95
              addNotification({
96
                style: "danger",
97
                msg: errorMessage,
98
              });
99
            }
100
          }
101
        });
102
        setLoading(false);
103
    }
104
 
105
    errorPassword = false;
106
  };
107
 
108
  useEffect(() => {
109
    reset({ ...getValues });
110
  }, [isSubmitSuccessful]);
111
 
112
  return (
113
    <div
114
      className="acc-setting"
115
      style={{
116
        position: "relative",
117
      }}
118
    >
119
      <h3>Básica</h3>
120
      <form onSubmit={handleSubmit(handleOnSubmit)}>
121
        <div className="cp-field">
122
          <label htmlFor="password">Clave</label>
123
          <div className="cpp-fiel">
124
            <input
125
              type="password"
126
              name="password"
127
              minLength="6"
128
              maxLength="16"
129
              id="password"
130
              ref={register({
131
                required: "Por favor ingrese la contraseña",
132
              })}
133
              pattern="^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$^x%x*-]).{6,16}$"
134
              title="La clave debe contener entre 6 y 16 caracteres, incluida una letra mayúscula, un número y un carácter especial #?!@$^%*-"
135
            />
136
            <i className="fa fa-lock"></i>
137
          </div>
138
          { isErrorPassword && (
139
            <p className="text-danger">Disculpe, La clave debe contener entre 6 y 16 caracteres, incluida una letra mayúscula, un número y un carácter especial #?!@$^%*-</p>
140
          )}
141
          {<FormErrorFeedback>{errors?.password?.message}</FormErrorFeedback>}
142
        </div>
143
        <div className="cp-field">
144
          <label htmlFor="confirmation">Confirmación</label>
145
          <div className="cpp-fiel">
146
            <input
147
              type="password"
148
              name="confirmation"
149
              minLength="6"
150
              maxLength="16"
151
              id="confirmation"
152
              ref={register({
153
                required: "Por favor ingrese la contraseña",
154
                validate: (value) =>
155
                  value === getValues("password") ||
156
                  "La contraseña no coincide",
157
              })}
158
              pattern="^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$^x%x*-]).{6,16}$"
159
              title="La clave debe contener entre 6 y 16 caracteres, incluida una letra mayúscula, un número y un carácter especial #?!@$^%*-"
160
            />
161
            <i className="fa fa-lock"></i>
162
          </div>
163
          { isErrorConfirmation && (
164
            <p className="text-danger">Disculpe, las claves tienen que coincidir</p>
165
          )}
166
          {
167
            <FormErrorFeedback>
168
              {errors?.confirmation?.message}
169
            </FormErrorFeedback>
170
          }
171
        </div>
172
        <div className="save-stngs pd2">
173
          <ul>
174
            <li>
175
              <button type="submit" className="btn-save-basic">
176
                Guardar
177
              </button>
178
            </li>
179
          </ul>
180
        </div>
181
        {/* <!--save-stngs end--> */}
182
        {/* <?php echo $this->form()->closeTag($form); ?>	 */}
183
      </form>
184
      {loading && (
185
        <StyledSpinnerContainer>
186
          <Spinner></Spinner>
187
        </StyledSpinnerContainer>
188
      )}
189
    </div>
190
  );
191
};
192
 
193
// const mapStateToProps = (state) => ({
194
 
195
// })
196
 
197
const mapDispatchToProps = {
198
  addNotification: (notification) => addNotification(notification),
199
};
200
 
201
export default connect(null, mapDispatchToProps)(ChangePassword);