Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useEffect, useState } from "react";
- import Form from "../Index";
- import { Input } from "../Input";
- import * as yup from "yup";
- import { SelectByObjectArray } from "../SelectByObjectArray";
- import { useForm } from "react-hook-form";
- import { yupResolver } from "@hookform/resolvers/yup";
- import { IManager } from "../../../interfaces/IManager";
- import { IIntech } from "../../../interfaces/IIntech";
- import { IEnterprise } from "../../../interfaces/IEnterprise";
- import { ISalesman } from "../../../interfaces/ISalesman";
- import { api } from "../../../utils/api";
- import router from "next/router";
- import { useValidationsBR } from "validations-br";
- import apiCep from "../../../utils/api/apiCep";
- interface submitData {
- id?: number,
- accountTypeEnum: string;
- email: string;
- manager?: IManager;
- salesman?: ISalesman;
- management?: IIntech;
- enterprise?: IEnterprise;
- }
- interface DataProps {
- id: number;
- accountTypeEnum: string;
- email: string;
- city: string;
- country: string;
- location: string;
- state: string;
- zipcode: string;
- cpf: string;
- enterpriseId: number;
- name: string;
- phone: string;
- }
- const formSchema = yup.object().shape({
- name: yup.string().required("Nome é obrigatório!"),
- email: yup.string().email("Email inválido!").required("Email é obrigatório!"),
- cpf: yup
- .string()
- .required("CPF obrigatório")
- .test("is-cpf", "CPF inválido", (value) =>
- useValidationsBR("cpf", String(value))
- ),
- phone: yup
- .string()
- .required("Número é obrigatório!")
- .test("is-phone", "Número inválido", (value) =>
- useValidationsBR("phone", String(value))
- ),
- city: yup.string().required("Cidade é obrigatória!"),
- country: yup.string().required("País é obrigatório!"),
- location: yup.string().required("Lugar é obrigatório!"),
- state: yup.string().required("Estado é obrigatório!"),
- zipcode: yup
- .string()
- .required("CEP é obrigatório!")
- .test("is-cep", "CEP inválido", (value) =>
- useValidationsBR("cep", String(value))
- ),
- enterpriseId: yup.number().required("Empresa é obrigatória!"),
- accountTypeEnum: yup.string().default("MANAGER"),
- });
- export default function ManagerForm(props: { data: submitData }) {
- const defaultValues: DataProps = {
- id: props.data.id,
- accountTypeEnum: props.data.accountTypeEnum,
- cpf: props.data.manager.cpf,
- name: props.data.manager.name,
- email: props.data.email,
- phone: props.data.manager.phone,
- enterpriseId: props.data.manager.enterpriseId,
- city: props.data.manager.address.city,
- country: props.data.manager.address.country,
- location: props.data.manager.address.location,
- state: props.data.manager.address.state,
- zipcode: props.data.manager.address.zipcode,
- }
- const [enterprises, setEnterprises] = useState<IEnterprise[]>();
- const {
- register,
- handleSubmit,
- setValue,
- formState: { errors },
- } = useForm({
- resolver: yupResolver(formSchema),
- defaultValues: defaultValues,
- });
- const getEnterprise = async () => {
- try {
- const response = await api.get("/enterprise");
- setEnterprises(response.data.content);
- console.log(response);
- } catch (err) {
- console.log(err);
- }
- };
- useEffect(() => {
- console.log("Data componente:");
- console.log(props.data);
- getEnterprise();
- }, []);
- async function handleCEPChange(e: React.ChangeEvent<HTMLInputElement>) {
- const cep = e.currentTarget.value;
- if (cep.length === e.currentTarget.maxLength) {
- const response = await apiCep.get(`/${cep}/json`);
- console.log("Endereço", response.data);
- const { logradouro, bairro, localidade, uf, complemento } = response.data;
- setValue("location", logradouro, { shouldValidate: true });
- setValue("city", localidade, { shouldValidate: true });
- setValue("state", uf, { shouldValidate: true });
- }
- }
- const onHandleSubmit = async (data: DataProps) => {
- const submitDate: submitData = {
- accountTypeEnum: data.accountTypeEnum,
- email: data.email,
- manager: {
- address: {
- city: data.city,
- country: data.country,
- location: data.location,
- state: data.state,
- zipcode: data.zipcode,
- },
- cpf: data.cpf,
- enterpriseId: data.enterpriseId,
- name: data.name,
- phone: data.phone,
- },
- };
- console.log(submitDate);
- try {
- const response = await api.put(`/account/${data.id}`, submitDate);
- console.log(response);
- alert("Cadastro Atualizado com Sucesso");
- router.push("/usuarios");
- } catch (err) {
- console.log(err);
- }
- };
- return (
- <Form
- onSubmit={handleSubmit(onHandleSubmit)}
- yupFormSchemaValidation={formSchema}
- >
- <Input
- name="name"
- type={"text"}
- label="Name"
- error={errors.name}
- {...register("name")}
- />
- <Input
- name="email"
- type={"email"}
- label="E-mail"
- error={errors.email}
- {...register("email")}
- />
- <Input
- name="cpf"
- type={"text"}
- label="CPF"
- error={errors.cpf}
- mask="cpf"
- {...register("cpf")}
- />
- <Input
- name="phone"
- type={"text"}
- label="Número"
- mask="phone"
- error={errors.phone}
- {...register("phone")}
- />
- <Input
- name="country"
- type={"text"}
- label="País"
- error={errors.country}
- {...register("country")}
- />
- <Input
- name="zipcode"
- type={"text"}
- label="CEP"
- mask="cep"
- error={errors.zipcode}
- {...register("zipcode")}
- onChange={(e) => handleCEPChange(e)}
- />
- <Input
- name="city"
- type={"text"}
- label="Cidade"
- error={errors.city}
- {...register("city")}
- />
- <Input
- name="location"
- type={"text"}
- label="Lugar"
- error={errors.location}
- {...register("location")}
- />
- <Input
- name="state"
- type={"text"}
- label="Estado"
- error={errors.state}
- {...register("state")}
- />
- <SelectByObjectArray
- name="enterpriseId"
- {...register("enterpriseId")}
- error={errors.enterpriseId}
- label="Empresa"
- dataLabel={(item) => item.name}
- dataValue={(item) => item.id}
- dataKey={(item) => item.id}
- data={enterprises}
- />
- </Form>
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement