Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

97.2 adicionar botao de notificacoes no layout do site 1 #151

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
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,5 @@
- [#54](https://github.com/KozielGPC/championship-platform/issues/54) - Adicionado formulário de criação de campeonato
- [#87](https://github.com/KozielGPC/championship-platform/issues/87) - Adicionado Tela de listagem de minhas equipes
- [#44](https://github.com/KozielGPC/championship-platform/issues/44) - Adicionado Tela de edição de um campeonato
- [#131](https://github.com/KozielGPC/championship-platform/issues/131) - Adicionado Listagem de jogos cadastrados
- [#131](https://github.com/KozielGPC/championship-platform/issues/131) - Adicionado Listagem de jogos cadastrados
- [#97](https://github.com/KozielGPC/championship-platform/issues/97) - Adicionado Tela de Convites
73 changes: 36 additions & 37 deletions backend/api/routers/teams_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,19 +85,17 @@ async def create(data: TeamInput, token: Annotated[str, Depends(oauth2_scheme)])

hashed_password = get_password_hash(data.password)
user = await get_current_user(token)


team_input = Team(name=data.name, password=hashed_password, owner_id=user.id, game_id=data.game_id)

team_input = Team(name=data.name, password=hashed_password, owner_id=user.id, game_id=data.game_id)
session.add(team_input)
session.commit()
session.refresh(team_input)


admin_input = TeamsHasUsers(team_id = team_input.id, user_id = user.id)

admin_input = TeamsHasUsers(team_id=team_input.id, user_id=user.id)
session.add(admin_input)
session.commit()
session.refresh(admin_input)

return team_input


Expand Down Expand Up @@ -160,41 +158,42 @@ async def addUserToTeam(input: AcceptTeamInviteInput, token: Annotated[str, Depe
if notification.reference_user_id != user.id:
raise HTTPException(status_code=401, detail="Notification is not from this user")

if input.accepted == False:
notification.visualized = True
session.commit()
session.refresh(notification)
return notification
player = session.query(User).filter(User.id == notification.reference_user_id).first()
if player == None:
raise HTTPException(status_code=404, detail="Player not found")
team = session.query(Team).filter(Team.id == notification.team_id).first()
if team == None:
raise HTTPException(status_code=404, detail="Team not found")
team_has_user = (
session.query(TeamsHasUsers)
.filter(
TeamsHasUsers.user_id == notification.reference_user_id,
TeamsHasUsers.team_id == notification.team_id,
if input.accepted == True:
player = session.query(User).filter(User.id == notification.reference_user_id).first()
if player == None:
raise HTTPException(status_code=404, detail="Player not found")
team = session.query(Team).filter(Team.id == notification.team_id).first()
if team == None:
raise HTTPException(status_code=404, detail="Team not found")
team_has_user = (
session.query(TeamsHasUsers)
.filter(
TeamsHasUsers.user_id == notification.reference_user_id,
TeamsHasUsers.team_id == notification.team_id,
)
.first()
)
.first()
)
if team_has_user != None:
raise HTTPException(status_code=400, detail="Player is already registered in this Team")
if team_has_user != None:
raise HTTPException(status_code=400, detail="Player is already registered in this Team")

data = TeamsHasUsers(
user_id=notification.reference_user_id,
team_id=notification.team_id,
)
data = TeamsHasUsers(
user_id=notification.reference_user_id,
team_id=notification.team_id,
)

notification.visualized = True
notification.visualized = True

session.add(data)
session.commit()
session.refresh(notification)
session.refresh(data)
session.add(data)
session.commit()
session.refresh(notification)
session.refresh(data)

return notification

return notification
else:
notification.visualized = True
session.commit()
return notification


@router.post(
Expand Down
9 changes: 8 additions & 1 deletion frontend/src/components/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {SignoutButton} from './signoutButton'
import {UserContext} from '../context/UserContext'
import { useContext } from 'react';
import { ExternalLinkIcon } from '@chakra-ui/icons'
import { MdAdd, MdOutlineSupervisorAccount, MdOutlineVideogameAsset } from 'react-icons/md'
import { MdAdd, MdOutlineSupervisorAccount, MdOutlineVideogameAsset,MdNotificationsNone } from 'react-icons/md'

interface LayoutProps {
children: React.ReactNode;
Expand Down Expand Up @@ -54,6 +54,13 @@ const Layout: React.FC<LayoutProps> = ({ children }) => {
</Link>
<Box display="inline-block" textAlign={'left'} textColor='white'>
<Box p='10px'>
<Link
pt='5px'
pb='10px'
display='flex' href='/profile/notifications'>
<Icon boxSize='25px' as={MdNotificationsNone} />
<Flex pl="5px" >Invites</Flex>
</Link>
<Link
pt='5px'
pb='10px'
Expand Down
212 changes: 112 additions & 100 deletions frontend/src/context/UserContext.tsx
Original file line number Diff line number Diff line change
@@ -1,117 +1,129 @@
import { createContext, ReactNode,useEffect,useState } from "react";
import jwt_decode from "jwt-decode"
import {User} from "../interfaces";
import {destroyCookie, parseCookies,setCookie} from 'nookies'
import { createContext, ReactNode, useEffect, useState } from "react";
import jwt_decode from "jwt-decode";
import { User } from "../interfaces";
import { destroyCookie, parseCookies } from "nookies";
import { useRouter } from "next/router";
import { getUserById } from "@/services/users/retrieve";
import { Token } from "../interfaces";
import { getUserById, getMyNotifications } from "@/services/users/retrieve";
import { Token, Notification } from "../interfaces";

type UserContextProps = {
children: ReactNode;
}
children: ReactNode;
};

type UserContextType = {
id: Number;
setId: (id: Number) => void;
username: string;
setUsername: (username: string) => void;
email: string;
setEmail: (email: string) => void;
clearUser: () => void;
signin: (token:string) => void
signout: () => void
}


id: Number;
setId: (id: Number) => void;
username: string;
setUsername: (username: string) => void;
email: string;
setEmail: (email: string) => void;
notifications: Notification[];
setNotifications: (notifications: Notification[]) => void;
clearUser: () => void;
signin: (token: string) => void;
signout: () => void;
getNotifications: () => void;
};

const initialValue = {
id: -1,
setId: () => {},
username: "",
setUsername: () => {},
email: "",
setEmail: () => {},
clearUser: () => {},
signin: () => {},
signout: () => {}
}

id: -1,
setId: () => {},
username: "",
setUsername: () => {},
email: "",
setEmail: () => {},
notifications: [],
setNotifications: () => {},
clearUser: () => {},
signin: () => {},
signout: () => {},
getNotifications: () => {},
};

export const UserContext = createContext<UserContextType>(initialValue);

export const UserProvider = ({ children }: UserContextProps) => {
const router = useRouter();

export const UserProvider = ({ children }: UserContextProps)=>{
const router = useRouter();

const [id, setId] = useState<Number>(initialValue.id);
const [username, setUsername] = useState<string>(initialValue.username);
const [email, setEmail] = useState<string>(initialValue.email);
const [notifications, setNotifications] = useState<Notification[]>([]);

const [id, setId] = useState<Number>(initialValue.id);
const [username, setUsername] = useState<string>(initialValue.username);
const [email, setEmail] = useState<string>(initialValue.email);
const token = parseCookies()["championship-token"];

const token = parseCookies()["championship-token"];

useEffect(
() => {
if(token){
signin(token)
};
},[token]
)

function clearUser(){
setId(-1);
setUsername("");
useEffect(() => {
if (token) {
signin(token);
getNotifications();
}


async function signin(token:string){
try{
setCookie(null, "championship-token", token, {
maxAge: 60 * 60 * 24, // 24 hours
});
const tokenData:Token = jwt_decode(token);
if(!tokenData.id){
throw new Error("Invalid token");
}
const response = await getUserById(tokenData.id.toString());
if(response.status == "error" || !response.data )throw new Error(response.message);

const userData:User = response.data;

setId(userData.id);
setUsername(userData.username);
setEmail(userData.email)
}
catch{
signout()
}
}, [token]);

function clearUser() {
setId(-1);
setUsername("");
}

async function getNotifications() {
const response = await getMyNotifications();
if (response && response.data) {
const notificationsArray: Notification[] = response.data;
if (notificationsArray) {
setNotifications(notificationsArray.reverse());
}
}

function signout(){
destroyCookie(null,'championship-token',{path: '/'});
clearUser();
router.push('/signin');
}

useEffect(() => {
console.log(notifications);
}, [notifications]);

async function signin(token: string) {
try {
const tokenData: Token = jwt_decode(token);
if (!tokenData.id) {
throw new Error("Invalid token");
}
const response = await getUserById(tokenData.id.toString());
if (response.status == "error" || !response.data)
throw new Error(response.message);

const userData: User = response.data;

setId(userData.id);
setUsername(userData.username);
setEmail(userData.email);
} catch {
signout();
}

return (
<UserContext.Provider

value={{
id, setId,
username,setUsername,
email, setEmail,
clearUser,
signin, signout
}}

>
{children}
</UserContext.Provider>
)
}


}

function signout() {
destroyCookie(null, "championship-token", { path: "/" });
clearUser();
router.push("/signin");
}

return (
<UserContext.Provider
value={{
id,
setId,
username,
setUsername,
email,
setEmail,
notifications,
setNotifications,
clearUser,
signin,
signout,
getNotifications,
}}
>
{children}
</UserContext.Provider>
);
};

export default UserContext;



Loading