Advertisement
Guest User

Untitled

a guest
Mar 14th, 2022
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.82 KB | None | 0 0
  1. import React, { useEffect, useState } from "react";
  2. import Form from "../Index";
  3. import { Input } from "../Input";
  4. import * as yup from "yup";
  5. import { SelectByObjectArray } from "../SelectByObjectArray";
  6. import { useForm } from "react-hook-form";
  7. import { yupResolver } from "@hookform/resolvers/yup";
  8. import { IManager } from "../../../interfaces/IManager";
  9. import { IIntech } from "../../../interfaces/IIntech";
  10. import { IEnterprise } from "../../../interfaces/IEnterprise";
  11. import { ISalesman } from "../../../interfaces/ISalesman";
  12. import { api } from "../../../utils/api";
  13. import router from "next/router";
  14. import { useValidationsBR } from "validations-br";
  15. import apiCep from "../../../utils/api/apiCep";
  16. interface submitData {
  17. id?: number,
  18. accountTypeEnum: string;
  19. email: string;
  20. manager?: IManager;
  21. salesman?: ISalesman;
  22. management?: IIntech;
  23. enterprise?: IEnterprise;
  24. }
  25.  
  26. interface DataProps {
  27. id: number;
  28. accountTypeEnum: string;
  29. email: string;
  30. city: string;
  31. country: string;
  32. location: string;
  33. state: string;
  34. zipcode: string;
  35. cpf: string;
  36. enterpriseId: number;
  37. name: string;
  38. phone: string;
  39. }
  40.  
  41. const formSchema = yup.object().shape({
  42. name: yup.string().required("Nome é obrigatório!"),
  43. email: yup.string().email("Email inválido!").required("Email é obrigatório!"),
  44. cpf: yup
  45. .string()
  46. .required("CPF obrigatório")
  47. .test("is-cpf", "CPF inválido", (value) =>
  48. useValidationsBR("cpf", String(value))
  49. ),
  50. phone: yup
  51. .string()
  52. .required("Número é obrigatório!")
  53. .test("is-phone", "Número inválido", (value) =>
  54. useValidationsBR("phone", String(value))
  55. ),
  56. city: yup.string().required("Cidade é obrigatória!"),
  57. country: yup.string().required("País é obrigatório!"),
  58. location: yup.string().required("Lugar é obrigatório!"),
  59. state: yup.string().required("Estado é obrigatório!"),
  60. zipcode: yup
  61. .string()
  62. .required("CEP é obrigatório!")
  63. .test("is-cep", "CEP inválido", (value) =>
  64. useValidationsBR("cep", String(value))
  65. ),
  66. enterpriseId: yup.number().required("Empresa é obrigatória!"),
  67. accountTypeEnum: yup.string().default("MANAGER"),
  68. });
  69.  
  70. export default function ManagerForm(props: { data: submitData }) {
  71. const defaultValues: DataProps = {
  72. id: props.data.id,
  73. accountTypeEnum: props.data.accountTypeEnum,
  74. cpf: props.data.manager.cpf,
  75. name: props.data.manager.name,
  76. email: props.data.email,
  77. phone: props.data.manager.phone,
  78. enterpriseId: props.data.manager.enterpriseId,
  79. city: props.data.manager.address.city,
  80. country: props.data.manager.address.country,
  81. location: props.data.manager.address.location,
  82. state: props.data.manager.address.state,
  83. zipcode: props.data.manager.address.zipcode,
  84. }
  85.  
  86. const [enterprises, setEnterprises] = useState<IEnterprise[]>();
  87. const {
  88. register,
  89. handleSubmit,
  90. setValue,
  91. formState: { errors },
  92. } = useForm({
  93. resolver: yupResolver(formSchema),
  94. defaultValues: defaultValues,
  95. });
  96. const getEnterprise = async () => {
  97. try {
  98. const response = await api.get("/enterprise");
  99. setEnterprises(response.data.content);
  100. console.log(response);
  101. } catch (err) {
  102. console.log(err);
  103. }
  104. };
  105.  
  106. useEffect(() => {
  107. console.log("Data componente:");
  108. console.log(props.data);
  109. getEnterprise();
  110. }, []);
  111.  
  112. async function handleCEPChange(e: React.ChangeEvent<HTMLInputElement>) {
  113. const cep = e.currentTarget.value;
  114.  
  115. if (cep.length === e.currentTarget.maxLength) {
  116. const response = await apiCep.get(`/${cep}/json`);
  117.  
  118. console.log("Endereço", response.data);
  119.  
  120. const { logradouro, bairro, localidade, uf, complemento } = response.data;
  121.  
  122. setValue("location", logradouro, { shouldValidate: true });
  123. setValue("city", localidade, { shouldValidate: true });
  124. setValue("state", uf, { shouldValidate: true });
  125. }
  126. }
  127.  
  128. const onHandleSubmit = async (data: DataProps) => {
  129. const submitDate: submitData = {
  130. accountTypeEnum: data.accountTypeEnum,
  131. email: data.email,
  132. manager: {
  133. address: {
  134. city: data.city,
  135. country: data.country,
  136. location: data.location,
  137. state: data.state,
  138. zipcode: data.zipcode,
  139. },
  140. cpf: data.cpf,
  141. enterpriseId: data.enterpriseId,
  142. name: data.name,
  143. phone: data.phone,
  144. },
  145. };
  146. console.log(submitDate);
  147. try {
  148. const response = await api.put(`/account/${data.id}`, submitDate);
  149. console.log(response);
  150. alert("Cadastro Atualizado com Sucesso");
  151. router.push("/usuarios");
  152. } catch (err) {
  153. console.log(err);
  154. }
  155. };
  156.  
  157. return (
  158. <Form
  159. onSubmit={handleSubmit(onHandleSubmit)}
  160. yupFormSchemaValidation={formSchema}
  161. >
  162. <Input
  163. name="name"
  164. type={"text"}
  165. label="Name"
  166. error={errors.name}
  167. {...register("name")}
  168. />
  169.  
  170. <Input
  171. name="email"
  172. type={"email"}
  173. label="E-mail"
  174. error={errors.email}
  175. {...register("email")}
  176. />
  177. <Input
  178. name="cpf"
  179. type={"text"}
  180. label="CPF"
  181. error={errors.cpf}
  182. mask="cpf"
  183. {...register("cpf")}
  184. />
  185.  
  186. <Input
  187. name="phone"
  188. type={"text"}
  189. label="Número"
  190. mask="phone"
  191. error={errors.phone}
  192. {...register("phone")}
  193. />
  194. <Input
  195. name="country"
  196. type={"text"}
  197. label="País"
  198. error={errors.country}
  199. {...register("country")}
  200. />
  201. <Input
  202. name="zipcode"
  203. type={"text"}
  204. label="CEP"
  205. mask="cep"
  206. error={errors.zipcode}
  207. {...register("zipcode")}
  208. onChange={(e) => handleCEPChange(e)}
  209. />
  210. <Input
  211. name="city"
  212. type={"text"}
  213. label="Cidade"
  214. error={errors.city}
  215. {...register("city")}
  216. />
  217.  
  218. <Input
  219. name="location"
  220. type={"text"}
  221. label="Lugar"
  222. error={errors.location}
  223. {...register("location")}
  224. />
  225. <Input
  226. name="state"
  227. type={"text"}
  228. label="Estado"
  229. error={errors.state}
  230. {...register("state")}
  231. />
  232. <SelectByObjectArray
  233. name="enterpriseId"
  234. {...register("enterpriseId")}
  235. error={errors.enterpriseId}
  236. label="Empresa"
  237. dataLabel={(item) => item.name}
  238. dataValue={(item) => item.id}
  239. dataKey={(item) => item.id}
  240. data={enterprises}
  241. />
  242. </Form>
  243. );
  244. }
  245.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement