Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions src/app/(dashboard)/perfil/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
'use client'

import { ArrowLeftIcon, Loader2 } from 'lucide-react'
import { useEffect, useState } from 'react'

import { getCurrentUser } from '@/actions/users'
import { DashboardContainer } from '@/components/dashboard/container'
import { Avatar } from '@/components/ui/avatar'
import { Button } from '@/components/ui/button'
import { DatePicker } from '@/components/ui/date-picker'
import { Divider } from '@/components/ui/divider'
import { Input } from '@/components/ui/input'
import { NavButton } from '@/components/ui/nav-button'
import { ChangePasswordButton } from '@/modules/profile/change-password-button'
import { ProfileForm } from '@/modules/profile/profile-form'

interface UserProfile {
category?: string
register?: string
avatar_url?: string | null | undefined
entryDate?: string | null | undefined
role: 'specialist'
}

export default function Page() {
const [user, setUser] = useState<UserProfile | null>(null)
const [loading, setLoading] = useState(true)

useEffect(() => {
async function fetchUser() {
try {
const data = await getCurrentUser()

if (!data) {
setUser(null)
return
}

const formattedUser: UserProfile = {
...data,
role: 'specialist',
entryDate: data.created_at
? new Date(data.created_at).toLocaleDateString('pt-BR')
: undefined,
category: (data as UserProfile).category ?? '',
register: (data as UserProfile).register ?? '',
avatar_url: (data as UserProfile).avatar_url ?? '',
}

setUser(formattedUser)
} catch (error) {
console.error('Erro ao carregar dados do usuário:', error)
} finally {
setLoading(false)
}
}

fetchUser()
}, [])

if (loading) {
return (
<div className='flex h-[60vh] items-center justify-center'>
<Loader2 className='text-muted-foreground h-6 w-6 animate-spin' />
</div>
)
}

if (!user) {
return (
<div className='text-muted-foreground flex h-[60vh] items-center justify-center'>
Não foi possível carregar suas informações.
</div>
)
}

const isEspecialist = user.role?.toLowerCase() === 'especialist'

return (
<div className='mx-auto max-w-3xl p-6'>
<DashboardContainer className='flex flex-col gap-6'>
<NavButton
href=''
variant='ghost'
className='text-foreground-soft mr-auto'
>
<ArrowLeftIcon />
Voltar
</NavButton>
<div className='flex gap-3'>
<div className='flex flex-col items-center gap-1'>
<Avatar className='size-16' />
<Button variant='outline'>Escolher</Button>
</div>
<div className='flex flex-col'>
<span>Imagem</span>
<span className='text-foreground-soft text-sm'>
Min 400x400px, PNG ou JPEG
</span>
</div>
<div>
<div>
<label className='text-muted-foreground text-sm'>
Data de entrada
</label>
<DatePicker
value={new Date().toLocaleDateString('pt-BR')}
readOnly
/>
</div>

<div>
<label className='text-muted-foreground text-sm'>
Profissional
</label>
<Input value={user.role ?? ''} readOnly />
</div>

{isEspecialist && (
<>
<div>
<label className='text-muted-foreground text-sm'>
Categoria
</label>
<Input
value={user.category ?? ''}
placeholder='Não informado'
readOnly
/>
</div>

<div>
<label className='text-muted-foreground text-sm'>
Registro
</label>
<Input
value={user.register ?? ''}
placeholder='Não informado'
readOnly
/>
</div>
</>
)}

<div className='pt-4'>
<ChangePasswordButton />
</div>
</div>
</div>
<ProfileForm />
<Divider />
<ChangePasswordButton />
</DashboardContainer>
</div>
)
}
23 changes: 23 additions & 0 deletions src/modules/profile/change-password-button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use client'

import { RectangleEllipsisIcon } from 'lucide-react'
import { useState } from 'react'

import { Dialog, DialogTrigger } from '@/components/ui/dialog'

import { ChangePasswordModal } from './change-password-modal'

export function ChangePasswordButton() {
const [dialogOpen, setDialogOpen] = useState(false)

return (
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogTrigger className='mr-auto' size='sm'>
<RectangleEllipsisIcon />
Alterar senha
</DialogTrigger>

{dialogOpen && <ChangePasswordModal onOpenChange={setDialogOpen} />}
</Dialog>
)
}
120 changes: 120 additions & 0 deletions src/modules/profile/change-password-modal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
'use client'

