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 { Button, Modal } from "react-bootstrap";
4
import { useForm } from "react-hook-form";
5
import styled from "styled-components";
6
import {axios} from "../../../../../../utils";
7
import FormErrorFeedback from "../../../../../../shared/form-error-feedback/FormErrorFeedback";
8
import Spinner from "../../../../../../shared/loading-spinner/Spinner";
9
import UbicationInput from "../../../../../../shared/ubication-input/UbicationInput";
10
 
11
const StyledSpinnerContainer = styled.div`
12
  position: absolute;
13
  left: 0;
14
  top: 0;
15
  width: 100%;
16
  height: 100%;
17
  background: rgba(255, 255, 255, 0.4);
18
  display: flex;
19
  justify-content: center;
20
  align-items: center;
21
  z-index: 300;
22
`;
23
 
24
const AddJobModal = (props) => {
25
  // props destructuring
26
  const {
27
    show,
28
    onHide,
29
    companyId,
30
    fetchJobs,
31
    addNotification,
32
    employmentTypes,
33
    jobCategories,
34
  } = props;
35
 
36
  // React hook form
37
  const {
38
    register,
39
    handleSubmit,
40
    errors,
41
    getValues,
42
    setError,
43
    setValue,
44
    watch,
45
    clearErrors,
46
  } = useForm();
47
 
48
  // states
49
  const wrapperRef = useRef();
50
  const [loading, setLoading] = useState(false);
51
  const [state, setState] = useState({ date: null, isOpen: false });
52
  const [settedAddress, setSettedAddress] = useState("");
53
  // refs
54
  const isAddressEmpty = useRef(true);
55
  const addressKeys = useRef([
56
    "address1",
57
    "address2",
58
    "country",
59
    "state",
60
    "city1",
61
    "city2",
62
    "postal_code",
63
    "latitude",
64
    "longitude",
65
  ]);
66
 
67
  useEffect(() => {
68
    addressKeys.current.map((addressKey) => {
69
      register(addressKey);
70
    });
71
    register("formatted_address", {
72
      required: "por favor seleccione una ubicación correcta",
73
    });
74
  }, []);
75
 
76
  const getAddressHandler = (addresObject) => {
77
    addressKeys.current.map((addressKey) => {
78
      setValue(addressKey, "");
79
    });
80
    const { address_components } = addresObject;
81
    if (address_components) {
82
      address_components.map((address_component) => {
83
        const address_component_name = address_component.long_name;
84
        const address_component_type = address_component.types[0];
85
        switch (address_component_type) {
86
          case "route":
87
            setValue("address1", address_component_name);
88
            break;
89
          case "sublocality":
90
            setValue("address2", address_component_name);
91
            break;
92
          case "locality":
93
            setValue("city1", address_component_name);
94
            break;
95
          case "administrative_area_level_2":
96
            setValue("city2", address_component_name);
97
            break;
98
          case "administrative_area_level_1":
99
            setValue("state", address_component_name);
100
            break;
101
          case "country":
102
            setValue("country", address_component_name);
103
            break;
104
          case "postal_code":
105
            setValue("postal_code", address_component_name);
106
            break;
107
          case "geometry":
108
            setValue("latitude", address_component.latitude);
109
            setValue("longitude", address_component.longitude);
110
            break;
111
          default:
112
            break;
113
        }
114
      });
115
      isAddressEmpty.current = false;
116
      clearErrors("formatted_address");
117
    } else {
118
      isAddressEmpty.current = true;
119
    }
120
    setValue("formatted_address", addresObject.formatted_address);
121
  };
122
 
123
  const onSubmitHandler = async (data) => {
124
     (data);
125
    setLoading(true);
126
    const formData = new FormData();
127
    Object.entries(data).map(([key, value]) => {
128
      formData.append(key, value);
129
    });
130
    await axios
131
      .post(`/my-company/${companyId}/job/add`, formData)
132
      .then((response) => {
133
        const resData = response.data;
134
         (resData);
135
        if (resData.success) {
136
          fetchJobs();
137
          onHide();
138
        } else {
139
          const resError = resData.data;
140
          if (resError.constructor.name === "Object") {
141
            Object.entries(resError).map(([key, value]) => {
142
              if (key in getValues()) {
143
                setError(key, {
144
                  type: "manual",
145
                  message: Array.isArray(value) ? value[0] : value,
146
                });
147
              }
148
            });
149
          } else {
150
            addNotification({
151
              style: "danger",
152
              msg: resError,
153
            });
154
          }
155
        }
156
      });
157
    setLoading(false);
158
  };
159
  return (
160
    <Modal show={show} onHide={onHide}>
161
      <Modal.Header closeButton>
162
        <Modal.Title id="contained-modal-title-vcenter">
163
          Nuevo Empleo
164
        </Modal.Title>
165
      </Modal.Header>
166
      <form onSubmit={handleSubmit(onSubmitHandler)}>
167
        <Modal.Body>
168
          <div style={{ position: "relative" }}>
169
            <div className="form-group">
170
              <input
171
                type="text"
172
                name="title"
173
                id="title"
174
                placeholder="Titulo"
175
                ref={register({
176
                  required: "Por favor ingrese el titulo",
177
                })}
178
              />
179
              {errors.title && (
180
                <FormErrorFeedback>{errors.title.message}</FormErrorFeedback>
181
              )}
182
            </div>
183
            <div className="form-group">
184
              <select
185
                name="employment_type"
186
                id="employment_type"
187
                defaultValue=""
188
                ref={register({
189
                  required: "Por favor eliga un tipo",
190
                })}
191
              >
192
                <option value="" hidden>
193
                  Tipo
194
                </option>
195
                {Object.entries(employmentTypes).map(([key, value]) => (
196
                  <option value={key} key={key}>
197
                    {value}
198
                  </option>
199
                ))}
200
              </select>
201
              {errors.employment_type && (
202
                <FormErrorFeedback>
203
                  {errors.employment_type.message}
204
                </FormErrorFeedback>
205
              )}
206
            </div>
207
            <div className="form-group">
208
              <input
209
                type="date"
210
                name="last_date_of_application"
211
                id="last_date_of_application"
212
                ref={register({
213
                  required: "Por favor ingrese una fecha",
214
                })}
215
              />
216
              {errors.last_date_of_application && (
217
                <FormErrorFeedback>
218
                  {errors.last_date_of_application.message}
219
                </FormErrorFeedback>
220
              )}
221
              {/* <input type="text" onClick={openCalendar} />
222
              <div ref={wrapperRef}>
223
                {state.isOpen && (
224
                  <Datetime
225
                    input={false}
226
                    onChange={handleDateChange}
227
                  ></Datetime>
228
                )}
229
              </div> */}
230
            </div>
231
            <div className="form-group">
232
              <select
233
                name="job_category_id"
234
                id="job_category_id"
235
                defaultValue=""
236
                ref={register({
237
                  required: "Por favor eliga un tipo",
238
                })}
239
              >
240
                <option value="1" hidden>
241
                  Categoría
242
                </option>
243
                {Object.entries(jobCategories).map(([key, value]) => (
244
                  <option value={key} key={key}>
245
                    {value}
246
                  </option>
247
                ))}
248
              </select>
249
              {errors.job_category_id && (
250
                <FormErrorFeedback>
251
                  {errors.job_category_id.message}
252
                </FormErrorFeedback>
253
              )}
254
            </div>
255
            <div className="form-group datefm">
256
              <UbicationInput
257
                onGetAddress={getAddressHandler}
258
                settedQuery={watch("formatted_address")}
259
              />
260
              <i className="fa fa-map-marker"></i>
261
              {errors.formatted_address && (
262
                <FormErrorFeedback>
263
                  {errors.formatted_address.message}
264
                </FormErrorFeedback>
265
              )}
266
            </div>
267
 
268
            {loading && (
269
              <StyledSpinnerContainer>
270
                <Spinner />
271
              </StyledSpinnerContainer>
272
            )}
273
          </div>
274
        </Modal.Body>
275
        <Modal.Footer>
276
          <Button type="submit">Crear</Button>
277
          <Button onClick={onHide} variant="danger">
278
            Cancelar
279
          </Button>
280
        </Modal.Footer>
281
      </form>
282
    </Modal>
283
  );
284
};
285
 
286
export default AddJobModal;