Skip to content

Commit

Permalink
Merge pull request #735 from basedosdados/feat/ajust-user-config
Browse files Browse the repository at this point in the history
Feat/ajust user config
  • Loading branch information
AldemirLucas authored Jan 10, 2024
2 parents ac36765 + 7e9f6cd commit dbbf68a
Show file tree
Hide file tree
Showing 9 changed files with 465 additions and 27 deletions.
4 changes: 2 additions & 2 deletions next/components/molecules/Menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -206,15 +206,15 @@ function MenuDrawerUser({ isOpen, onClose}) {
fontWeight="400"
lineHeight="27px"
letterSpacing="0.3px"
>{userData?.username ? userData?.username : "Dadinho"}</Text>
>{userData?.username || ""}</Text>
<Text
color="#6F6F6F"
fontFamily="Ubuntu"
fontSize="14px"
fontWeight="400"
lineHeight="27px"
letterSpacing="0.3px"
>{userData?.email ? userData?.email : "[email protected]"}</Text>
>{userData?.email || ""}</Text>
</Stack>

<Accordion allowToggle width="100%" defaultIndex={0}>
Expand Down
2 changes: 1 addition & 1 deletion next/pages/api/user/activeAccount.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from "axios";

const API_URL= `${process.env.NEXT_PUBLIC_API_URL}/account/activate`
const API_URL= `${process.env.NEXT_PUBLIC_API_URL}/account/account_activate_confirm`

export default async function activeAccount(
id,
Expand Down
28 changes: 28 additions & 0 deletions next/pages/api/user/deleteAccount.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import axios from "axios";
import cookies from "js-cookie";

const API_URL= `${process.env.NEXT_PUBLIC_API_URL}/api/v1/graphql`

export default async function deleteAccount(id) {
let token = cookies.get("token") || ""

try {
const res = await axios({
url: API_URL,
method: "POST",
headers: {
Authorization: `Bearer ${token}`
},
data: {
query: `
mutation {
DeleteAccount (id: "${id}") { errors }
}`
}
})
const data = res.data.data.DeleteAccount
return data
} catch (error) {
console.error(error)
}
}
4 changes: 3 additions & 1 deletion next/pages/api/user/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import updateProfile from "./updateProfile";
import updateUser from "./updateUser";
import updatePassword from "./updatePassword";
import activeAccount from "./activeAccount";
import deleteAccount from "./deleteAccount";

export {
getToken,
Expand All @@ -23,5 +24,6 @@ export {
updateProfile,
updateUser,
updatePassword,
activeAccount
activeAccount,
deleteAccount,
}
80 changes: 70 additions & 10 deletions next/pages/user/[username].js
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,14 @@ import PaymentSystem from "../../components/organisms/PaymentSystem";
import { getUserDataJson, checkUserInfo, cleanUserInfo } from "../../utils";

import {
getUser,
getSimpleToken,
getFullUser,
updateProfile,
refreshToken,
updatePassword,
updateUser
updateUser,
deleteAccount
} from "../api/user";

import Exclamation from "../../public/img/icons/exclamationIcon";
Expand Down Expand Up @@ -508,12 +510,16 @@ const Account = ({ userInfo }) => {
const emailModal = useDisclosure()
const usernameModal = useDisclosure()
const eraseModalAccount = useDisclosure()
const [confirmationWord, setConfirmationWord] = useState("")
const [emailSent, setEmailSent] = useState(false)
const [showPassword, setShowPassword] = useState(true)

const [formData, setFormData] = useState({})
const [formData, setFormData] = useState({username: ""})
const [errors, setErrors] = useState({})
const [isLoading, setIsLoading] = useState(true)

const handleSpaceKey = (e) => {
if(e.key === " ") { e.preventDefault() }
}

const handleInputChange = (e) => {
setFormData((prevState) => ({
Expand All @@ -523,19 +529,43 @@ const Account = ({ userInfo }) => {
}

async function submitUpdate() {
if(formData.username === "") return setErrors({username: "Nome de usuário inválido."})
if(formData.username.includes(" ")) return setErrors({username: "Nome de usuário não pode conter espaços."})

const reg = new RegExp("(?<=:).*")
const [ id ] = reg.exec(userInfo?.id)
const form = {id: id, username: formData.username}

const result = await updateUser(form)

if(result?.errors?.length === 0) return location.reload(true)
if(result?.errors?.length === 0) {
const userData = await getUser(userInfo.email)
cookies.set('userBD', JSON.stringify(userData))
window.open(`/user/${formData.username}`, "_self")
}

if(result?.errors?.length > 0) {
setErrors({username: "Nome de usuário inválido ou já existe uma conta com este nome de usuário."})
}
}

async function eraseAccount(string) {
if(string = "consciente e desejo excluir minha conta") {
const reg = new RegExp("(?<=:).*")
const [ id ] = reg.exec(userInfo.id)

const result = await deleteAccount(id)

if(result?.errors?.length === 0) {
cookies.remove('userBD', { path: '/' })
cookies.remove('token', { path: '/' })
return window.open("/", "_self")
}
}
}

const stringConfirm = confirmationWord === "consciente e desejo excluir minha conta"

return (
<Stack spacing="24px">
<ModalGeneral
Expand Down Expand Up @@ -731,6 +761,7 @@ instruções enviadas no e-mail para completar a alteração.</ExtraInfoTextForm
name="username"
value={formData.username}
onChange={handleInputChange}
onKeyDown={handleSpaceKey}
fontFamily="ubuntu"
height="40px"
fontSize="14px"
Expand All @@ -755,6 +786,7 @@ instruções enviadas no e-mail para completar a alteração.</ExtraInfoTextForm
<ModalGeneral
isOpen={eraseModalAccount.isOpen}
onClose={eraseModalAccount.onClose}
propsModalContent={{minWidth:isMobileMod() ? "" : "620px !important"}}
>
<Stack spacing={0} marginBottom="16px">
<SectionTitle
Expand All @@ -765,13 +797,39 @@ instruções enviadas no e-mail para completar a alteração.</ExtraInfoTextForm
top="34px"
right="26px"
_hover={{backgroundColor: "transparent", color:"#FF8484"}}
onClick={() => {
eraseModalAccount.onClose()
setConfirmationWord("")
}}
/>
</Stack>

<Stack spacing="24px" marginBottom="16px">
<ExtraInfoTextForm fontSize="16px" lineHeight="24px" letterSpacing="0.2px">
Após deletar sua conta, todos os dados serão permanentemente removidos e não poderão ser recuperados.
</ExtraInfoTextForm>

<FormControl isInvalid={!!errors.firstName}>
<FormLabel
color="#252A32"
fontFamily="ubuntu"
letterSpacing="0.2px"
fontSize="16px"
fontWeight="400"
lineHeight="16px"
userSelect="none"
>Por favor, confirme escrevendo: "consciente e desejo excluir minha conta" abaixo.</FormLabel>
<InputForm
value={confirmationWord}
onChange={(e) => setConfirmationWord(e.target.value)}
fontFamily="ubuntu"
height="40px"
fontSize="14px"
borderRadius="16px"
_placeholder={{color: "#A3A3A3"}}
_invalid={{boxShadow:"0 0 0 2px #D93B3B"}}
/>
</FormControl>
</Stack>

<Stack
Expand All @@ -787,19 +845,21 @@ instruções enviadas no e-mail para completar a alteração.</ExtraInfoTextForm
color="#FF8484"
width={isMobileMod() ? "100%" : "fit-content"}
_hover={{transform: "none", opacity: 0.8}}
onClick={() => eraseModalAccount.onClose()}
onClick={() => {
eraseModalAccount.onClose()
setConfirmationWord("")
}}
>
Cancelar
</RoundedButton>

<RoundedButton
borderRadius="30px"
// backgroundColor="#FF8484"
cursor="default"
backgroundColor="#C4C4C4"
backgroundColor={stringConfirm ? "#FF8484" : "#C4C4C4"}
cursor={stringConfirm ? "pointer" : "default"}
width={isMobileMod() ? "100%" : "fit-content"}
// _hover={{transform: "none", opacity: 0.8}}
_hover={{transform: "none"}}
_hover={stringConfirm ? {transform: "none", opacity: 0.8} : {transform: "none", pointerEvents: "none"}}
onClick={() => eraseAccount(confirmationWord)}
>
Deletar
</RoundedButton>
Expand Down
1 change: 0 additions & 1 deletion next/pages/user/activate-account.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
Stack,
} from "@chakra-ui/react";
import { useState, useEffect } from "react";
import { activeAccount } from "../api/user";

import Display from "../../components/atoms/Display";
Expand Down
52 changes: 47 additions & 5 deletions next/pages/user/check-email.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
Text,
} from "@chakra-ui/react";
import { useState, useEffect } from "react";
import axios from "axios";

import Display from "../../components/atoms/Display";
import { isMobileMod } from "../../hooks/useCheckMobile.hook"
Expand All @@ -12,11 +13,50 @@ import { EmailConfirmImage } from "../../public/img/emailImage";

export default function CheckEmail() {
const [email, setEmail] = useState("")
const [count, setCount] = useState(0)
const [forwardingDisabled, setForwardingDisabled] = useState(false)

useEffect(() => {
setEmail(localStorage.getItem("registration_email_bd") || "")
const res = sessionStorage.getItem("registration_email_bd") || ""
if(res === "") return window.open("/", "_self")
setEmail(res)
}, [])

useEffect(() => {
if(count > 0) {
const time = setTimeout(() => {
setCount(count - 1)
}, 1000)
return () => clearTimeout(time)
} else {
setForwardingDisabled(false)
}
}, [count])

async function handleEmailConfirm() {
if(email === "") return null
const API_URL = `${process.env.NEXT_PUBLIC_API_URL}`

const getIdUser = await axios({
url: `${API_URL}/api/v1/graphql`,
method: "POST",
data: {
query: `query { allAccount (email: "${email}") {edges{node{id}}} }`
}
})

const reg = new RegExp("(?<=:).*")
const [ id ] = reg.exec(getIdUser?.data?.data?.allAccount?.edges[0]?.node?.id)

try {
await axios.post(`${API_URL}/account/account_activate/${btoa(id)}/`)
setForwardingDisabled(true)
setCount(60)
} catch (error) {
console.error(error)
}
}

return (
<MainPageTemplate display="flex" justifyContent="center" cleanTemplate>
<Stack
Expand Down Expand Up @@ -79,16 +119,18 @@ export default function CheckEmail() {
</Text>

<Text
cursor="pointer"
_hover={{opacity:0.7}}
cursor={forwardingDisabled ? "default" : "pointer"}
_hover={{opacity:forwardingDisabled ? 1 : 0.7}}
pointerEvents={forwardingDisabled ? "none" : ""}
textAlign="center"
fontFamily="ubuntu"
color="#42B0FF"
color={forwardingDisabled ? "#252A32" : "#42B0FF"}
fontSize="16px"
fontWeight="500"
lineHeight="30px"
letterSpacing="0.2px"
>Reenviar e-mail</Text>
onClick={() => handleEmailConfirm()}
>{forwardingDisabled ? `Espere ${count} segundos...` :"Reenviar e-mail"}</Text>
</Stack>
</Stack>
</MainPageTemplate>
Expand Down
Loading

0 comments on commit dbbf68a

Please sign in to comment.