Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 3177 | Rev 3872 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
3730 stevensc 1
/* eslint-disable react/prop-types */
1 www 2
import React from "react";
3
import { useState, useEffect } from "react";
4
import { Button, Modal } from "react-bootstrap";
5
import { useForm } from "react-hook-form";
6
import styled from "styled-components";
3177 stevensc 7
import { axios } from "../../../../../utils";
1 www 8
import Spinner from "../../../../loading-spinner/Spinner";
9
import DropzoneComponent from "../../../../dropzone/DropzoneComponent";
10
import { profileTypes } from "../../../Profile.types";
11
import FormErrorFeedback from "../../../../form-error-feedback/FormErrorFeedback";
3730 stevensc 12
import { addNotification } from "../../../../../redux/notification/notification.actions";
1 www 13
 
14
const StyledSpinnerContainer = styled.div`
15
  position: absolute;
16
  left: 0;
17
  top: 0;
18
  width: 100%;
19
  height: 100%;
20
  background: rgba(255, 255, 255, 0.4);
21
  display: flex;
22
  justify-content: center;
23
  align-items: center;
24
  z-index: 300;
25
`;
26
 
3730 stevensc 27
const ProfileImg = ({
28
  entityId = '',
29
  profileId = '',
30
  image = '',
31
  imageProfileCover = '',
32
  profileType = ''
33
}) => {
1 www 34
 
35
  const {
36
    register,
37
    errors,
38
    handleSubmit,
39
    setValue,
40
    clearErrors,
41
    setError,
3730 stevensc 42
    getValues
1 www 43
  } = useForm();
44
 
45
  // states
46
  const [isModalOpen, setIsModalOpen] = useState(false);
47
  const [loading, setLoading] = useState(false);
48
  const [profileImg, setProfileImg] = useState(() => {
49
    switch (profileType) {
50
      case profileTypes.USER:
51
        return {
3177 stevensc 52
          path: `/storage/type/user-profile/code/${entityId}/${image && `filename/${image}`
53
            }`,
1 www 54
          uid: Date.now(),
55
        };
56
      case profileTypes.COMPANY:
57
        return {
3730 stevensc 58
          path: `/storage/type/company/code/${entityId}/${image && `filename/${image}`}`,
1 www 59
          uid: Date.now(),
3730 stevensc 60
        }
1 www 61
      default:
62
        break;
63
    }
64
  });
65
 
66
  const handleModalOpen = (event) => {
67
    event && event.preventDefault();
68
    setIsModalOpen(!isModalOpen);
69
  };
70
 
71
  const onUploadedHandler = (files) => {
72
    setValue("image", files);
73
    clearErrors("image");
74
  };
75
 
76
  const dropZoneRender = () => (
77
    <DropzoneComponent
78
      modalType="IMAGE"
79
      onUploaded={onUploadedHandler}
80
      recomendationText={`Imágenes recomendadas de ${imageProfileCover}`}
81
    />
82
  );
83
 
84
  useEffect(() => {
85
    register("image", {
86
      required: { value: "true", message: "El campo es requerido" },
87
    });
88
    // setSettedCover(false);
89
  }, []);
90
 
91
  const onSubmitHandler = async (data) => {
92
    let postPath = "";
93
    switch (profileType) {
94
      case profileTypes.USER:
95
        postPath = `/profile/my-profiles/image/${profileId}/operation/upload`;
96
        break;
97
      case profileTypes.COMPANY:
98
        postPath = `/my-company/${profileId}/profile/image/upload`;
99
        break;
100
      default:
101
        break;
102
    }
3177 stevensc 103
    ("called");
1 www 104
    setLoading(true);
105
    const formData = new FormData();
106
    Object.entries(data).map(([key, value]) => {
107
      formData.append(key, value);
108
    });
109
    await axios.post(postPath, formData).then((response) => {
110
      const resData = response.data;
3177 stevensc 111
      (resData);
1 www 112
      if (resData.success) {
113
        setLoading(false);
114
        const newCoverImg = {
115
          path: resData.data.profile,
116
          uid: Date.now(),
117
        };
3177 stevensc 118
        if (resData.data.update_navbar) sessionStorage.setItem('user_session_image', resData.data.user)
1 www 119
        setProfileImg(newCoverImg);
120
        setValue("image", "");
121
        handleModalOpen();
122
      } else {
123
        const resError = resData.data;
124
        if (resError.constructor.name === "Object") {
125
          Object.entries(resError).map(([key, value]) => {
126
            if (key in getValues()) {
127
              setError(key, {
128
                type: "manual",
129
                message: Array.isArray(value) ? value[0] : value,
130
              });
131
            }
132
          });
133
        } else {
134
          addNotification({
135
            style: "danger",
136
            msg: resError,
137
          });
138
        }
139
      }
140
    });
141
    setLoading(false);
142
  };
143
 
144
  return (
145
    <React.Fragment>
146
      <div className="user-pro-img">
147
        <img
148
          id="user-profile-img"
149
          src={`${profileImg.path}?${profileImg.uid}`}
150
          alt=""
151
        />
152
        <div className="add-dp" id="OpenImgUpload">
153
          <a href="#" className="btn-image-open" onClick={handleModalOpen}>
154
            <i className="fas fa-camera"></i>
155
          </a>
156
        </div>
157
      </div>
158
 
159
      {/* modal */}
160
      <Modal
161
        show={isModalOpen}
162
        onHide={handleModalOpen}
163
        style={{ overflowY: "scroll" }}
164
      >
165
        <Modal.Header closeButton>
166
          <Modal.Title>Portada</Modal.Title>
167
        </Modal.Header>
168
        <form
169
          encType="multipart/form-data"
170
          onSubmit={handleSubmit(onSubmitHandler)}
171
        >
172
          <Modal.Body>
173
            {dropZoneRender()}
174
            {errors.image && (
175
              <FormErrorFeedback>{errors.image.message}</FormErrorFeedback>
176
            )}
177
          </Modal.Body>
178
          <Modal.Footer>
179
            <Button type="submit">Enviar</Button>
180
            <Button variant="danger" onClick={handleModalOpen}>
3148 stevensc 181
              Cancelar
1 www 182
            </Button>
183
          </Modal.Footer>
184
        </form>
185
        {loading && (
186
          <StyledSpinnerContainer>
187
            <Spinner />
188
          </StyledSpinnerContainer>
189
        )}
190
      </Modal>
191
    </React.Fragment>
192
  );
193
};
194
 
195
export default ProfileImg;