Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 www 1
import React from "react";
2
import { useState, useEffect, useRef } from "react";
3
import { useForm } from "react-hook-form";
4
import styled from "styled-components";
5
import {axios} from "../../../../../utils";
6
import Spinner from "../../../../../shared/loading-spinner/Spinner";
7
import AddLocationModal from "./add-location-modal/AddLocationModal";
8
 
9
const StyledSpinnerContainer = styled.div`
10
  position: absolute;
11
  left: 0;
12
  top: 0;
13
  width: 100%;
14
  height: 100%;
15
  background: rgba(255, 255, 255, 0.4);
16
  display: flex;
17
  justify-content: center;
18
  align-items: center;
19
  z-index: 300;
20
`;
21
 
22
const Locations = (props) => {
23
  // props destructuring
24
  const { companyId, locations, addNotification } = props;
25
 
26
  // React hook form
27
  const {
28
    register,
29
    errors,
30
    handleSubmit,
31
    setValue,
32
    clearErrors,
33
    getValues,
34
    watch,
35
    setError,
36
  } = useForm();
37
 
38
  // states
39
  const [isModalOpen, setIsModalOpen] = useState(false);
40
  const [loading, setLoading] = useState(false);
41
  const [modalLoading, setModalLoading] = useState(false);
42
  const [settedLocations, setSettedLocations] = useState(locations);
43
  // refs
44
  const locationPostUrl = useRef(
45
    `/my-company/${companyId}/profile/location/add`
46
  );
47
  const isAddressEmpty = useRef(true);
48
  const addressKeys = useRef([
49
    "address1",
50
    "address2",
51
    "country",
52
    "state",
53
    "city1",
54
    "city2",
55
    "postal_code",
56
    "latitude",
57
    "longitude",
58
  ]);
59
 
60
  useEffect(() => {
61
    addressKeys.current.map((addressKey) => {
62
      register(addressKey);
63
    });
64
    register("formatted_address", {
65
      required: "por favor seleccione una ubicación correcta",
66
    });
67
  }, []);
68
 
69
  const handleModalOpen = (event) => {
70
    event && event.preventDefault();
71
    Object.entries(getValues()).map(([key, value]) => {
72
      setValue(key, "");
73
    });
74
    setIsModalOpen(!isModalOpen);
75
  };
76
 
77
  const handleAddNewLocation = () => {
78
    locationPostUrl.current = `/my-company/${companyId}/profile/location/add`;
79
    handleModalOpen();
80
  };
81
 
82
  const handleDelete = async (delete_link) => {
83
    setLoading(true);
84
    await axios.post(delete_link).then((response) => {
85
      const resData = response.data;
86
      if (resData.success) {
87
        setSettedLocations(resData.data);
88
      } else {
89
        // alert error
90
      }
91
    });
92
    setLoading(false);
93
  };
94
 
95
  const handleEdit = async (linkEdit) => {
96
    handleModalOpen();
97
    locationPostUrl.current = linkEdit;
98
    setModalLoading(true);
99
     (linkEdit);
100
    await axios.get(linkEdit).then((response) => {
101
      const resData = response.data;
102
       (resData);
103
      if (resData.success) {
104
        Object.entries(resData.data).map(async ([key, value]) => {
105
          if (value && value !== "n") {
106
            setValue(key, value);
107
          }
108
        });
109
        isAddressEmpty.current = false;
110
      }
111
    });
112
    setModalLoading(false);
113
  };
114
 
115
  const getAddressHandler = (addresObject) => {
116
    addressKeys.current.map((addressKey) => {
117
      setValue(addressKey, "");
118
    });
119
    const { address_components } = addresObject;
120
    if (address_components) {
121
      address_components.map((address_component) => {
122
        const address_component_name = address_component.long_name;
123
        const address_component_type = address_component.types[0];
124
        switch (address_component_type) {
125
          case "route":
126
            setValue("address1", address_component_name);
127
            break;
128
          case "sublocality":
129
            setValue("address2", address_component_name);
130
            break;
131
          case "locality":
132
            setValue("city1", address_component_name);
133
            break;
134
          case "administrative_area_level_2":
135
            setValue("city2", address_component_name);
136
            break;
137
          case "administrative_area_level_1":
138
            setValue("state", address_component_name);
139
            break;
140
          case "country":
141
            setValue("country", address_component_name);
142
            break;
143
          case "postal_code":
144
            setValue("postal_code", address_component_name);
145
            break;
146
          case "geometry":
147
            setValue("latitude", address_component.latitude);
148
            setValue("longitude", address_component.longitude);
149
            break;
150
          default:
151
            break;
152
        }
153
      });
154
      isAddressEmpty.current = false;
155
      clearErrors("formatted_address");
156
    } else {
157
      isAddressEmpty.current = true;
158
    }
159
    setValue("formatted_address", addresObject.formatted_address);
160
  };
161
 
162
  const onSubmitHandler = async (data) => {
163
    setModalLoading(true);
164
    const formData = new FormData();
165
    Object.entries(data).map(([key, value]) => {
166
      if (value) {
167
        formData.append(key, value);
168
      }
169
    });
170
    await axios.post(locationPostUrl.current, formData).then((response) => {
171
      const resData = response.data;
172
       (resData);
173
      if (resData.success) {
174
        setSettedLocations(resData.data);
175
        handleModalOpen();
176
      } else {
177
        const resError = resData.data;
178
        if (resError.constructor.name === "Object") {
179
          Object.entries(resError).map(([key, value]) => {
180
            if (key in getValues()) {
181
              setError(key, {
182
                type: "manual",
183
                message: Array.isArray(value) ? value[0] : value,
184
              });
185
            }
186
          });
187
        } else {
188
          addNotification({
189
            style: "danger",
190
            msg: resError,
191
          });
192
        }
193
      }
194
    });
195
    setModalLoading(false);
196
  };
197
 
198
  return (
199
    <React.Fragment>
200
      <div
201
        className="user-profile-extended-ov st2"
202
        style={{ position: "relative" }}
203
      >
204
        <h3>
205
          Ubicaciones
206
          <a
207
            href="#"
208
            title=""
209
            className="btn-location-add"
210
            onClick={(e) => {
211
              e.preventDefault();
212
              handleAddNewLocation();
213
            }}
214
          >
215
            <i className="fa fa-plus-square"></i>
216
          </a>
217
        </h3>
218
        <span id="locations-records">
219
          {settedLocations.map(
220
            (
221
              { country, formatted_address, is_main, link_delete, link_edit },
222
              index
223
            ) => (
224
              <React.Fragment key={index}>
225
                {index >= 1 ? <hr /> : ""}
226
                <div>
227
                  {/* <?php echo $location['formatted_address']   ?><?php echo $location['is_main'] == 'y' ? ' (LABEL_MAIN_LOCATION) ' : ''?> */}
228
                  {`${formatted_address} ${
229
                    is_main === "y" ? "(Principal)" : ""
230
                  }`}
231
                  <div style={{ marginLeft: "5px", display: "inline" }}>
232
                    <a
233
                      href="#"
234
                      title=""
235
                      onClick={(e) => {
236
                        e.preventDefault();
237
                        handleEdit(link_edit);
238
                      }}
239
                      className="btn-location-edit"
240
                    >
241
                      <i className="fa fa-pencil"></i>
242
                    </a>
243
                    &nbsp;
244
                    <a
245
                      href="#"
246
                      title=""
247
                      onClick={(e) => {
248
                        e.preventDefault();
249
                        handleDelete(link_delete);
250
                      }}
251
                      className="btn-location-delete"
252
                    >
253
                      <i className="fa fa-trash"></i>
254
                    </a>
255
                  </div>
256
                </div>
257
              </React.Fragment>
258
            )
259
          )}
260
        </span>
261
        {loading && (
262
          <StyledSpinnerContainer>
263
            <Spinner />
264
          </StyledSpinnerContainer>
265
        )}
266
      </div>
267
      <AddLocationModal
268
        isModalOpen={isModalOpen}
269
        handleModalOpen={handleModalOpen}
270
        handleSubmit={handleSubmit}
271
        onSubmitHandler={onSubmitHandler}
272
        watch={watch}
273
        getAddressHandler={getAddressHandler}
274
        errors={errors}
275
        modalLoading={modalLoading}
276
        register={register}
277
      />
278
    </React.Fragment>
279
  );
280
};
281
 
282
export default Locations;