Skip to content

Commit

Permalink
Merge branch 'main' into feat#172/funcionalidade-de-participar-de-um-…
Browse files Browse the repository at this point in the history
…grupo
  • Loading branch information
NiiMiyo authored Oct 26, 2023
2 parents c4c10db + dc1ea78 commit 72108c0
Show file tree
Hide file tree
Showing 13 changed files with 160 additions and 87 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const AllCategories: React.FC = () => {

useEffect(() => {
UniversimeApi.Capacity.categoryList()
.then(res => setAvailableCategories(res.body.categories));
.then(res => setAvailableCategories(res.body?.categories ?? []));
}, [])

return (
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Capacity/Components/Content/ContentStar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const ContentStar: React.FC = () => {
throw new Error("Categoria não informada");

const response = await UniversimeApi.Capacity.contentsInCategory({id: category});
setContents(response.body.contents);
setContents(response.body?.contents ?? []);
} catch (error) {
console.error('Erro ao buscar os vídeos:', error);
}
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Capacity/Components/FolderBar/AllFolders.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default function AllFolders() {

useEffect(() => {
UniversimeApi.Capacity.folderList()
.then(res => setAvailableFolders(res.body.folders));
.then(res => setAvailableFolders(res.body?.folders ?? []));
}, []);

return (
Expand Down
45 changes: 37 additions & 8 deletions src/pages/Capacity/ManagerCapacity.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import React, { useState, useEffect, useContext } from 'react';
import Select, { MultiValue } from 'react-select';
import React, { useContext, useEffect, useState } from 'react';
import Select from 'react-select';

import UniversimeApi from '@/services/UniversimeApi';
import { Folder, Content , Category, Types} from '@/types/Capacity';
import { AuthContext } from '@/contexts/Auth';
import UniversimeApi from '@/services/UniversimeApi';
import { Category, Content, Folder, Types } from '@/types/Capacity';
import * as SwalUtils from "@/utils/sweetalertUtils";

import './ManagerCapacity.css'
import './ManagerCapacity.css';

const CrudTela: React.FC = () => {
const [contents, setContents] = useState<Content[]>([]);
Expand All @@ -22,6 +22,7 @@ const CrudTela: React.FC = () => {
const [editedDescription, setEditedDescription] = useState('');
const [editedUrl, setEditedUrl] = useState('');
const [editedRating, setEditedRating] = useState(1);
const [editedType, setEditedType] = useState<string>(contentTypes[0])

const [showAddModal, setShowAddModal] = useState(false);
const [newTitle, setNewTitle] = useState('');
Expand Down Expand Up @@ -53,7 +54,7 @@ const CrudTela: React.FC = () => {
const fetchContents = async () => {
try {
const response = await UniversimeApi.Capacity.contentList();
setContents(response.body.contents);
setContents(response.body?.contents ?? []);
} catch (error) {
console.error('Erro ao buscar os conteúdos:', error);
}
Expand All @@ -63,7 +64,7 @@ const CrudTela: React.FC = () => {
try {
const arr: { value: string; label: string; }[] = [];
const response = await UniversimeApi.Capacity.categoryList();
let categoriesArr = response.body.categories;
let categoriesArr = response.body?.categories ?? [];
categoriesArr.map((category: Category) => {
return arr.push({value: category.id, label: category.name});
});
Expand All @@ -77,7 +78,7 @@ const CrudTela: React.FC = () => {
try {
const arr: { value: string; label: string; }[] = [];
const response = await UniversimeApi.Capacity.folderList()
let foldersArr = response.body.folders;
let foldersArr = response.body?.folders ?? [];
foldersArr.map((folder: Folder) => {
return arr.push({value: folder.id, label: folder.name});
});
Expand Down Expand Up @@ -107,12 +108,21 @@ const CrudTela: React.FC = () => {
}
};

const handleEditType = (option : any) =>{
console.log("aa")
console.log(option)
setEditedType(option.value)
console.log(editedType)
console.log(option.value)
}

const handleEditClick = (content: Content) => {
setEditedContent(content);
setEditedTitle(content.title);
setEditedDescription(content.description ?? "");
setEditedUrl(content.url);
setEditedRating(content.rating);
setEditedType(content.type != null ? content.type : "");

const contentCategoriesIds = content.categories;
const arrCategories: { value: string; label: string; }[] = [];
Expand Down Expand Up @@ -145,6 +155,7 @@ const CrudTela: React.FC = () => {
description: editedDescription,
url: editedUrl,
rating: editedRating,
type: editedType,

addCategoriesByIds: categoriesToAddIds,
removeCategoriesByIds: categoriesToRemoveIds,
Expand Down Expand Up @@ -373,6 +384,24 @@ const CrudTela: React.FC = () => {
},
})}
onChange={handleCategoriesOnChange} value={categoriesStateSelected} classNamePrefix="select" noOptionsMessage={()=>"Categoria Não Encontrada"} />
</div>
<div style={{marginTop: '15px'}}>
<label >Tipo:</label>
<Select placeholder= "Selecionar Tipo..." name="tipos" options={contentTypes.map((label) => ({value: label, label: label}))} className="basic-multi-select" theme={(theme) => ({
...theme,
borderRadius: 10,
color: 'black',
colors: {
...theme.colors,
primary25: 'red',
primary: 'blue',
neutral10: 'green',
neutral5: 'black',
neutral0: '#c2c2c2'
},
})}
onChange={handleEditType} value={{value: editedType, label: editedType}} classNamePrefix="select" noOptionsMessage={()=>"Tipo Não Encontrado"} />

</div>
<div style={{marginTop: '15px'}}>
<label>Pastas:</label>
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Capacity/VideoPlayer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const VideoPage: React.FC = () => {
throw new Error("ID do vídeo não foi informado");

const response = await UniversimeApi.Capacity.getContent({id: videoId});
setVideo(response.body.content);
setVideo(response.body?.content ?? null);
} catch (error) {
console.error('Erro ao buscar o vídeo:', error);
}
Expand Down
1 change: 1 addition & 0 deletions src/pages/Group/GroupTabs/GroupPeople/GroupPeople.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ function makePeopleList(people: Profile[], filter: string) {
}

return filteredPeople
.filter(p => !p.user.needProfile)
.map(renderPerson);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@ export function ProfileGroupListing(){
if(profileContext == null)
return null

const groupCount = profileContext.profileListData.groups.length.toLocaleString('pt-BR', {
minimumIntegerDigits: 2,
useGrouping: false,
})

return(
<>
<h1 className="group-name">Meus Grupos</h1>
Expand All @@ -26,8 +21,7 @@ export function ProfileGroupListing(){
profileContext.profileListData.groups.map((group) => {
return group === undefined ? null : (
<Link to={`/group${group.path}`} className="group-item-listing" title={group.name} key={group.id}>
{/* todo: set group url */}
<img src={group.image} alt="" />
<img src={group.image ?? undefined} alt="" />
</Link>
);
})
Expand Down
96 changes: 32 additions & 64 deletions src/pages/Profile/ProfilePage.tsx
Original file line number Diff line number Diff line change
@@ -1,60 +1,69 @@
import { useNavigate, useParams } from "react-router-dom";
import { useContext, useState, useEffect } from "react";
import { Navigate, useLoaderData, useNavigate } from "react-router-dom";
import { useContext, useState, useEffect, useMemo } from "react";

import {
ProfileBio, ProfileGroups, ProfileRecommendSettingsButton,
ProfileSettings, CompetencesSettings, ProfileDiscardChanges, ProfileContext }
from '@/pages/Profile'
ProfileBio, ProfileGroups, ProfileRecommendSettingsButton,
ProfileSettings, CompetencesSettings, ProfileDiscardChanges, ProfileContext,
type ProfileContextType, type ProfilePageLoaderResponse
} from '@/pages/Profile';
import { UniversiModal } from "@/components/UniversiModal";
import * as SwalUtils from "@/utils/sweetalertUtils"
import * as SwalUtils from "@/utils/sweetalertUtils";
import { AuthContext } from "@/contexts/Auth";
import { UniversimeApi } from "@/services/UniversimeApi";
import type { ProfileContextType } from '@/pages/Profile'
import { SelectionBar } from "./SelectionBar/SelectionBar";

import './Profile.css'
import './Profile.css';

export function ProfilePage() {
const auth = useContext(AuthContext);
const navigate = useNavigate();
const { id } = useParams();
const loaderData = useLoaderData() as ProfilePageLoaderResponse;

const [showProfileSettings, setShowProfileSettings] = useState<boolean>(false);
const [showCompetencesSettings, setShowCompetencesSettings] = useState<boolean>(false);
const [showDiscardChanges, setShowDiscardChanges] = useState<boolean>(false);

const [profileContext, setProfileContext] = useState<ProfileContextType>(null);
const profileContext = useMemo<ProfileContextType>(() => ({
accessingLoggedUser: loaderData.accessingLoggedUser,
allCompetenceTypes: loaderData.allCompetenceTypes,
editCompetence: null,
profile: loaderData.profile!,
profileListData: {
achievements: loaderData.profileListData.achievements,
competences: loaderData.profileListData.competences,
folders: loaderData.profileListData.folders,
groups: loaderData.profileListData.groups,
links: loaderData.profileListData.links,
recommendationsReceived: loaderData.profileListData.recommendationsReceived,
recommendationsSend: loaderData.profileListData.recommendationsSend,
},

reloadPage: () => {navigate(location.href)},
}), [loaderData]);

useEffect(() => {
loadAccessedUser();

if (auth.user === null) {
navigate('/login');
}
}, [id, auth.user]);

useEffect(() => {
const user = profileContext?.profile.user;
if (user?.needProfile && user.ownerOfSession) {
navigate("/manage-profile");
}
}, [profileContext?.profile.user])
}, [auth.user]);

if (!profileContext)
return null;

if (profileContext.profile.user.needProfile) {
if (!loaderData.profile || profileContext.profile.user.needProfile) {
SwalUtils.fireModal({
title: "Erro ao acessar perfil",
text: "Esse usuário não criou seu perfil ainda",
}).then(_ => navigate(-1));
return null;
}

if (profileContext.profile.user.needProfile && profileContext.profile.user.ownerOfSession) {
return <Navigate to="/manage-profile"/>
}

return (
<ProfileContext.Provider value={profileContext} >
<div id="profile-page">
{/* todo: color from API */}
<div className="content">
<div id="left-side">
<ProfileBio profile={profileContext.profile} />
Expand Down Expand Up @@ -104,45 +113,4 @@ export function ProfilePage() {
setShowProfileSettings(false);
setShowDiscardChanges(false);
}

async function loadAccessedUser() {
const [profileRes, competenceTypeRes] = await Promise.all([
UniversimeApi.Profile.get({username: id}),
UniversimeApi.CompetenceType.list(),
]);

const profileListData = await loadProfileListData(profileRes.body.profile.id);

setProfileContext({
accessingLoggedUser: profileRes.body?.profile.user.ownerOfSession ?? false,
profile: profileRes.body.profile,
allCompetenceTypes: competenceTypeRes.body.list,
profileListData: profileListData,
editCompetence: null,

reloadPage: loadAccessedUser,
});

discardChanges();
}

async function loadProfileListData(profileId: string) {
const [groupsRes, competencesRes, linksRes, recommendationsRes, foldersRes] = await Promise.all([
UniversimeApi.Profile.groups({profileId}),
UniversimeApi.Profile.competences({profileId}),
UniversimeApi.Profile.links({profileId}),
UniversimeApi.Profile.recommendations({profileId}),
UniversimeApi.Profile.folders({profileId, assignedOnly: true}),
]);

return {
groups: groupsRes.body.groups,
competences: competencesRes.body.competences,
links: linksRes.body.links,
recommendationsSend: recommendationsRes.body.recomendationsSend,
recommendationsReceived: recommendationsRes.body.recomendationsReceived,
folders: foldersRes.body.folders,
achievements: [], // todo: fetch achievements
};
}
}
1 change: 1 addition & 0 deletions src/pages/Profile/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export * from './ProfileSettings/ProfileSettings'
export * from './CompetencesSettings/CompetencesSettings'
export * from './ProfileDiscard/ProfileDiscard'
export * from './ProfileContext'
export * from "./loader";
78 changes: 78 additions & 0 deletions src/pages/Profile/loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import UniversimeApi from "@/services/UniversimeApi";
import type { Achievements } from "@/types/Achievements";
import type { Folder } from "@/types/Capacity";
import type { Competence, CompetenceType } from "@/types/Competence";
import type { Group } from "@/types/Group";
import type { Link } from "@/types/Link";
import type { Profile } from "@/types/Profile";
import type { Recommendation } from "@/types/Recommendation";
import type { LoaderFunctionArgs } from "react-router-dom";

export type ProfilePageLoaderResponse = {
profile: Profile | undefined;
accessingLoggedUser: boolean;
allCompetenceTypes: CompetenceType[];

profileListData: {
groups: Group[];
competences: Competence[];
links: Link[];
recommendationsSend: Recommendation[];
recommendationsReceived: Recommendation[];
achievements: Achievements[];
folders: Folder[];
};
};

export async function ProfilePageLoader(args: LoaderFunctionArgs): Promise<ProfilePageLoaderResponse> {
const username = args.params["id"];
if (username === undefined)
return FAILED_TO_LOAD;

const [fetchProfile, fetchCompetenceTypes] = await Promise.all([
UniversimeApi.Profile.get({username}),
UniversimeApi.CompetenceType.list(),
]);

if (!fetchProfile.success || !fetchProfile.body?.profile || !fetchCompetenceTypes.success || !fetchCompetenceTypes.body?.list)
return FAILED_TO_LOAD;

const [fetchGroups, fetchCompetences, fetchLinks, fetchRecommendations, fetchFolders] = await Promise.all([
UniversimeApi.Profile.groups({username}),
UniversimeApi.Profile.competences({username}),
UniversimeApi.Profile.links({username}),
UniversimeApi.Profile.recommendations({username}),
UniversimeApi.Profile.folders({username, assignedOnly: true}),
]);

return {
profile: fetchProfile.body.profile,
accessingLoggedUser: fetchProfile.body.profile.user.ownerOfSession,
allCompetenceTypes: fetchCompetenceTypes.body.list,

profileListData: {
achievements: [], // todo: fetch achievements,
competences: fetchCompetences.body?.competences ?? [],
folders: fetchFolders.body?.folders ?? [],
groups: fetchGroups.body?.groups ?? [],
links: fetchLinks.body?.links ?? [],
recommendationsReceived: fetchRecommendations.body?.recomendationsReceived ?? [],
recommendationsSend: fetchRecommendations.body?.recomendationsSend ?? [],
},
};
}

const FAILED_TO_LOAD: ProfilePageLoaderResponse = {
profile: undefined,
accessingLoggedUser: false,
allCompetenceTypes: [],
profileListData: {
achievements: [],
competences: [],
folders: [],
groups: [],
links: [],
recommendationsReceived: [],
recommendationsSend: [],
},
};
Loading

0 comments on commit 72108c0

Please sign in to comment.