ProyectoDishjer / clienteapp-frontend / src / components / ServiceForm.js
ServiceForm.js
Raw
import React, { useState} from "react";
import axios, { HttpStatusCode } from "axios";
import { Link } from "react-router-dom";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { handleSendMail1 } from "./HandleSendMail";
import SignaturePad from "./firmaCanvas";



const fechaActual = () => { 
  const now = new Date();
  now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
  return now.toISOString().split('T')[0];
 }
  
const horaActual = () => { 
  return new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getSeconds();
}



const ServiceForm = () => {
  const [clienteId, setClienteId] = useState(null); // Nuevo estado para almacenar clienteId
  const [formData, setFormData] = useState({
    nombreCliente: "",
    correoCliente: "",
    nombreContacto: "",
    numero: "",
    direccion: "",
    barrio: "",
    ciudad: "",
    fecha: fechaActual(),
    horaInicio: horaActual(),
    horaFin: "",
    tipoServicio: "",
    tipoContrato: "",
    serialEquipo: "",
    contadorNegro: "",
    contadorColor: "",
    cantidad: "",
    descripcion: "",
    tipoRepuesto: "",
    observaciones: "",
    firmaTecnico: "",
    firmaCliente: "",
  });

  function handleKeyPressNumbers(e) {
    const regex = /[0-9 ]/;
    const specialKeys = [
      "Backspace",
      "ArrowLeft",
      "ArrowRight",
      "Delete",
      "Tab",
      "Home",
      "End",
      "Enter",
    ];
    if (!regex.test(e.key) && !specialKeys.includes(e.key)) {
      e.preventDefault();
    }
  }
  function handleKeyPressWords(e) {
    // condicional para evitar caracteres en nombre
    const regex = /[a-zA-Z \s ]+$/;
    const specialKeys = ["Backspace", "Enter", "Delete", "Tab"];
    if (!regex.test(e.key) && !specialKeys.includes(e.key)) {
      // Evitar que se ingrese el caracter solo letras
      e.preventDefault();
    }
  }

  const combinacionCaracteres = (e) => {
    const regex = /[a-zA-Z0-9\s]/;
    const specialKeys = ["Backspace", "Enter", "Delete", "Tab"];
    if (!regex.test(e.key) && !specialKeys.includes(e.key)) {
      e.preventDefault();
    }
  };

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  
 

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      // Crear cliente
      const clienteResponse = await axios.post(
        "http://localhost:8080/clientes",
        {
          nombreCliente: formData.nombreCliente,
          correoCliente: formData.correoCliente,
        }
      );
       const clienteId = clienteResponse.data.id;
      setClienteId(clienteId);
      
      console.log("Cliente creado con el id:", clienteId)
      console.log("enviando datos cliente ", clienteResponse.data);

      // Crear dirección asociada al cliente
      await axios.post("http://localhost:8080/direcciones", {
        direccion: formData.direccion,
        barrio: formData.barrio,
        ciudad: formData.ciudad,
        clienteId: clienteId,
      });

      // Crear equipo asociado al cliente

      const equipoResponse = await axios.post("http://localhost:8080/equipos", {
        serialEquipo: formData.serialEquipo,
        clienteId: clienteId,
        contadorColor: formData.contadorColor,
        contadorBlancoNegro: formData.contadorNegro,
      });
      const equipoId = equipoResponse.data.id;

      // Crear servicio asociado al equipo
      await axios.post("http://localhost:8080/servicios", {
        fecha: formData.fecha,
        horaInicio: formData.horaInicio,
        horaFin: formData.horaFin,
        tipoServicio: formData.tipoServicio,
        tipoContrato: formData.tipoContrato,
        observaciones: formData.observaciones,
        firmaTecnico: formData.firmaTecnico,
        firmaCliente: formData.firmaCliente,
        equipoId: equipoId,
      });

      // Crear repuesto asociado al equipo
      await axios.post("http://localhost:8080/repuestos", {
        descripcion: formData.descripcion,
        cantidad: formData.cantidad,
        tipo: formData.tipoRepuesto,
        equipoId: equipoId,
      });

      // Crear contacto asociado al cliente
      const contactoResponse = await axios.post(
        "http://localhost:8080/contactos",
        {
          nombreContacto: formData.nombreContacto,
          clienteId: clienteId,
        }
      );
      const contactoId = contactoResponse.data.id;

      // Crear teléfono asociado al contacto
      await axios.post("http://localhost:8080/telefonos", {
        numero: formData.numero,
        contactoId: contactoId,
      });

      const jsonData = {
        id: clienteId,
        nombreCliente: formData.nombreCliente,
        correoCliente: formData.correoCliente,
        direcciones: [
          {
            direccion: formData.direccion,
            barrio: formData.barrio,
            ciudad: formData.ciudad,
            clienteId: clienteId,
          },
        ],
        equipos: [
          {
            id: equipoId,
            serialEquipo: formData.serialEquipo,
            contadorColor: formData.contadorColor,
            contadorBlancoNegro: formData.contadorNegro,
            servicios: [
              {
                fecha: formData.fecha,
                horaInicio: formData.horaInicio,
                horaFin: formData.horaFin,
                tipoServicio: formData.tipoServicio,
                tipoContrato: formData.tipoContrato,
                observaciones: formData.observaciones,
                firmaTecnico: formData.firmaTecnico,
                firmaCliente: formData.firmaCliente,
                equipoId: equipoId,
              },
            ],
            repuestos: [
              {
                descripcion: formData.descripcion,
                cantidad: formData.cantidad,
                tipo: formData.tipoRepuesto,
                equipoId: equipoId,
              },
            ],
            clienteId: clienteId,
          },
        ],
        contactos: [
          {
            nombreContacto: formData.nombreContacto,
            telefono: {
              numero: formData.numero,
              contactoId: contactoId,
            },
            clienteId: clienteId,
          },
        ],
      };


      // Enviar el JSON al backend para generar el PDF y descargarlo
      const response = await axios.post(
        "http://localhost:8080/generate-pdf",
        jsonData,
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      );

      if (response === HttpStatusCode.Ok) {
        console.log("se envio correctamente los datos al backend")
      }
      setFormData({
        nombreCliente: "",
        correoCliente:"",
        contacto: "",
        numero: "",
        direccion: "",
        barrio: "",
        ciudad: "",
        fecha: "",
        horaInicio: "",
        horaFin: "",
        tipoServicio: "",
        tipoContrato: "",
        serialEquipo: "",
        contadorNegro: "",
        contadorColor: "",
        cantidad: "",
        descripcion: "",
        tipoRepuesto: "",
        observaciones: "",
        firmaTecnico: "",
        firmaCliente: "",
      });
      console.log("Todos los datos fueron enviados correctamente");
      toast.success("Formulario enviado con exito");
    //Aqui se llama la funcion para descargar el pdf
      handleDownloadPdf(clienteId)
       // Aqui se llama la funcion de enviar correo, luego de haber generado el pdf 
     // handleSendMail1(clienteId, jsonData);
    } catch (error) {
      console.error("Error al crear el servicio:", error);
      console.error("Error generando el pdf ", error);
    }
  };
  

 const handleDownloadPdf = async (clienteId) => {
    try {
      console.log("Descargando PDF...");
      const response = await axios.get(
        `http://localhost:8080/download-pdf/${clienteId }`,
        {
          responseType: "blob",
        }
      );
      if (response.data.size === 0) {
        throw new Error("El arhcivo pdf esta vacio")
      }

      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", `cliente_${clienteId}.pdf`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      console.log("PDF descargado correctamente.");
    } catch (error) {
      console.error("Error descargando PDF", error);
    }
  };

  const handleClearForm = () => {
    setFormData({
      nombreCliente: "",
      nombreContacto: "",
      numero: "",
      direccion: "",
      barrio: "",
      ciudad: "",
      fecha: "",
      horaInicio: "",
      horaFin: "",
      tipoServicio: "",
      tipoContrato: "",
      serialEquipo: "",
      contadorNegro: "",
      contadorColor: "",
      cantidad: "",
      descripcion: "",
      tipoRepuesto: "",
      observaciones: "",
      firmaTecnico: "",
      firmaCliente: "",
    });
  };


  return (
    <div className="box-wrapper">
      <div className="row">
        <div className="col-md-6 mt-4 ml-1 mb-4 mr-4">
          <div className="container mt-3">
            <nav class="navbar bg-dark navbar-expand-lg bg-body-tertiary custom-navbar-bg ">
              <div div class="container mt-1 d-flex justify-content-start  ">
                 <img
              src="https://disjher.com/images/LOGO_DISJHER_ULTIMO_CORREGIDO-01.png"
              alt="Logo"
              width="100px"
                  height="50px"
            />
                <h4 className="text-white-custom">
                      Servicio Técnico
                </h4>
                <Link
                  to="/clientes"
                  className="btn btn-link ml-xl-5 my-2 my-sm-4"
                >
                  Clientes
                </Link>
              </div>
              <form className="form-inline ml-xl-5 "></form>
            </nav>
          </div>
          <form onSubmit={handleSubmit} className="mt-5 container left ">
            <div className="form-group">
              <label>Nombre Cliente</label>
              <select
                type="text"
                className="form-control"
                name="nombreCliente"
                value={formData.nombreCliente}
                onChange={handleChange}
                required
              //  onKeyDown={(e) => handleKeyPressWords(e)}
              >  <option value="">Seleccione un tipo</option>
                <option value="Dalu">Dalu</option>
                <option value="Tava">Tava</option>
                <option value="ImagenEditorial">ImagenEditorial</option>
                <option value="ArteMunar">ArteMunar</option>
                <option value="ArteMunar">ArteMunar</option>
                
          


                </select>
              
            </div>

            <div className="form-group">
              <label>Nombre Contacto</label>
              <input
                type="text"
                className="form-control"
                name="nombreContacto"
                value={formData.nombreContacto}
                onChange={handleChange}
                required
                onKeyDown={(e) => handleKeyPressWords(e)}
              />
            </div>
            <div className="form-group">
              <label>Telefono</label>
              <input
                type="text"
                className="form-control"
                name="numero"
                value={formData.numero}
                onChange={handleChange}
                required
                onKeyDown={(e) => handleKeyPressNumbers(e)}
              />
            </div>
            <div className="form-group">
              <label>Correo Electronico</label>
              <input
                type="text"
                className="form-control"
                name="correoCliente"
                value={formData.correoCliente}
                onChange={handleChange}
                required
              />
            </div>
            <div className="form-group">
              <label>Dirección</label>
              <input
                type="text"
                className="form-control"
                name="direccion"
                value={formData.direccion}
                onChange={handleChange}
                required
              />
            </div>

            <div className="form-group">
              <label>Barrio</label>
              <input
                type="text"
                className="form-control"
                name="barrio"
                value={formData.barrio}
                onChange={handleChange}
                required
                onKeyDown={(e) => handleKeyPressWords(e)}
              />
            </div>
            <div className="form-group">
              <label>Ciudad</label>
              <input
                type="text"
                className="form-control"
                name="ciudad"
                value={formData.ciudad}
                onChange={handleChange}
                required
                onKeyDown={(e) => handleKeyPressWords(e)}
              />
            </div>

            <div className="form-group">
              <label>Fecha</label>
              <input
                type="date"
                className="form-control"
                name="fecha"
                value={formData.fecha}
                onChange={handleChange}
                required
              />
            </div>
            <div className="form-group">
              <label>Hora de Inicio</label>
              <input
                type="time"
                className="form-control"
                name="horaInicio"
                value={formData.horaInicio}
                onChange={handleChange}
                required
              />
            </div>
            <div className="form-group">
              <label>Hora de Fin</label>
              <input
                type="time"
                className="form-control"
                name="horaFin"
                value={formData.horaFin}
                onChange={handleChange}
                required
              />
            </div>
            <div className="form-group">
              <label>Tipo de Servicio</label>
              <select
                className="form-control"
                name="tipoServicio"
                value={formData.tipoServicio}
                onChange={handleChange}
                required
              >
                <option value="">Seleccione un tipo</option>
                <option value="mantenimiento preventivo">
                  Mantenimiento Preventivo
                </option>
                <option value="mantenimiento correctivo">
                  Mantenimiento Correctivo
                </option>
                <option value="reparación">Reparación</option>
              </select>
            </div>
            <div className="form-group">
              <label>Tipo de Contrato</label>
              <select
                className="form-control"
                name="tipoContrato"
                value={formData.tipoContrato}
                onChange={handleChange}
                required
              >
                <option value="">Seleccione un tipo</option>
                <option value="contrato">Contrato</option>
                <option value="garantia">Garantia</option>
                <option value="facturar">Facturar</option>
              </select>
            </div>
            <div className="form-group">
              <label>Serial del Equipo</label>
              <input
                type="text"
                className="form-control"
                name="serialEquipo"
                value={formData.serialEquipo}
                onChange={handleChange}
                required
                onKeyDown={(e) => combinacionCaracteres(e)}
              />
            </div>
            <div className="form-group">
              <label>Contador Negro</label>
              <input
                type="number"
                className="form-control"
                name="contadorNegro"
                value={formData.contadorNegro}
                onChange={handleChange}
                required
                onKeyDown={(e) => handleKeyPressNumbers(e)}
              />
            </div>
            <div className="form-group">
              <label>Contador Color</label>
              <input
                type="number"
                className="form-control"
                name="contadorColor"
                value={formData.contadorColor}
                onChange={handleChange}
                onKeyDown={(e) => handleKeyPressNumbers(e)}
              />
            </div>
            <div className="form-group">
              <label>Repuesto</label>
              <select
                className="form-control"
                name="descripcion"
                value={formData.descripcion}
                onChange={handleChange}
                required
                onKeyDown={(e) => handleKeyPressWords(e)}
              >
              <option value="">Selecciona un tipo</option>   
              <option value="si">Si</option>
              <option value="no">No</option>
              </select>

            </div>
            <div className="form-group">
              <label>Cantidad Repuestos</label>
              <input
                type="number"
                className="form-control"
                name="cantidad"
                value={formData.cantidad}
                onChange={handleChange}
                required
                onKeyDown={(e) => handleKeyPressNumbers(e)}
              />
            </div>
            <div className="form-group">
              <label>Estado del repuesto</label>
              <select
                className="form-control"
                name="tipoRepuesto"
                value={formData.tipoRepuesto}
                onChange={handleChange}
                required
              >
                <option value="">Seleccione un tipo</option>
                <option value="cotizacion">Cotización</option>
                <option value="cambio">Cambio</option>
                <option value="ninguno">Ninguno</option>

              </select>
            </div>
            <div className="form-group">
              <label>Observaciones</label>
              <textarea
                className="form-control"
                name="observaciones"
                value={formData.observaciones}
                onChange={handleChange}
                required
                maxLength="800"
              />
            </div>
            <div className="form-group">
              <label>Firma Técnico</label>
             
              <SignaturePad onSave={(signature) => setFormData({ ...formData, firmaTecnico: signature }) } />
           {/*   <input
                type="text"
                className="form-control"
                name="firmaTecnico"
                value={formData.firmaTecnico}
                onChange={handleChange}
                required
              />*/}
            </div>
            <div className="form-group">
              <label>Firma Cliente</label>
              <SignaturePad onSave={(signature) => setFormData({ ...formData, firmaCliente: signature })
              
              } />
             {/* <input
                type="text"
                className="form-control"
                name="firmaCliente"
                value={formData.firmaCliente}
                onChange={handleChange}
                required
              />*/}
            </div>
            <div style={{ display: "flex", justifyContent: "space-around" }}>
              <button
                type="submit"
                className="btn  btn-dark btn-primary "
                style={{ marginTop: "10px" }}
            //    onClick={handleButtonClick}
              >
                Enviar
              </button>
              <button
                type="button"
                className="btn btn-dark btn-primary"
                style={{ marginTop: "10px" }}
                onClick={handleClearForm}
              >
                Limpiar
              </button>
            </div>
          </form>
          <ToastContainer
            position="bottom-center"
            autoClose={5000}
            hideProgressBar={false}
            newestOnTop={false}
            closeOnClick
            rtl={false}
            pauseOnFocusLoss
            draggable
            pauseOnHover
            theme="dark"
          />
        </div>
      </div>
    </div>
  );
};
export default ServiceForm;