Created
April 21, 2023 13:58
-
-
Save JamDev0/d5f9af99c72c53501217f74ad6bc86ae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| "use client" | |
| import { gql, useMutation } from "@apollo/client"; | |
| import { Badge } from "@components/Bagde"; | |
| import { Button } from "@components/Button"; | |
| import { ContainerPage } from "@components/ContainerPage"; | |
| import { Divider } from "@components/Divider"; | |
| import { Input } from "@components/Form/Input"; | |
| import { SkeletonLoading } from "@components/SkeletonLoading"; | |
| import { ApiUserInfoFormatServer } from "@contexts/dataTypes"; | |
| import { zodResolver } from "@hookform/resolvers/zod"; | |
| import { useToast } from "@hooks/useToast"; | |
| import { fetcher } from "@utils/swrFetcher"; | |
| import Link from "next/link"; | |
| import { parseCookies } from "nookies"; | |
| import { CaretLeft } from "phosphor-react"; | |
| import { useCallback, useEffect, useState } from "react"; | |
| import { useForm } from "react-hook-form"; | |
| import useSWR from "swr"; | |
| import zod from "zod"; | |
| import { DocumentSection } from "./components/DocumentSection"; | |
| import { InfoSection } from "./components/InfoSection"; | |
| const GET_USER_DOCUMENTS = gql` | |
| query getUserDocuments($id: String!) { | |
| getUser(id: $id) { | |
| userDocuments { | |
| id | |
| approved | |
| comment | |
| document { | |
| name | |
| } | |
| upload { | |
| fileName | |
| id | |
| } | |
| } | |
| } | |
| } | |
| ` | |
| const GET_USER_SPECIALTIES = gql` | |
| query getUserSpecialties($id: String!) { | |
| getUser(id: $id) { | |
| userSpecialties { | |
| id | |
| approved | |
| comment | |
| specialty { | |
| name | |
| } | |
| upload { | |
| fileName | |
| id | |
| } | |
| } | |
| } | |
| } | |
| ` | |
| const UPDATE_USER_DOCUMENT = gql` | |
| mutation updateUserDocument($id: String!, $data: UpdateUserDocumentInput!) { | |
| updateUserDocument(id: $id, data: $data) | |
| } | |
| ` | |
| const UPDATE_USER_SPECIALTY = gql` | |
| mutation updateUserSpecialty($id: String!, $data: UpdateUserSpecialtyInput!) { | |
| updateUserSpecialty(id: $id, data: $data) | |
| } | |
| ` | |
| const VALIDATE_USER = gql` | |
| mutation validateUser($data: ValidateUserInput!) { | |
| validateUser(data: $data) | |
| } | |
| ` | |
| const NOT_VALIDATE_USER = gql` | |
| mutation notValidateUser($data: NotValidateUserInput!) { | |
| notValidateUser(data: $data) | |
| } | |
| ` | |
| const APPROVE_USER = gql` | |
| mutation approveUser($data: ApproveUserInput!) { | |
| approveUser(data: $data) | |
| } | |
| ` | |
| const REJECT_USER = gql` | |
| mutation rejectUser($data: RejectUserInput!) { | |
| rejectUser(data: $data) | |
| } | |
| ` | |
| const COMPLETE_USER = gql` | |
| mutation completeUser($data: CompleteUserInput!) { | |
| completeUser(data: $data) | |
| } | |
| ` | |
| const userApprovalFormSchema = zod.object({ | |
| "user-approval-comment": zod.string().min(5, "Comentário deve ter no mínimo 5 letras."), | |
| }) | |
| type UserApprovalData = zod.infer<typeof userApprovalFormSchema> | |
| export default function UserApproval({ params: { userId } }: {params: { userId: string }}) { | |
| // talvez separar a requisição das informações dos usuários e dos usersInfo | |
| const { data, error, isLoading } = useSWR(['/api/getUserNameUserInfoAndStatusByUserId', { body: userId, method: "POST" }], fetcher); | |
| const userInfo: ApiUserInfoFormatServer[] = (!isLoading && data.info) && JSON.parse(data.info) as ApiUserInfoFormatServer[]; | |
| const userStatusName = !isLoading && data.user.status.name; | |
| const { addToast } = useToast(); | |
| const cookies = parseCookies(); | |
| const userRole = cookies["medical-registration.user.role"]; | |
| const { handleSubmit, register, trigger, formState: { errors } } = useForm<UserApprovalData>({ | |
| resolver: zodResolver(userApprovalFormSchema) | |
| }); | |
| const [approveUser] = useMutation(APPROVE_USER); | |
| const [rejectUser] = useMutation(REJECT_USER); | |
| const [validateUser] = useMutation(VALIDATE_USER); | |
| const [notValidateUser] = useMutation(NOT_VALIDATE_USER); | |
| const [completeUser] = useMutation(COMPLETE_USER); | |
| const [submitAction, setSubmitAction] = useState<"approve" | "validate" | "not validate" | "reject" | null>(null); | |
| console.log({userRole}) | |
| const handleApprovalFormSubmit = useCallback(async function (formData: any) { | |
| const comment = formData["user-approval-comment"]; | |
| console.log(submitAction) | |
| try { | |
| switch(submitAction) { | |
| case "approve": { | |
| const {} = await approveUser({ | |
| variables: { | |
| data: { | |
| userId, | |
| comment, | |
| } | |
| } | |
| }) | |
| addToast({ title: "Usuário aprovado com sucesso!" }); | |
| break; | |
| } | |
| case "reject": { | |
| const {} = await rejectUser({ | |
| variables: { | |
| data: { | |
| userId, | |
| comment, | |
| } | |
| } | |
| }) | |
| addToast({ title: "Usuário rejeitado com sucesso!" }); | |
| break; | |
| } | |
| case "validate": { | |
| const {} = await validateUser({ | |
| variables: { | |
| data: { | |
| userId, | |
| comment, | |
| } | |
| } | |
| }) | |
| addToast({ title: "Usuário não validado com sucesso!" }); | |
| break; | |
| } | |
| case "not validate": { | |
| const {} = await notValidateUser({ | |
| variables: { | |
| data: { | |
| userId, | |
| comment, | |
| } | |
| } | |
| }) | |
| addToast({ title: "Usuário não validado com sucesso!" }); | |
| break; | |
| } | |
| default: { | |
| addToast({ title: "Erro", description: "Não foi definido um tipo de ação", type: "error" }) | |
| } | |
| } | |
| } catch(err) { | |
| console.log({err}); | |
| addToast({ title: "Erro", type: "error" }) | |
| } | |
| }, [submitAction, addToast, approveUser, notValidateUser, rejectUser, userId, validateUser]) | |
| async function handleUserComplete() { | |
| try { | |
| const {} = await completeUser({ | |
| variables: { | |
| data: { | |
| userId, | |
| } | |
| } | |
| }) | |
| addToast({ title: "Usuário finalizado com sucesso!" }); | |
| } catch(err) { | |
| console.log({err}); | |
| addToast({ title: "Erro", type: "error" }); | |
| } | |
| } | |
| async function handlePrintPage() { | |
| if(!userInfo) return ; | |
| const idk = await fetch('/api/userApprovalToPdf', { | |
| method: 'POST', | |
| body: JSON.stringify(userInfo), | |
| }); | |
| } | |
| useEffect(() => { | |
| if(submitAction) { | |
| handleSubmit(handleApprovalFormSubmit)(); | |
| } | |
| }, [submitAction, handleSubmit, handleApprovalFormSubmit]) | |
| return ( | |
| <ContainerPage title={`Aprovação de Cadastro Médico`}> | |
| <div className="flex flex-col gap-4"> | |
| <div className="-mt-4 flex justify-between items-center"> | |
| <nav className="group flex items-start" aria-label="Breadcrumb"> | |
| <Link | |
| href="/users" | |
| className="inline-flex items-center space-x-2 text-sm font-medium text-brand-actions-200 group-hover:text-brand-actions-200/80" | |
| > | |
| <CaretLeft | |
| className="-ml-2 h-5 w-5 text-brand-actions-200 group-hover:text-brand-actions-200/80" | |
| aria-hidden="true" | |
| /> | |
| <span>Voltar para usuários</span> | |
| </Link> | |
| </nav> | |
| { | |
| (!isLoading && userStatusName) && ( | |
| <Badge label={userStatusName} /> | |
| ) | |
| } | |
| </div> | |
| { | |
| isLoading ? ( | |
| <SkeletonLoading skeletons={[1, 3, 3, 1, 3, 3, 1, 3, 3]} /> | |
| ) : ( | |
| <> | |
| { | |
| userInfo ? | |
| <> | |
| { | |
| userInfo.map((info: ApiUserInfoFormatServer) => { | |
| return info.sections.map(section => ( | |
| <InfoSection fields={section.fields} name={section.name} key={section.name} /> | |
| )) | |
| }) | |
| } | |
| <Button onClick={handlePrintPage}>Imprimir</Button> | |
| <DocumentSection name="Especialidades" hasDate={false} query={GET_USER_SPECIALTIES} updateServerFileQuery={UPDATE_USER_SPECIALTY} userId={userId} /> | |
| {/* <DocumentSection name="Privilégios" hasDate={false} /> */} | |
| <DocumentSection name="Documentos Anexados" hasDate={true} query={GET_USER_DOCUMENTS} updateServerFileQuery={UPDATE_USER_DOCUMENT} userId={userId} /> | |
| </> | |
| : | |
| <p>O usuário ainda não inseriu suas informações 😪</p> | |
| } | |
| </> | |
| ) | |
| } | |
| { | |
| userStatusName === "Arquivos enviados" || userStatusName === "Validado" ? ( | |
| <> | |
| <Divider /> | |
| <div> | |
| <h2 className="text-lg font-medium mb-5">Validação de Cadastro</h2> | |
| <form> | |
| <Input type="textarea" {...register("user-approval-comment")} error={errors["user-approval-comment"]} label="Comentário" /> | |
| <div className="flex justify-end gap-x-2 mt-4"> | |
| { | |
| userRole === "CAM" ? | |
| <> | |
| <Button | |
| variant="primary" | |
| onClick={(e) => { | |
| e.preventDefault(); | |
| setSubmitAction("validate"); | |
| }} | |
| > | |
| Validar | |
| </Button> | |
| <Button | |
| variant="delete" | |
| onClick={(e) => { | |
| e.preventDefault(); | |
| setSubmitAction("not validate"); | |
| }} | |
| > | |
| Não Validar | |
| </Button> | |
| </> | |
| : | |
| userRole === "ADMIN" && | |
| <> | |
| <Button | |
| variant="primary" | |
| onClick={(e) => { | |
| e.preventDefault(); | |
| setSubmitAction("approve"); | |
| }} | |
| > | |
| Aprovar | |
| </Button> | |
| <Button | |
| variant="delete" | |
| onClick={(e) => { | |
| e.preventDefault(); | |
| setSubmitAction("reject"); | |
| }} | |
| > | |
| Rejeitar | |
| </Button> | |
| </> | |
| } | |
| </div> | |
| </form> | |
| </div> | |
| </> | |
| ) | |
| : userStatusName === "Incluir informação no Tasy" && | |
| <div className="flex justify-end"> | |
| <Button | |
| variant="primary" | |
| type="button" | |
| onClick={handleUserComplete} | |
| > | |
| Finalizar | |
| </Button> | |
| </div> | |
| } | |
| </div> | |
| </ContainerPage> | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment