Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Autoría | Ultima modificación | Ver Log |

/* eslint-disable react/prop-types */
import { CKEditor } from 'ckeditor4-react';
import React, { useEffect, useRef, useState } from 'react'
import { Button, Modal } from 'react-bootstrap'
import { useForm } from 'react-hook-form';
import { addNotification } from '../../../../../../redux/notification/notification.actions';
import FormErrorFeedback from '../../../../../../shared/form-error-feedback/FormErrorFeedback';
import Spinner from '../../../../../../shared/loading-spinner/Spinner';
import UbicationInput from '../../../../../../shared/ubication-input/UbicationInput';
import { axios, CKEDITOR_OPTIONS } from '../../../../../../utils';

const ExperienceModal = ({ show, closeModal, setSettedUserExperiences, settedUserExperiences }) => {

    const { register, errors, handleSubmit, setValue, clearErrors, getValues, watch, setError, } = useForm();

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modalLoading, setModalLoading] = useState(false);
    const [settedDescription, setSettedDescription] = useState("");

    const isAddressEmpty = useRef(true);
    const postUrl = useRef("");
    const addressKeys = useRef([
        "address1",
        "address2",
        "country",
        "state",
        "city1",
        "city2",
        "postal_code",
        "latitude",
        "longitude",
    ]);

    useEffect(() => {
        addressKeys.current.map((addressKey) => {
            register(addressKey);
        });
        register("formatted_address", {
            required: "Este campo es requerido",
        });
        register("description");
    }, []);

    const getAddressHandler = (addresObject) => {
        addressKeys.current.map((addressKey) => {
            setValue(addressKey, "");
        });
        const { address_components } = addresObject;
        if (address_components) {
            address_components.map((address_component) => {
                const address_component_name = address_component.long_name;
                const address_component_type = address_component.types[0];
                switch (address_component_type) {
                    case "route":
                        setValue("address1", address_component_name);
                        break;
                    case "sublocality":
                        setValue("address2", address_component_name);
                        break;
                    case "locality":
                        setValue("city1", address_component_name);
                        break;
                    case "administrative_area_level_2":
                        setValue("city2", address_component_name);
                        break;
                    case "administrative_area_level_1":
                        setValue("state", address_component_name);
                        break;
                    case "country":
                        setValue("country", address_component_name);
                        break;
                    case "postal_code":
                        setValue("postal_code", address_component_name);
                        break;
                    case "geometry":
                        setValue("latitude", address_component.latitude);
                        setValue("longitude", address_component.longitude);
                        break;
                    default:
                        break;
                }
            });
            isAddressEmpty.current = false;
        } else {
            isAddressEmpty.current = true;
        }
        setValue("formatted_address", addresObject.formatted_address);
        clearErrors("formatted_address");
    };

    const getYears = () => {
        const date = new Date();
        const currentYear = date.getFullYear();
        let years = [];
        for (let index = currentYear; index > currentYear - 100; index--) {
            years = [...years, index];
        }
        return years;
    };

    const onSubmitHandler = async (data) => {
        console.log(data)
        setModalLoading(true);

        const formData = new FormData();
        Object.entries(data).map(([key, value]) => {
            if (value) formData.append(key, value);
        });

        await axios.post(postUrl.current, formData)
            .then((response) => {
                const resData = response.data;

                if (resData.success) {
                    setSettedUserExperiences(resData.data);
                    closeModal();
                } else {
                    const resError = resData.data;
                    if (resError.constructor.name === "Object") {
                        Object.entries(resError).map(([key, value]) => {
                            if (key in getValues()) {
                                setError(key, {
                                    type: "manual",
                                    message: Array.isArray(value) ? value[0] : value,
                                });
                            }
                        });
                    } else {
                        addNotification({
                            style: "danger",
                            msg: resError,
                        });
                    }
                }
            });
        setModalLoading(false);
    };



    const handleNewExperience = (event) => {
        event.preventDefault();
        postUrl.current = `/profile/my-profiles/experience/${userIdEncrypted}/operation/add`;
        setSettedDescription("");
        handleModalOpen();
    };

    const handleEdit = async (linkEdit) => {
        postUrl.current = linkEdit;
        const currentDescription = settedUserExperiences.find(experience => experience.link_edit === linkEdit)
        setSettedDescription(currentDescription.description)
        setModalLoading(true)
        const { data } = await axios.get(linkEdit)
        if (!data.success) {
            addNotification({
                style: "danger",
                msg: typeof data.data === 'string' ? data.data : 'Ha ocurrido un error'
            })
            setModalLoading(false);
            return
        }
        handleModalOpen();
        Object.entries(data.data.experience)
            .map(([key, value]) => value && setValue(key, value));
        Object.entries(data.data.location)
            .map(([key, value]) => value && setValue(key, value));
        isAddressEmpty.current = false;
        setModalLoading(false)
    };

    return (
        <Modal show={show} onHide={closeModal} style={{ overflowY: "scroll" }}>
            <Modal.Header closeButton>
                <Modal.Title>Experiencia</Modal.Title>
            </Modal.Header>
            <form onSubmit={handleSubmit(onSubmitHandler)}>
                <Modal.Body>
                    <div className="form-group">
                        <input
                            type="text"
                            name="company"
                            placeholder="Empresa"
                            ref={register({
                                required: "este campo es requerido",
                            })}
                        />
                        {errors.company && <FormErrorFeedback>{errors.company.message}</FormErrorFeedback>}
                    </div>
                    <div className="form-group">
                        <select
                            name="industry_id"
                            id="industry_id"
                            ref={register({
                                required: "este campo es requerido",
                            })}
                            defaultValue=""
                        >
                            <option value="" hidden>
                                Industria
                            </option>
                            {Object.entries(industriesOptions).map(([key, value]) => (
                                <option value={key} key={key}>
                                    {value}
                                </option>
                            ))}
                        </select>
                        {errors.industry_id && (
                            <FormErrorFeedback>
                                {errors.industry_id.message}
                            </FormErrorFeedback>
                        )}
                    </div>
                    <div className="form-group">
                        <select
                            name="company_size_id"
                            id="company_size_id"
                            ref={register({
                                required: "este campo es requerido",
                            })}
                            defaultValue=""
                        >
                            <option value="" hidden>
                                Tamaño de la Empresa
                            </option>
                            {Object.entries(companySizesOptions).map(([key, value]) => (
                                <option value={key} key={key}>
                                    {value}
                                </option>
                            ))}
                        </select>
                        {errors.company_size_id && (
                            <FormErrorFeedback>
                                {errors.company_size_id.message}
                            </FormErrorFeedback>
                        )}
                    </div>
                    <div className="form-group">
                        <input
                            type="text"
                            name="title"
                            placeholder="Titulo"
                            ref={register({
                                required: "este campo es requerido",
                            })}
                        />
                        {errors.title && (
                            <FormErrorFeedback>{errors.title.message}</FormErrorFeedback>
                        )}
                    </div>
                    <div className="form-group datefm">
                        <UbicationInput
                            onGetAddress={getAddressHandler}
                            settedQuery={watch("formatted_address")}
                        />
                        <i className="fa fa-map-marker" />
                        {errors.formatted_address &&
                            <FormErrorFeedback>
                                {errors.formatted_address.message}
                            </FormErrorFeedback>
                        }
                    </div>
                    <div className="row profile-year" style={{ gap: '.5rem' }}>
                        <div className="input-c p-0">
                            <div className="form-group">
                                <select
                                    name="from_month"
                                    id="from_month"
                                    ref={register({ required: "este campo es requerido" })}
                                    defaultValue=""
                                >
                                    <option value="">Mes desde</option>
                                    {months.map((month, id) => (
                                        <option key={id} value={id + 1}>
                                            {month}
                                        </option>
                                    ))}
                                </select>
                                {errors.from_month &&
                                    <FormErrorFeedback>
                                        {errors.from_month.message}
                                    </FormErrorFeedback>
                                }
                            </div>
                        </div>
                        <div className="input-c p-0">
                            <div className="form-group">
                                <select
                                    name="from_year"
                                    ref={register({ required: "este campo es requerido", })}
                                    defaultValue=""
                                >
                                    <option value="">Año desde</option>
                                    {getYears().map((year) => (
                                        <option key={year} value={year}>
                                            {year}
                                        </option>
                                    ))}
                                </select>
                                {errors.from_year && (
                                    <FormErrorFeedback>
                                        {errors.from_year.message}
                                    </FormErrorFeedback>
                                )}
                            </div>
                        </div>
                    </div>
                    <label htmlFor="is_current"> Trabajo Actual</label>
                    <div className="form-group">
                        <StyledSwitch className="switch">
                            <input
                                type="checkbox"
                                name="is_current"
                                id="is_current"
                                value="y"
                                ref={register}
                            />
                            <span className="slider round"></span>
                        </StyledSwitch>
                    </div>
                    {!watch("is_current") && (
                        <div className="row profile-year">
                            <div className="input-c p-0">
                                <div className="form-group">
                                    <select
                                        name="to_month"
                                        id="to_month"
                                        ref={register({
                                            required: "este campo es requerido",
                                        })}
                                        defaultValue=""
                                    >
                                        <option value="">Mes hasta</option>
                                        {months.map((month, id) => (
                                            <option key={id} value={id + 1}>
                                                {month}
                                            </option>
                                        ))}
                                    </select>
                                    {errors.to_month && (
                                        <FormErrorFeedback>
                                            {errors.to_month.message}
                                        </FormErrorFeedback>
                                    )}
                                </div>
                            </div>
                            <div className="input-c p-0">
                                <div className="form-group">
                                    <select
                                        name="to_year"
                                        id="to_year"
                                        ref={register({
                                            required: "este campo es requerido",
                                        })}
                                        defaultValue=""
                                    >
                                        <option value="">Año hasta</option>
                                        {getYears().map((year) => (
                                            <option key={year} value={year}>
                                                {year}
                                            </option>
                                        ))}
                                    </select>
                                    {errors.to_year && (
                                        <FormErrorFeedback>
                                            {errors.to_year.message}
                                        </FormErrorFeedback>
                                    )}
                                </div>
                            </div>
                        </div>
                    )}
                    <div className="form-group">
                        <CKEditor
                            onChange={(e) => setValue('description', e.editor.getData())}
                            onInstanceReady={(e) => e.editor.setData(settedDescription)}
                            config={CKEDITOR_OPTIONS}
                        />
                        {errors.description && (
                            <FormErrorFeedback>
                                {errors.description.message}
                            </FormErrorFeedback>
                        )}
                    </div>
                </Modal.Body>
                <Modal.Footer>
                    <Button size="sm" type="submit">Enviar</Button>
                    <Button size="sm" variant="danger" onClick={handleModalOpen}>
                        Cancelar
                    </Button>
                </Modal.Footer>
            </form>
            {modalLoading && <Spinner />}
        </Modal>
    )
}

export default ExperienceModal