import { zodResolver } from '@hookform/resolvers/zod'
import { FormProvider, useForm } from 'react-hook-form'
import { z } from 'zod'

import { FormContainer } from '@/components/form/form-container'
import { FormField } from '@/components/form/form-field'
import { PasswordInput } from '@/components/form/password-input'
import { Alert } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import {
DialogClose,
DialogContainer,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'

// TODO: create a shared schema for password change and new password forms
const changePasswordSchema = z
.object({
password: z
.string()
.min(1, 'Insira sua senha')
.min(8, 'Sua senha precisa conter 8 ou mais caracteres')
.regex(/^(?=.*[A-Z])(?=.*\d)/, 'Senha inválida'),
confirmPassword: z.string(),
currentPassword: z.string().min(1, 'Digite sua senha atual'),
})
.refine((data) => data.password === data.confirmPassword, {
message: 'Suas senhas não coincidem',
path: ['confirmPassword'],
})

type ChangePasswordSchema = z.infer<typeof changePasswordSchema>

interface PasswordModalProps {
onOpenChange: (open: boolean) => void
}

export function ChangePasswordModal({ onOpenChange }: PasswordModalProps) {
const methods = useForm<ChangePasswordSchema>({
resolver: zodResolver(changePasswordSchema),
defaultValues: { password: '', confirmPassword: '', currentPassword: '' },
mode: 'onBlur',
})

const isSubmitting = methods.formState.isSubmitting
const errorMessage = methods.formState.errors.root?.message
const success = false

async function onSubmit(data: ChangePasswordSchema) {
console.log('Dados enviados para troca de senha:', data)
onOpenChange(false)
}

return (
<DialogContainer>
<DialogHeader>
<DialogTitle>Alterar senha</DialogTitle>
</DialogHeader>

<FormProvider {...methods}>
<FormContainer onSubmit={methods.handleSubmit(onSubmit)}>
<DialogContent className='flex flex-col gap-8'>
<FormField>
<PasswordInput
name='currentPassword'
label='Senha atual'
placeholder='Digite sua senha atual'
isRequired
/>

<PasswordInput
name='password'
label='Nova senha'
placeholder='Crie uma nova senha'
isRequired
showRequirements
/>

<PasswordInput
name='confirmPassword'
label='Confirmar nova senha'
placeholder='Repita a nova senha'
isRequired
/>
</FormField>

<DialogFooter>
<Button type='submit' loading={isSubmitting} className='flex-1'>
Aplicar alterações
</Button>
<DialogClose
className='flex-1'
disabled={methods.formState.isSubmitting}
>
Cancelar
</DialogClose>
</DialogFooter>

{success && (
<Alert variant='success' className='text-center'>
Senha atualizada com sucesso.
</Alert>
)}

{errorMessage && (
<Alert error className='text-center'>
{errorMessage}
</Alert>
)}
</DialogContent>
</FormContainer>
</FormProvider>
</DialogContainer>
)
}
42 changes: 42 additions & 0 deletions src/modules/profile/profile-form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'use client'

import { FormProvider, useForm } from 'react-hook-form'

import { DateInput } from '@/components/form/date-input'
import { FormContainer } from '@/components/form/form-container'
import { FormField } from '@/components/form/form-field'
import { TextInput } from '@/components/form/text-input'

export function ProfileForm() {
const formMethods = useForm({
defaultValues: {
name: 'Claudio Luiz Oliveira',
entry_date: String(new Date()),
professional: 'Enfermagem',
specialty: 'Enfermagem',
professional_registration: 'COREN-SP 112233',
},
mode: 'onBlur',
})

return (
<FormProvider {...formMethods}>
<FormContainer>
<FormField className='grid grid-cols-2 gap-4'>
<TextInput name='name' label='Nome completo' readOnly />
<DateInput name='entry_date' label='Data de entrada' readOnly />
</FormField>

<FormField className='grid grid-cols-3 gap-4'>
<TextInput name='professional' label='Profissional' readOnly />
<TextInput name='specialty' label='Especialidade' readOnly />
<TextInput
name='professional_registration'
label='Registro profissional'
readOnly
/>
</FormField>
</FormContainer>
</FormProvider>
)
}