diff --git a/src/components/FormWorkCreated/FormWorkCreated.jsx b/src/components/FormWorkCreated/FormWorkCreated.jsx index a0b2a55..7b0975a 100644 --- a/src/components/FormWorkCreated/FormWorkCreated.jsx +++ b/src/components/FormWorkCreated/FormWorkCreated.jsx @@ -1,50 +1,51 @@ -import React, { isValidElement } from "react"; -import { NavLink, useNavigate, Link } from "react-router-dom"; +import axios from "axios"; +import { NavLink, useNavigate } from "react-router-dom"; import { useState, useEffect, useRef } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useParams } from "react-router-dom"; import validation from "../Validations/Validations"; -import { postJobs, getTypes, editPost } from "../../toolkit/ActionsworkPublications"; +import { + postJobs, + getTypes, + editPost, +} from "../../toolkit/ActionsworkPublications"; import { getDetailWork } from "../../toolkit/thunks"; import { useLocalStorage } from "../UseLocalStorage/UseLocalStorage"; import { getUser } from "../../toolkit/Users/usersHandler"; - -// Toast -import { ToastContainer, toast } from "react-toastify"; -import "react-toastify/dist/ReactToastify.css"; - -import axios from "axios"; - -// Components +import { + Button, + Card, + Input, + Option, + Select, + Textarea, + Typography, +} from "@material-tailwind/react"; +import { ArrowLeftIcon } from "@heroicons/react/24/outline"; +import { toast } from "sonner"; import Footer from "../Footer/Footer"; import Nav from "../PanelUser/Nav"; -import { setId } from "@material-tailwind/react/components/Tabs/TabsContext"; -import Loader from "../Loader/Loader"; - -//_______________________________________ const WorkPerTime = ["/Hora", "/Fijo"]; const maxSiseMB = 3 * 1024 * 1024; // Tamaño de 3mb para las fotos - export default function FormCreateWork() { - const { id } = useParams(); const dispatch = useDispatch(); - const dispatch2 = useDispatch(); const navigate = useNavigate(); - const ability = useSelector((state) => state.formwork.allWorkTypes) + const ability = useSelector((state) => state.formwork.allWorkTypes); const [selectedPaymentOption, setSelectedPaymentOption] = useState(""); const [fileSelected, setFileSelected] = useState(false); //Soluciona el filed seleccionado + const [selectKey, setSelectKey] = useState(0); + const [selectKey1, setSelectKey1] = useState(1); const fileInputRef = useRef(null); - const params = useParams() const TodosLostrabajos = useSelector((state) => state.work.work); - const { userCredentials } = useSelector(state => state.users); - const trabajoFiltrado = TodosLostrabajos.find(trabajo => trabajo._id === id); // Usa find en lugar de filter para obtener un solo objeto - const { detail } = useSelector(state => state.work) + const { userCredentials } = useSelector((state) => state.users); + const trabajoFiltrado = TodosLostrabajos.find( + (trabajo) => trabajo._id === id + ); // Usa find en lugar de filter para obtener un solo objeto let numericPrice; - const [workdata, setWorkData] = useState({ title: "", description: "", @@ -54,15 +55,6 @@ export default function FormCreateWork() { price: "", }); - const [workdata2, setWorkData2] = useState({ - title: "", - description: "", - address: "", - ability: [], - image: "", - price: "", - }); - const [errors, setErrors] = useState({ title: "", description: "", @@ -70,19 +62,15 @@ export default function FormCreateWork() { ability: [], image: "", price: "", - - }) - - + }); useEffect(() => { dispatch(getTypes()); if (userCredentials && userCredentials.uid === id) { - dispatch(getDetailWork(id)) + dispatch(getDetailWork(id)); dispatch(getUser(id)); - } - }, [dispatch, id, userCredentials]) + }, [dispatch, id, userCredentials]); function handleChange(event) { const { name, value } = event.target; @@ -92,35 +80,53 @@ export default function FormCreateWork() { [name]: value, }); - setErrors(validation({ - ...workdata, - [name]: value, - })); - + setErrors( + validation({ + ...workdata, + [name]: value, + }) + ); } - function handleSelect(event) { - const typeworkSelect = event.target.value; + const handleClick = () => { + navigate("/home"); + }; + + function handleSelect(value) { + const typeworkSelect = value; if (!workdata.ability.includes(typeworkSelect)) { setWorkData({ ...workdata, - ability: [...workdata.ability, typeworkSelect] - }) + ability: [...workdata.ability, typeworkSelect], + }); } } + const handleSelectPrice = (value) => { + setSelectedPaymentOption(value); + }; + function handleSubmit(event) { event.preventDefault(); const putUser = async () => { - const resultPut = await axios.put(`https://skillhub-back-production.up.railway.app/user/${id}`, { - cantidadPost: filterCantidadPost[0] + 1 - }) - } + const resultPut = await axios.put( + `https://skillhub-back-production.up.railway.app/user/${id}`, + { + cantidadPost: filterCantidadPost[0] + 1, + } + ); + }; putUser(); let updatedWorkData; const validateFields = () => { - if (!workdata.title || !workdata.description || !workdata.price || !workdata.image || !workdata.address) { + if ( + !workdata.title || + !workdata.description || + !workdata.price || + !workdata.image || + !workdata.address + ) { toast.error("Completa los datos para continuar"); return false; } else if (!selectedPaymentOption) { @@ -138,10 +144,15 @@ export default function FormCreateWork() { } else if (workdata.description.length > 200) { toast.error("La descripción debe tener máximo 200 caracteres"); return false; - } else if (errors.image === "El tamaño de la imagen debe ser inferior a 3MB") { + } else if ( + errors.image === "El tamaño de la imagen debe ser inferior a 3MB" + ) { toast.error("El peso de la imagen debe ser de máximo 3MB"); return false; - } else if (errors.title === "Prohibido" || errors.description === "Prohibido") { + } else if ( + errors.title === "Prohibido" || + errors.description === "Prohibido" + ) { toast.error("No está permitido escribir este tipo de servicios"); return false; } @@ -149,14 +160,12 @@ export default function FormCreateWork() { }; if (trabajoFiltrado) { - numericPrice = parseInt(workdata.price, 10); // Parsear a número if (validateFields()) { const userConfirmation = window.confirm("¿Editar trabajo?"); if (userConfirmation) { // Concatenar la opción de pago al precio const finalPrice = `${numericPrice} ${selectedPaymentOption}`; - updatedWorkData = { ...workdata, @@ -174,7 +183,9 @@ export default function FormCreateWork() { } } else { if (validateFields()) { - const userConfirmation = window.confirm("ADVERTENCIA! No podrás modificar el título después."); + const userConfirmation = window.confirm( + "ADVERTENCIA! No podrás modificar el título después." + ); if (userConfirmation) { // Concatenar la opción de pago al precio const finalPrice = `${workdata.price} ${selectedPaymentOption}`; @@ -194,14 +205,12 @@ export default function FormCreateWork() { } } } - //LocalStorage values - const [textDesciption, setTextDesciption] = useLocalStorage('text', ('')) - const [textTitle, setTextTitle] = useLocalStorage('tex1', ' ') - const [priceValue, setPriceValue] = useLocalStorage("text2", '') - const [directionValue, setDirectionValue] = useLocalStorage("tex3", ' ') - + const [textDesciption, setTextDesciption] = useLocalStorage("text", ""); + const [textTitle, setTextTitle] = useLocalStorage("tex1", " "); + const [priceValue, setPriceValue] = useLocalStorage("text2", ""); + const [directionValue, setDirectionValue] = useLocalStorage("tex3", " "); const handleReset = () => { setTextTitle(""); @@ -209,12 +218,13 @@ export default function FormCreateWork() { setDirectionValue(""); setPriceValue(""); setFileSelected(false); + setSelectKey((prevKey) => prevKey + 1); + setSelectKey1((prevKey) => prevKey + 10); if (fileInputRef.current) { fileInputRef.current.value = ""; } - setWorkData({ title: "", description: "", @@ -237,24 +247,25 @@ export default function FormCreateWork() { } }, []); - - const [selectWorkType, setSelectWorkType] = useState(""); - //Para poder seleccionar y borrar las categorias seleccionadas const tiposSelected = workdata.ability.map((cat) => (
{cat} + className="p-0.5 ml-1 bg-gray-800 text-white rounded-md w-6 h-6 border-2 border-slate-600 hover:bg-gray-700 hover:shadow-sm transition text-xs flex items-center justify-center" + > + {" "} + x{" "} +
)); function handleDelete(cat) { setWorkData({ ...workdata, - ability: workdata.ability.filter(typ => typ !== cat) - }) + ability: workdata.ability.filter((typ) => typ !== cat), + }); } //Subir imagenes a cloudinary @@ -262,26 +273,31 @@ export default function FormCreateWork() { async function uploadImage(files) { const selectedFile = files[0]; - if (selectedFile) { if (selectedFile.size < maxSiseMB) { setErrors({ ...errors, - image: "" + image: "", }); const imageFormData = new FormData(); imageFormData.append("file", files[0]); imageFormData.append("upload_preset", "PostWorks"); try { - const response = await axios.post("https://api.cloudinary.com/v1_1/dvr9giaia/upload", imageFormData); + const response = await axios.post( + "https://api.cloudinary.com/v1_1/dvr9giaia/upload", + imageFormData + ); const data = response.data.secure_url; // Actualizar el estado de manera inmutable - setWorkData(prevData => ({ + setWorkData((prevData) => ({ ...prevData, - image: data + image: data, })); - console.log("Esta es la nueva info de setWorkData en img", workdata.image); + console.log( + "Esta es la nueva info de setWorkData en img", + workdata.image + ); } catch (error) { console.log("Error en el componente UploadImage en cludinary", error); } @@ -289,29 +305,32 @@ export default function FormCreateWork() { } else { setErrors({ ...errors, - image: "El tamaño de la imagen debe ser inferior a 3MB" + image: "El tamaño de la imagen debe ser inferior a 3MB", }); } } } - - // Previsualización de la imagen - let previewImage = workdata.image ? ( - - Imagen Seleccionada -
- nature image -
-) : null; - - + // Previsualización de la imagen + let previewImage = workdata.image ? ( + + Imagen Seleccionada +
+ nature image +
+ ) : null; //Editar tarea @@ -325,262 +344,328 @@ export default function FormCreateWork() { image: trabajoFiltrado.image, price: trabajoFiltrado.price, }); - } }, [trabajoFiltrado, id]); - - -const [usuario, setUsuario] = useState([]) - -useEffect(() => { - const getUser = async () => { - const response = await axios(`https://skillhub-back-production.up.railway.app/user/`) - setUsuario(response.data.filter((element) => element.uid === id)) - - - } - getUser(); - }, [id]) - - - const filterUser = () => { - if (usuario.filter((element) => element.uid === id).map(({ pay }) => pay)[0] === undefined) { - return 'No hay suscripción'; - } else if(!usuario.filter((element) => element.uid === id).map(({ pay }) => pay.subscription)){ - return 'No hay suscripción'; - } else if (usuario.filter((element) => element.uid === id).some(({ pay }) => pay.subscription === true)) { - return usuario.filter((element) => element.uid === id).map(({ pay }) => pay.plan)[0]; - } else { - return 'No hay suscripción'; - } + + const [usuario, setUsuario] = useState([]); + + useEffect(() => { + const getUser = async () => { + const response = await axios( + `https://skillhub-back-production.up.railway.app/user/` + ); + setUsuario(response.data.filter((element) => element.uid === id)); + }; + getUser(); + }, [id]); + + const filterUser = () => { + if ( + usuario + .filter((element) => element.uid === id) + .map(({ pay }) => pay)[0] === undefined + ) { + return "No hay suscripción"; + } else if ( + !usuario + .filter((element) => element.uid === id) + .map(({ pay }) => pay.subscription) + ) { + return "No hay suscripción"; + } else if ( + usuario + .filter((element) => element.uid === id) + .some(({ pay }) => pay.subscription === true) + ) { + return usuario + .filter((element) => element.uid === id) + .map(({ pay }) => pay.plan)[0]; + } else { + return "No hay suscripción"; + } }; - const filterCantidadPost = usuario.filter((element) => element.uid === id).map(({cantidadPost}) => cantidadPost) - const filterCantidadPost2 = usuario.filter((element) => element.uid === id).map(({cantidadPost}) => cantidadPost)[0] - + const filterCantidadPost = usuario + .filter((element) => element.uid === id) + .map(({ cantidadPost }) => cantidadPost); + const filterCantidadPost2 = usuario + .filter((element) => element.uid === id) + .map(({ cantidadPost }) => cantidadPost)[0]; const findValidacion = () => { - if(filterUser() === 'No hay suscripción') { - return 'No se encontro suscripcion activa' - } - else if (filterUser() === "Plan BRONCE" && filterCantidadPost2 === 2) { - return 'cumplio la cantidad' - } else if (filterUser() === "Plan ORO" && filterCantidadPost2 === 15) { - return 'cumplio la cantidad' - } else { - return 'Suscripción activa' - } - - -} -const resultValidacion = findValidacion(); - + if (filterUser() === "No hay suscripción") { + return "No se encontro suscripcion activa"; + } else if (filterUser() === "Plan BRONCE" && filterCantidadPost2 === 2) { + return "cumplio la cantidad"; + } else if (filterUser() === "Plan ORO" && filterCantidadPost2 === 15) { + return "cumplio la cantidad"; + } else { + return "Suscripción activa"; + } + }; + const resultValidacion = findValidacion(); return ( - (
- { userCredentials && (usuario.length===1 ?resultValidacion === 'Suscripción activa':userCredentials)? - -
-